From riklaunim at gmail.com Thu Jun 1 00:04:41 2006 From: riklaunim at gmail.com (=?ISO-8859-2?Q?piotr_mali=F1ski?=) Date: Wed, 31 May 2006 23:04:41 +0100 Subject: is a wiki engine based on a cvs/svn a good idea? Message-ID: <1f7f7cf70605311504q1bb9660em2a8e6dcefd01e49d@mail.gmail.com> I'm planning to wite a fully featured wiki in Python in one of frameworks. I've seen some notes about wiki/documentation management scripts that use SVN as a data storage/versioning. I've been using SVN a bit but I don't know if it's a good idea to use it in a wiki engine. Pro: versioning / diffs, Cons: you need your own svn/cvs repository, can pyLucene or Xapwrap index this? From vinay_sajip at yahoo.co.uk Thu Jun 1 00:05:13 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 31 May 2006 15:05:13 -0700 Subject: logging In-Reply-To: References: <1148426018.334087.124160@i40g2000cwc.googlegroups.com> <1148577240.250304.116360@j55g2000cwa.googlegroups.com> <1149005605.819519.242350@j55g2000cwa.googlegroups.com> Message-ID: <1149113113.083677.235570@i39g2000cwa.googlegroups.com> ibr at radix50.net wrote: > Hello Vinay, > > Hmm, log1 decides once whether to print an event, and after that it gets > printed in log1 and all its ancestors, regardless of their level? I find > this quite counter-intuitive. I'd instead expect that each logger > decides whether to print an event according to its own level. Could you > give an example why one would want the python behavior? Loggers are hierarchical for a reason - not just randomly named channels. Just as it is generally useful to develop a system by modularising it into subsystems, packages, modules, etc. so it is useful when logging to follow a parallel hierarchy. The audiences for the logging events are orthogonal to the events themselves, and the way the logging module is organised reflects good practice as determined by practical experience over a period of time. The approach you're questioning is not specific to Python - log4j (which inspired Python's logging), and the logging built into Java 1.4, also work this way. Practically, this makes configuration a lot simpler; if I want to log everything to console, I just attach a handler to the root logger, and I never have to worry about attaching to every single logger. (Logger names are generally not cast in stone - I might break down a module's logic into smaller pieces and thus introduce new logger names to describe events in the refactored module. I certainly don't want to change my logging configuration every time I refactor my code.) May I suggest you review the log4j documentation to get a better exposition of the principles which govern the design of such logging systems. From ippisl at gmail.com Thu Jun 1 00:29:11 2006 From: ippisl at gmail.com (ippisl at gmail.com) Date: 31 May 2006 15:29:11 -0700 Subject: OT: Search for python in Norway In-Reply-To: <1149108651.205786.99100@j55g2000cwa.googlegroups.com> References: <1149108651.205786.99100@j55g2000cwa.googlegroups.com> Message-ID: <1149114551.858491.231890@i40g2000cwc.googlegroups.com> your search for python refers for python=snake. you should look for "python programming". cyberco wrote: > Although the climate wouldn't make you think so, but searching for > python is hot in Norway: > > http://www.google.com/trends?q=python&ctab=1&geo=all&date=all > > I wonder what the explanation could be. > > Btw: Java seems to be all the rage in India :) > http://www.google.com/trends?q=java&ctab=1&geo=all&date=all From gdamjan at gmail.com Thu Jun 1 00:33:54 2006 From: gdamjan at gmail.com (Damjan) Date: Thu, 01 Jun 2006 00:33:54 +0200 Subject: is a wiki engine based on a cvs/svn a good idea? References: Message-ID: <447e19d2$0$15788$14726298@news.sunsite.dk> > I'm planning to wite a fully featured wiki in Python in one of > frameworks. I've seen some notes about wiki/documentation management > scripts that use SVN as a data storage/versioning. Cool > I've been using SVN a bit but I don't know if it's a good idea to use > it in a wiki engine. Pro: versioning / diffs, Cons: you need your own > svn/cvs repository, can pyLucene or Xapwrap index this? You can certanly index the svn checkout if nothing else. -- damjan From bdesth.quelquechose at free.quelquepart.fr Thu Jun 1 04:14:20 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Jun 2006 04:14:20 +0200 Subject: is a wiki engine based on a cvs/svn a good idea? In-Reply-To: References: Message-ID: <447e1dfc$0$20866$626a54ce@news.free.fr> piotr maliski a ?crit : > I'm planning to wite a fully featured wiki in Python Then first have a look at both moinmoin and Trac. Good part of the job is already done. > in one of > frameworks. I've seen some notes about wiki/documentation management > scripts that use SVN as a data storage/versioning. > I've been using SVN a bit but I don't know if it's a good idea to use > it in a wiki engine. This has been discussed for Trac, cf: http://projects.edgewall.com/trac/wiki/TighterSubversionIntegration http://projects.edgewall.com/trac/wiki/WhySQLite > Pro: versioning / diffs, > Cons: you need your own svn/cvs repository, > can pyLucene or Xapwrap index this? From jcb at iteris.com Thu Jun 1 00:53:30 2006 From: jcb at iteris.com (Metalone) Date: 31 May 2006 15:53:30 -0700 Subject: ctypes pointers and SendMessage Message-ID: <1149116010.351538.258990@g10g2000cwb.googlegroups.com> I would like to call windll.user32.SendMessageA(hwnd, win32con.WM_COMMAND, wParam, lParam) where lParam represents a pointer to an object. And also convert this pointer back to an object reference inside of wnd_proc def wnd_proc(hwnd, msg, wParam, lParam): So something like this: class X(Structure): def __init__(self, x): self.v = x x = X(1) windll.user32.SendMessageA(hwnd, WM_COMMAND, 4000, addressof(x)) def wnd_proc(hwnd, msg, wParam, lParam): if msg == WM_COMMAND and wParam == 4000): x = X.from_address(lParam) print x.v Unfortunately, this does not work. Also to my surprise the following does not work: x1 = X(1) x2 = X.from_address(addressof(x1)) addressof(x1) == addressof(x2) --> True but x2.v --> 'object has no attribute v' x1.v --> 1 Also this does not work as I expect. p = pointer(x) p[0].v --> 'object has no attribute v'. What am I doing wrong? From mateus.justino at gmail.com Thu Jun 1 01:09:32 2006 From: mateus.justino at gmail.com (mateus) Date: 31 May 2006 16:09:32 -0700 Subject: Variable name has a typo, but code still works. Why? References: <1149082236.151844.99600@u72g2000cwu.googlegroups.com> <1149083447.370584.197070@f6g2000cwb.googlegroups.com> Message-ID: <1149116972.201718.155660@h76g2000cwa.googlegroups.com> Well, one by one I checked for the presence of both sessions and session in the globals dictionary (within showReport(), but outside of the loops). Neither one of them existed previously, thus and I received the exception about them not being found: File "/home/mjpl/hct/repository/hct/tutoo.py", line 219, in loadNext self.loadStage(self.cur+1) File "/home/mjpl/hct/repository/hct/tutoo.py", line 195, in loadStage self.stageFrame.show() File "/home/mjpl/hct/repository/hct/stages/resultadoframe/resultadoframe.py", line 17, in show self.listView.showReport() File "/home/mjpl/hct/repository/hct/widgets/deviceview.py", line 54, in showReport print globals()['session'] KeyError: 'session' So, I tried using other variable names for the outer and inner loops with the only difference of one letter. I then got the expected message about the variable name not being encountered. I returned the variable names to 'sessions' and 'session' respectively, and I got the same error about the name 'session' not being founded. I can only assume that there was some type of cache problem. Could it have been in the .pyc? I thought that was recompiled every time a .py is run/set to be interpreted. I'm sure I got that last sentence wrong. hwiechers at gmail.com wrote: > mateus wrote: > > print "hello world" > > > > I have a nested loop where the outer loop iterates over key value pairs > > of a dictionary and the inner loop iterates over a list each list of > > which is a mapped value from the dictionary > > > > def showReport(self): > > for dev, sessions in self.logger.items(): > > for tree in session: > > self.addTestItem(self, tree) > > > > What I don't understand is why this executes w/o any problems when > > "sessions" was spelled as plural (sessionS) while later being spelled > > in the singular (session). > > > > Is there some type of name resolution of local variables where Python > > makes assumptions? > > I've never heard of a rule disregarding ending 's'es and I really doubt > one > exists. > > Are you sure session isn't a global variable? You can check using > globals(). From jmcmonagle at velseis.com.au Thu Jun 1 01:19:00 2006 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Thu, 01 Jun 2006 09:19:00 +1000 Subject: Tkinter question In-Reply-To: <9583ed900605310837q57eb8b76h6ac5e9c435bf885@mail.gmail.com> References: <9583ed900605310837q57eb8b76h6ac5e9c435bf885@mail.gmail.com> Message-ID: <1149117540.26711.9.camel@kuepper.vels-int.com.au> On Wed, 2006-05-31 at 11:37 -0400, david brochu jr wrote: > I am trying to create a GUI that will display a new window with > information about my program when the user clicks on the info button > (a green "i" bitmap). So far all I can get my program to do is show > the new window (using Toplevel() ) when the program loads, not when > the user presses the information bitmap. I think it has something to > do with my command for the information button. Anyone have any ideas > or have a GOOD resource that they could point me to? > Indeed the problem is to do with your command for the information button. Keeping it in your coding style, change it to: self.info_bttn["command"] = self.info Regards, John > -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From go at away.com Thu Jun 1 01:24:01 2006 From: go at away.com (3rdshiftcoder) Date: Wed, 31 May 2006 23:24:01 GMT Subject: beginner: using parameter in functions Message-ID: hi- i am having trouble using parameter values in my function and to be honest a little trouble with member variables. i am trying to pass in the argument 'd' representing delete. what the code will do is if it is 'd' it will make a delete query template string. if it is an 'i' then insert query etc. this is the results of my attempt to print the contents of the parameter values. <__main__.getQryStr instance at 0x01151D50> ('d',) me mad (and on a side note if i dont include the *args i get an invalid number of parameters supplied message.) why is it returning the value in this format ('d',) ? i cant get x == d i guess that value 'd' is stored in a tuple and i'd like to get it out of there. so basically the function returns nope as it stands python is sure different from other languages i have used. thanks for any help, jim class getQryStr: def __init__(self,op): print op self.x = 'd' def returnStr(x,*args): print '%s %s me mad' % (x,args) if x == 'd': s = Template("delete from columndef where tblid = $tblid and colname = $colname") else: return 'nope' #this else is just for illustration and testing d = dict(tblid=t.tblid.getText(), colname=t.colName.getText()) print s.substitute(d) return s def delqry(self): createfldobj = getQryStr('d') s = createfldobj.returnStr('d') From eurleif at ecritters.biz Thu Jun 1 01:28:09 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 31 May 2006 19:28:09 -0400 Subject: TSV to HTML In-Reply-To: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> References: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> Message-ID: <447e268a$0$3699$4d3efbfe@news.sover.net> Brian wrote: > I was wondering if anyone here on the group could point me in a > direction that would expllaing how to use python to convert a tsv file > to html. I have been searching for a resource but have only seen > information on dealing with converting csv to tsv. Specifically I want > to take the values and insert them into an html table. import csv from xml.sax.saxutils import escape def tsv_to_html(input_file, output_file): output_file.write('\n') for row in csv.reader(input_file, 'excel-tab'): output_file.write('') for col in row: output_file.write('' % escape(col)) output_file.write('\n') output_file.write('
%s
') Usage example: >>> from cStringIO import StringIO >>> input_file = StringIO('"foo"\t"bar"\t"baz"\n' ... '"qux"\t"quux"\t"quux"\n') >>> output_file = StringIO() >>> tsv_to_html(input_file, output_file) >>> print output_file.getvalue()
foobarbaz
quxquuxquux
From tjreedy at udel.edu Thu Jun 1 01:34:52 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 31 May 2006 19:34:52 -0400 Subject: OT: Search for python in Norway References: <1149108651.205786.99100@j55g2000cwa.googlegroups.com> <1149114551.858491.231890@i40g2000cwc.googlegroups.com> Message-ID: wrote in message news:1149114551.858491.231890 at i40g2000cwc.googlegroups.com... > your search for python refers for python=snake. It combines both, but spikes are definately snakey. > you should look for "python programming". I tried that, and Google missed the Nokia article it found with python alone. Also, South Africa and India are hottest countries with their normalization. http://www.google.com/trends?q=python+programming&ctab=1&geo=all&date=all tjr From pydecker at gmail.com Thu Jun 1 01:35:37 2006 From: pydecker at gmail.com (Peter Decker) Date: Wed, 31 May 2006 19:35:37 -0400 Subject: using import * with GUIs? In-Reply-To: References: Message-ID: On 5/31/06, John Salerno wrote: > I guess if I'm going to learn a GUI, I might as well jump right into > wxPython from the beginning. May I recommend that you take a look at the Dabo project? While they have a full application framework for creating database applications, you can easily just use the dabo.ui module, which wraps wxPython. This eliminates most of the C++ cruft that wxPython inherited from wxWidgets, and makes for a much more Pythonic experience. I worked with wxPython for a couple of years, and looked at Dabo based on a recommendation on the wxPython list. Since then, I haven't written a single app using raw wxPython; I use the dabo.ui module for all my GUI applications. It gives you all the advantages of wxPython, but it just works better. -- # p.d. From jmcmonagle at velseis.com.au Thu Jun 1 01:57:13 2006 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Thu, 01 Jun 2006 09:57:13 +1000 Subject: beginner: using parameter in functions In-Reply-To: References: Message-ID: <1149119833.26711.12.camel@kuepper.vels-int.com.au> On Wed, 2006-05-31 at 23:24 +0000, 3rdshiftcoder wrote: > hi- > > i am having trouble using parameter values in my function and to be honest a > little trouble with > member variables. i am trying to pass in the argument 'd' representing > delete. > what the code will do is if it is 'd' it will make a delete query template > string. > if it is an 'i' then insert query etc. > > this is the results of my attempt to print the contents of the parameter > values. > <__main__.getQryStr instance at 0x01151D50> ('d',) me mad > > > (and on a side note if i dont include the *args i get an invalid number of > parameters supplied message.) > why is it returning the value in this format ('d',) ? > i cant get x == d > i guess that value 'd' is stored in a tuple and i'd like to get it out of > there. > > so basically the function returns nope as it stands > > python is sure different from other languages i have used. > > thanks for any help, > jim > Try, the following: class getQryStr: def __init__(self,op): print op self.x = 'd' def returnStr(self, *args): print '%s %s me mad' % (self.x,args) if self.x == 'd': s = Template("delete from columndef where tblid = $tblid and colname = $colname") else: return 'nope' #this else is just for illustration and testing d = dict(tblid=t.tblid.getText(), colname=t.colName.getText()) print s.substitute(d) return s Regards, John -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From sjmachin at lexicon.net Thu Jun 1 02:21:05 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 01 Jun 2006 10:21:05 +1000 Subject: beginner: using parameter in functions In-Reply-To: References: Message-ID: <447e32f3@news.eftel.com> On 1/06/2006 9:24 AM, 3rdshiftcoder wrote: > hi- > > i am having trouble using parameter values in my function and to be honest a > little trouble with > member variables. i am trying to pass in the argument 'd' representing > delete. > what the code will do is if it is 'd' it will make a delete query template > string. > if it is an 'i' then insert query etc. > > this is the results of my attempt to print the contents of the parameter > values. > <__main__.getQryStr instance at 0x01151D50> ('d',) me mad Exactly right, first parameter is the object itself, second parameter is a 1-tuple of the supplied args. See more explanation below. > > > (and on a side note if i dont include the *args i get an invalid number of > parameters supplied message.) > why is it returning the value in this format ('d',) ? > i cant get x == d > i guess that value 'd' is stored in a tuple and i'd like to get it out of > there. No, 'd' is stored as the value of the attribute you've named "x". One of the main points of the whole OO caper is that objects have attributes -- please see later remarks about the tutorial. > > so basically the function returns nope as it stands > > python is sure different from other languages i have used. > > thanks for any help, > jim > > > class getQryStr: > def __init__(self,op): > print op > self.x = 'd' You probably meant self.x = op > def returnStr(x,*args): Like the first (__init__) method, this should have the mandatory "self" argument, plus *one* other arg .. *if* you need it. It's not apparent why you are calling the constructor *and* the returnStr method *each* with 'd'. > > print '%s %s me mad' % (x,args) > if x == 'd': Here x is the object that you have created. The first argument to a method is the object itself, and is conventionally named "self". It must be declared in the method itself def amethod(self, arg1, arg2): but is supplied automatically when you invoke it anobj.amethod('foo', 42) [snip] Please consider working your way through the Python tutorial http://docs.python.org/tut/node11.html and/or one of the free e-books e.g. http://www.byteofpython.info/ At the end of this post is a modified version of your script which shows what is going on under normal expected usage. HTH, John 8<=== demo script === C:\junk>type use_self.py class getQryStr: def __init__(self, op): print '__init__ ... op:%r' % op self.x = op def returnStr(self, arg): print 'returnStr ... self.x:%r arg:%r' % (self.x, arg) return '=%s=%s=' % (self.x, arg) obj = getQryStr('blah') print '__main__ ... obj.x:%r' % obj.x s = obj.returnStr('yadda') print '__main__ ... s:%r' % s 8<=== output from demo script === C:\junk>use_self.py __init__ ... op:'blah' __main__ ... obj.x:'blah' returnStr ... self.x:'blah' arg:'yadda' __main__ ... s:'=blah=yadda=' 8<=== end === From go at away.com Thu Jun 1 02:34:35 2006 From: go at away.com (3rdshiftcoder) Date: Thu, 01 Jun 2006 00:34:35 GMT Subject: beginner: using parameter in functions References: Message-ID: thanks very much John! so i can have self as function parameter as well as in a method. that allowed me to use properties to retrieve the value set in the constructor. i just changed the function return statement and it worked. i was working along these lines but couldnt get it up and running as fast as you posted. templating sure is a great way to create dynamic query strings. very cool so far but still lots to learn. thanks again, jim "John McMonagle" wrote in message news:mailman.6388.1149119924.27775.python-list at python.org... > On Wed, 2006-05-31 at 23:24 +0000, 3rdshiftcoder wrote: >> hi- >> >> i am having trouble using parameter values in my function and to be >> honest a >> little trouble with >> member variables. i am trying to pass in the argument 'd' representing >> delete. >> what the code will do is if it is 'd' it will make a delete query >> template >> string. >> if it is an 'i' then insert query etc. >> >> this is the results of my attempt to print the contents of the parameter >> values. >> <__main__.getQryStr instance at 0x01151D50> ('d',) me mad >> >> >> (and on a side note if i dont include the *args i get an invalid number >> of >> parameters supplied message.) >> why is it returning the value in this format ('d',) ? >> i cant get x == d >> i guess that value 'd' is stored in a tuple and i'd like to get it out of >> there. >> >> so basically the function returns nope as it stands >> >> python is sure different from other languages i have used. >> >> thanks for any help, >> jim >> > > > Try, the following: > > class getQryStr: > def __init__(self,op): > print op > self.x = 'd' > def returnStr(self, *args): > > print '%s %s me mad' % (self.x,args) > if self.x == 'd': > s = Template("delete from columndef where tblid = $tblid and > colname = $colname") > else: > return 'nope' #this else is just for illustration and > testing > > d = dict(tblid=t.tblid.getText(), colname=t.colName.getText()) > > print s.substitute(d) > > return s > > > Regards, > > John > > > > -- > This message has been scanned for viruses and > dangerous content by MailScanner, and is > believed to be clean. > From rpdooling at gmail.com Thu Jun 1 02:31:40 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 31 May 2006 17:31:40 -0700 Subject: Variable name has a typo, but code still works. Why? References: <1149082236.151844.99600@u72g2000cwu.googlegroups.com> <1149083447.370584.197070@f6g2000cwb.googlegroups.com> <1149116972.201718.155660@h76g2000cwa.googlegroups.com> Message-ID: <1149121900.895494.24360@y43g2000cwc.googlegroups.com> > I can only assume that there was some type of cache problem. Could it > have been in the .pyc? I thought that was recompiled every time a .py > is run/set to be interpreted. If you are on Windows, check your PATHEXT environment variable and make sure that .py is listed ahead of .pyc and any other .py? See, e.g., a bug in earlier versions of ActiveState distrib http://tinyurl.com/qok9v rd "Electricity is actually made up of extremely tiny particles called electrons, that you cannot see with the naked eye unless you have been drinking."--Dave Barry From noway at sorry.com Thu Jun 1 02:50:37 2006 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 01 Jun 2006 00:50:37 GMT Subject: struct: type registration? Message-ID: Hello, given the ongoing work on struct (which I thought was a dead module), I was wondering if it would be possible to add an API to register custom parsing codes for struct. Whenever I use it for non-trivial tasks, I always happen to write small wrapper functions to adjust the values returned by struct. An example API would be the following: ============================================ def mystring_len(): return 20 def mystring_pack(s): if len(s) > 20: raise ValueError, "a mystring can be at max 20 chars" s = (s + "\0"*20)[:20] s = struct.pack("20s", s) return s def mystring_unpack(s): assert len(s) == 20 s = struct.unpack("20s", s)[0] idx = s.find("\0") if idx >= 0: s = s[:idx] return s struct.register("S", mystring_pack, mystring_unpack, mystring_len) # then later foo = struct.unpack("iilS", data) ============================================ This is only an example, any similar API which might fit better struct internals would do as well. As shown, the custom packer/unpacker can call the original pack/unpack as a basis for their work. I guess an issue with this could be the endianess problem: it would make sense if, when called recursively, struct.pack/unpack used by the default the endianess specified by the external format string. -- Giovanni Bajo From george.sakkis at gmail.com Thu Jun 1 03:03:59 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 31 May 2006 18:03:59 -0700 Subject: ideas for programs? References: Message-ID: <1149123839.683480.178380@y43g2000cwc.googlegroups.com> Brandon McGinty wrote: > Hi, > I've been learning python for the past couple of months and writing misc > scripts here and there, along with some web apps. > I'm wondering if anyone has ideas of programs I might try my hand at making? > I'd appreciate it if they don't use images, because I'm blind. One ambitious idea would be to implement (a subset of) MDX, the Multi-Dimensional eXpressions language (http://msdn2.microsoft.com/en-us/library/ms145506.aspx). If you have any java experience, there is an open source implementation in it so you don't have to start from scratch: http://mondrian.sourceforge.net. George From DustanGroups at gmail.com Thu Jun 1 03:12:51 2006 From: DustanGroups at gmail.com (Dustan) Date: 31 May 2006 18:12:51 -0700 Subject: Downloading and Displaying an Image from the Internet in Tkinter Message-ID: <1149124371.337732.3650@f6g2000cwb.googlegroups.com> The title pretty much says it all. What is the easiest way in Tkinter to display an image from the internet given the URL? From bnblazer at gmail.com Thu Jun 1 03:48:30 2006 From: bnblazer at gmail.com (Brian) Date: 31 May 2006 18:48:30 -0700 Subject: TSV to HTML In-Reply-To: <447e268a$0$3699$4d3efbfe@news.sover.net> References: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> <447e268a$0$3699$4d3efbfe@news.sover.net> Message-ID: <1149126509.984331.306530@h76g2000cwa.googlegroups.com> First let me say that I appreciate the responses that everyone has given. A friend of mine is a ruby programmer but knows nothing about python. He gave me the script below and it does exactly what I want, only it is in Ruby. Not knowing ruby this is greek to me, and I would like to re-write it in python. I ask then, is this essentially what others here have shown me to do, or is it in a different vein all together? Code: class TsvToHTML @@styleBlock = <<-ENDMARK ENDMARK def TsvToHTML::wrapTag(data,tag,modifier = "") return "<#{tag} #{modifier}>" + data + "\n" end # wrapTag def TsvToHTML::makePage(source) page = "" rowNum = 0 source.readlines.each { |record| row = "" record.chomp.split("\t").each { |field| # replace blank fields with   field.sub!(/^$/," ") # wrap in TD tag, specify style row += wrapTag(field,"td","class=\"" + ((rowNum == 0)?"cellTitle":"cell#{rowNum % 2}") + "\"") } rowNum += 1 # wrap in TR tag, add row to page page += wrapTag(row,"tr") + "\n" } # finish page formatting [ [ "table","cellpadding=0 cellspacing=0 border=0" ], "body","html" ].each { |tag| page = wrapTag(@@styleBlock,"head") + page if tag == "html" page = wrapTag(page,*tag) } return page end # makePage end # class # stdin -> convert -> stdout print TsvToHTML.makePage(STDIN) From yinglcs at gmail.com Thu Jun 1 03:52:41 2006 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 31 May 2006 18:52:41 -0700 Subject: Save data to a file thru a http connection In-Reply-To: <447e0221$1@nntp0.pdx.net> References: <1149100667.391141.222280@i40g2000cwc.googlegroups.com> <447e0221$1@nntp0.pdx.net> Message-ID: <1149126761.726836.73360@y43g2000cwc.googlegroups.com> Scott, Can you please tell me which chapter of the tutorial that you are referring to http://docs.python.org/tut/tut.html? The only chapter that I find about http is chapter 10.7, but it does not have the example that you are referring to Scott David Daniels wrote: > yinglcs at gmail.com wrote: > > I am new to python. I read an example here about how to fetch data thru > > a HTTP connection: > > http://diveintopython.org/http_web_services/review.html, > > > > My question is how can i save the data to a file after reading it from > > a http connection. > > Do the tutorial and this and many other things will become clear. > > Instead of just "print sometext", do something like: > ... > f = open('filename', 'w') > ... > print >>f, sometext > ... (possibly more prints like the above). > f.close() > > --Scott David Daniels > scott.daniels at acm.org From sjmachin at lexicon.net Thu Jun 1 04:06:15 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 01 Jun 2006 12:06:15 +1000 Subject: struct: type registration? In-Reply-To: References: Message-ID: <447e4b98$1@news.eftel.com> On 1/06/2006 10:50 AM, Giovanni Bajo wrote: > Hello, > > given the ongoing work on struct (which I thought was a dead module), I was > wondering if it would be possible to add an API to register custom parsing > codes for struct. Whenever I use it for non-trivial tasks, I always happen to > write small wrapper functions to adjust the values returned by struct. > > An example API would be the following: > > ============================================ > def mystring_len(): > return 20 > > def mystring_pack(s): > if len(s) > 20: > raise ValueError, "a mystring can be at max 20 chars" > s = (s + "\0"*20)[:20] Have you considered s.ljust(20, "\0") ? > s = struct.pack("20s", s) > return s I am an idiot, so please be gentle with me: I don't understand why you are using struct.pack at all: |>>> import struct |>>> x = ("abcde" + "\0" * 20)[:20] |>>> x 'abcde\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' |>>> len(x) 20 |>>> y = struct.pack("20s", x) |>>> y == x True |>>> Looks like a big fat no-op to me; you've done all the heavy lifting yourself. > > def mystring_unpack(s): > assert len(s) == 20 > s = struct.unpack("20s", s)[0] Errrm, g'day, it's that pesky idiot again: |>>> z = struct.unpack("20s", y)[0] |>>> z 'abcde\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' |>>> z == y == x True > idx = s.find("\0") > if idx >= 0: > s = s[:idx] > return s Have you considered this: |>>> z.rstrip("\0") 'abcde' |>>> ("\0" * 20).rstrip("\0") '' |>>> ("x" * 20).rstrip("\0") 'xxxxxxxxxxxxxxxxxxxx' > > struct.register("S", mystring_pack, mystring_unpack, mystring_len) > > # then later > foo = struct.unpack("iilS", data) > ============================================ > > This is only an example, any similar API which might fit better struct > internals would do as well. > > As shown, the custom packer/unpacker can call the original pack/unpack as a > basis for their work. I guess an issue with this could be the endianess > problem: it would make sense if, when called recursively, struct.pack/unpack > used by the default the endianess specified by the external format string. From sjmachin at lexicon.net Thu Jun 1 04:14:45 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 01 Jun 2006 12:14:45 +1000 Subject: Save data to a file thru a http connection In-Reply-To: <1149126761.726836.73360@y43g2000cwc.googlegroups.com> References: <1149100667.391141.222280@i40g2000cwc.googlegroups.com> <447e0221$1@nntp0.pdx.net> <1149126761.726836.73360@y43g2000cwc.googlegroups.com> Message-ID: <447E4D95.4040805@lexicon.net> On 1/06/2006 11:52 AM, yinglcs at gmail.com wrote: > Scott, > > Can you please tell me which chapter of the tutorial that you are > referring to http://docs.python.org/tut/tut.html? > > The only chapter that I find about http is chapter 10.7, but it does > not have the example that you are referring to Break the problem up into two parts: (1) Get some data. You've achieved that, using HTTP. (2) Save some data to a file. Doesn't matter *how* you got the data. You need to know how to open a file for writing and how to write to it and how to close it when you've finished. Look for the section in the tutorial about *files*. Better still, read *all* the sections in the tutorial :-) > > Scott David Daniels wrote: >> yinglcs at gmail.com wrote: >>> I am new to python. I read an example here about how to fetch data thru >>> a HTTP connection: >>> http://diveintopython.org/http_web_services/review.html, >>> >>> My question is how can i save the data to a file after reading it from >>> a http connection. >> Do the tutorial and this and many other things will become clear. >> >> Instead of just "print sometext", do something like: >> ... >> f = open('filename', 'w') >> ... >> print >>f, sometext >> ... (possibly more prints like the above). >> f.close() >> >> --Scott David Daniels >> scott.daniels at acm.org > From go at away.com Thu Jun 1 04:21:57 2006 From: go at away.com (3rdshiftcoder) Date: Thu, 01 Jun 2006 02:21:57 GMT Subject: beginner: using parameter in functions References: <447e32f3@news.eftel.com> Message-ID: <9bsfg.240$Cw3.174@trndny01> "John Machin" wrote in message news:447e32f3 at news.eftel.com... thanks for the help. it is really appreciated. i am going to do some more reading in the next couple of days. jim From nkammah at yahoo.fr Thu Jun 1 05:08:30 2006 From: nkammah at yahoo.fr (kepioo) Date: 31 May 2006 20:08:30 -0700 Subject: How to access the content of notepad with Python? Message-ID: <1149131310.763870.29250@j55g2000cwa.googlegroups.com> Hi, I have a software running on my computer that really looks like notepad ( same interface, different name). I need to write a script that will capture the content of this software --> the text written inside. Is it possible using win32 libs? any clue? Thanks! From rupole at hotmail.com Thu Jun 1 05:35:50 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 31 May 2006 23:35:50 -0400 Subject: Try/Except for ADSI GetObject References: Message-ID: <1149132664_5885@sp6iad.superfeed.net> "LittlePython" wrote in message news:al5fg.9877$ho6.1459 at trnddc07... >I am a little confused on why I can not detect an object that does not exist > with a try and except. If I understand ADSI correctly from what I have read > you do not create these objects but rather get them. They already exist. I > believe if I do the equivalent in VB I would generate an error when I try to > get an object that does not exist (can not find). I don't get an error when doing a GetObject in VBS for a nonexistent domain. What have I done wrong? > I have included the function below that works in ever respect but detecting > incorrect NT Domain Names (objects that do not exist) . Any tips, insight or > comments would be welcome by this newbie. You should be able to use win32net.NetValidateName to verify that the domain exists before doing any more operations. hth Roger ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From rupole at hotmail.com Thu Jun 1 05:37:55 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 31 May 2006 23:37:55 -0400 Subject: WinPops References: Message-ID: <1149132789_5889@sp6iad.superfeed.net> "Hari Sekhon" wrote in message news:mailman.6230.1148640634.27775.python-list at python.org... > Hi, > Is there a way of sending winpops (Windows Pop-Up / Net Send messages) in python? > > Perhaps some library or something that I can use under both Windows and Linux? > > Hari On Windows, you can use win32net.NetMessageBufferSend. Roger ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From Bulkan at gmail.com Thu Jun 1 05:47:32 2006 From: Bulkan at gmail.com (placid) Date: 31 May 2006 20:47:32 -0700 Subject: How to access the content of notepad with Python? In-Reply-To: <1149131310.763870.29250@j55g2000cwa.googlegroups.com> References: <1149131310.763870.29250@j55g2000cwa.googlegroups.com> Message-ID: <1149133652.024007.220150@i39g2000cwa.googlegroups.com> kepioo wrote: > Hi, > > I have a software running on my computer that really looks like notepad > ( same interface, different name). I need to write a script that will > capture the content of this software --> the text written inside. > Dont know about win32, but if you want an easy solution then save the text you want to capture and then read it via Python! From Bulkan at gmail.com Thu Jun 1 05:52:49 2006 From: Bulkan at gmail.com (placid) Date: 31 May 2006 20:52:49 -0700 Subject: Is device Connected Windows? Message-ID: <1149133969.191368.224660@h76g2000cwa.googlegroups.com> Hi all, Just wondering is there a way (not brute force) to check if a usb storage device is connected? The brute force method im talking about is doing a os.path.isdir() or os.path.isdir() on all the drive letters from A-Z, because you know that this usb device contains a folder called A or file called foo.txt. Thanks in Advance From timr at probo.com Thu Jun 1 06:42:22 2006 From: timr at probo.com (Tim Roberts) Date: Thu, 01 Jun 2006 04:42:22 GMT Subject: TIming References: Message-ID: WIdgeteye wrote: >On Tue, 30 May 2006 16:15:44 +1000, John McMonagle wrote: > >> Tim Roberts is right. As you are on linux, I suggest you investigate the >> at command - very user friendly and not at all complicated. > >I have been using Slackware for over 10 years I know all about the >commands on the OS. > >If you guys don't have an answer to the question just say so. But don't >give me suggestions on how to use an OS I have been using most likely >longer than 90% of the people using linux today. > >This is the comp.lang.python news group not the linux news group. If I >didn't want to write the Python code and I wanted to use the OS commands >instead I would. Utter nonsense. If someone posted on comp.lang.python that they wanted to know how to write a DMA-based PCI driver in Python, I am sure as heck going to tell them that there are better tools for the job and better newsgroups for the question. >Python is cross platform. Linux is not. I intend to release the software >to the general public someday when it is done. I want it cross platform. Windows also has an "at" command. However, you are not going to be able to write a television-based application that is cross platform. The video tools are just too different. >BTW in the time it took me NOT to get an answer for my question in this so >called Python NG, I figured it out for myself. That's almost always the case with newsgroups. They are NOT a real-time medium. >This PYTHON NG blows to high heaven. Whats worse, the answers I got were >most likely from people who know SQUAT about Python scripting. That's why >they gave me such lame fucking answers. We did not give you "lame fucking answers". We gave you solutions to the problem you posed. If the problem statement wasn't clear enough, that isn't our fault. >Idiots. It takes one to know one. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jstroud at ucla.edu Thu Jun 1 06:51:25 2006 From: jstroud at ucla.edu (James Stroud) Date: Wed, 31 May 2006 21:51:25 -0700 Subject: ideas for programs? In-Reply-To: References: Message-ID: A digest of the major points summarizing the consensus opinion: Thomas Bartkus wrote: > Python is your tool to put your expertise on a computer. Skill with Python, > or any computer language for that matter, counts for little. And akameswaran at gmail.com wrote: > As far as employment. I come from a java background, and that seems > the only language I can pay the bills with:). Particularly in the US > paid python jobs are hard to come by. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From webraviteja at gmail.com Thu Jun 1 07:00:08 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 31 May 2006 22:00:08 -0700 Subject: How to access the content of notepad with Python? In-Reply-To: <1149131310.763870.29250@j55g2000cwa.googlegroups.com> References: <1149131310.763870.29250@j55g2000cwa.googlegroups.com> Message-ID: <1149138007.952375.22560@u72g2000cwu.googlegroups.com> > I have a software running on my computer that really looks like notepad > ( same interface, different name). I need to write a script that will > capture the content of this software --> the text written inside. > > Is it possible using win32 libs? any clue? http://www.openqa.org/pywinauto/ The example on their home page is in fact how to automate Notepad. I am sure you can work from there. From paddy3118 at netscape.net Thu Jun 1 07:31:15 2006 From: paddy3118 at netscape.net (Paddy) Date: 31 May 2006 22:31:15 -0700 Subject: TSV to HTML References: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> <447e268a$0$3699$4d3efbfe@news.sover.net> <1149126509.984331.306530@h76g2000cwa.googlegroups.com> Message-ID: <1149139875.503669.57900@h76g2000cwa.googlegroups.com> Brian wrote: > First let me say that I appreciate the responses that everyone has > given. > > A friend of mine is a ruby programmer but knows nothing about python. > He gave me the script below and it does exactly what I want, only it is > in Ruby. Not knowing ruby this is greek to me, and I would like to > re-write it in python. > > I ask then, is this essentially what others here have shown me to do, > or is it in a different vein all together? > Leif's Python example uses the csv module which understands a lot more about the peculiarities of the CSV/TSV formats. The Ruby example prepends a block. The Ruby example splits each line to form a table row and each row on tabs, to form the cells. The thing about TSV/CSV formats is that their is no one format. you need to check how your TSV creator generates the TSV file: Does it put quotes around text fields? What kind of quotes? How does it represent null fields? Might you get fields that include newlines? - P.S. I'm not a Ruby programmer, just read the source ;-) From anatoli.barski at googlemail.com Thu Jun 1 09:04:26 2006 From: anatoli.barski at googlemail.com (anatoli.barski at googlemail.com) Date: 1 Jun 2006 00:04:26 -0700 Subject: how to print newline in xml? In-Reply-To: References: <1149023930.292203.152540@u72g2000cwu.googlegroups.com> Message-ID: <1149145466.190011.146250@i39g2000cwa.googlegroups.com> Thank you for a possible solution, but it's not what I'm looking for, cause something like would look quite similar... for big elements like robot it would be ok to use comment as a child of element - but imagine I'd like to comment transformation: I wouldn't like to make this element parent of a description - it is not nice - I have lots of such elements. It is important that a user after having a glance at the document is able to quickly find and change some values. I don't want to bother him with reading documentation nodes - but if he needs - they should be there... the only possible solution I can think of would be: > How about: > > > armar3 > : > : > > > XML editor + xpath makes this way more easier to use by humans compared to > normal comments. Also, if you declare several of comment elements > (summary, description, author, etc.) you can auto generate documentation > etc. > > -- > John MexIT: http://johnbokma.com/mexit/ > personal page: http://johnbokma.com/ > Experienced programmer available: http://castleamber.com/ > Happy Customers: http://castleamber.com/testimonials.html From laura at voipro.nl Thu Jun 1 09:08:32 2006 From: laura at voipro.nl (Laura van Tuin) Date: Thu, 1 Jun 2006 09:08:32 +0200 Subject: Python Programmerwanted Message-ID: Python programmer wanted Our fast-growing team of software developers is currently looking for a (junior) Python programmer to assist in the development of our core technology. To extend the core team we're looking for a talented individual with specifically: thorough knowledge of Linux and Python experience with Zope and Plone is recommended knowledge of VoIP including open standards such as SIP at least HBO/academic education fluent in English, preferably also in Dutch Working at Voipro is about team work and sharing in the success of the company. Our compensation is highly competitive and our organization has room for entrepreneurial professionals with experience in the telecommunication and technology markets. Professionalism, relationship management, and creativity are our core values and inherent strengths in our team. Voipro extends its founders tradition of delivering technological solutions in the technology and telecommunication markets successfully. Our fast growing team is motivated to deliver success to its investors, customers, and partners. If you are interested please contact Voipro Nederland BV - Laura van Tuin +31 20 7884000 / laura at voipro.nl -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-list/attachments/20060601/a31f9ee4/attachment.htm From kapil.sundrani at wipro.com Thu Jun 1 09:08:25 2006 From: kapil.sundrani at wipro.com (kapil.sundrani at wipro.com) Date: Thu, 1 Jun 2006 12:38:25 +0530 Subject: problem with file upload... Message-ID: <865660148009AD47BBBFD82BFED3A92601E785A1@BLR-EC-MBX04.wipro.com> I have a problem in uploading a file. The input tag looks like and the form tag looks like.
But still after form submission I don't get the file data. Debugging shows that the input field is being taken as a MinifieldStorage instead of FieldStorage. Thanks in advance for any help :-) Regards, Kapil 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: http://mail.python.org/pipermail/python-list/attachments/20060601/1b8bad49/attachment.html From grflanagan at yahoo.co.uk Thu Jun 1 09:32:44 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 1 Jun 2006 00:32:44 -0700 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> Message-ID: <1149147164.012044.66960@u72g2000cwu.googlegroups.com> Ben Finney wrote: [snip] > > Please don't write C in Python. The 'for' statement allows iteration > directly over a sequence, no need to maintain an index. Also, the > modulus operator is called for with your cycling of the pile index. > > pile_index = 0 > for card in deck: > piles[pile_index].append(card) > pile_index = (pile_index + 1) % numpiles > no need to maintain an index ;-) piles = [ list() for _ in range(n) ] for i, card in enumerate(deck): piles[i % numpiles].append(card) Gerard From pemboa at gmail.com Thu Jun 1 09:36:06 2006 From: pemboa at gmail.com (Arthur Pemberton) Date: Thu, 1 Jun 2006 02:36:06 -0500 Subject: Best way to do data source abstraction Message-ID: <16de708d0606010036j65d64096m5a4dcb0c04c5656a@mail.gmail.com> What is the best way to do data source abtraction? For example have different classes with the same interface, but different implementations. I was thinking of almost having classA as my main class, and have classA dynamically "absorb" classFood into to based on the extension of the input file received by classA. But this doesn't seem possible. Please advise. Thank you. -- To be updated... From bignose+hates-spam at benfinney.id.au Thu Jun 1 09:52:00 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 01 Jun 2006 17:52:00 +1000 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149147164.012044.66960@u72g2000cwu.googlegroups.com> Message-ID: <87bqtdz527.fsf@benfinney.id.au> "Gerard Flanagan" writes: > Ben Finney wrote: > > pile_index = 0 > > for card in deck: > > piles[pile_index].append(card) > > pile_index = (pile_index + 1) % numpiles > > > > no need to maintain an index ;-) > > piles = [ list() for _ in range(n) ] > for i, card in enumerate(deck): > piles[i % numpiles].append(card) That's a matter of style. I prefer what I wrote, since I've given an explicit name to the calculation you're doing inside the [] operator; that way, anyone reading the code knows *why* the calculation is done in this particular case. If, of course, the index was a simple increment-by-one each time, your 'enumerate' usage would be clearer. -- \ "We spend the first twelve months of our children's lives | `\ teaching them to walk and talk and the next twelve years | _o__) telling them to sit down and shut up." -- Phyllis Diller | Ben Finney From __peter__ at web.de Thu Jun 1 09:52:25 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jun 2006 09:52:25 +0200 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149147164.012044.66960@u72g2000cwu.googlegroups.com> Message-ID: Gerard Flanagan wrote: > Ben Finney wrote: >> pile_index = 0 >> for card in deck: >> piles[pile_index].append(card) >> pile_index = (pile_index + 1) % numpiles >> > > no need to maintain an index ;-) > > piles = [ list() for _ in range(n) ] > for i, card in enumerate(deck): > piles[i % numpiles].append(card) No need to maintain an index ;-) piles = [deck[start::numpiles] for start in range(numpiles)] Assuming deck is a list, that is. Peter From nicogrubert at gmail.com Thu Jun 1 10:00:49 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Thu, 01 Jun 2006 10:00:49 +0200 Subject: os.popen3() - how to close cmd window automatically? In-Reply-To: References: Message-ID: <447E9EB1.6090506@gmail.com> > replace console=[... by windows=[... in your setup.py Works perfect. Thank you, Rony! From michele.petrazzo at TOGLIunipex.it Thu Jun 1 10:04:28 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 01 Jun 2006 08:04:28 GMT Subject: ctypes pointers and SendMessage In-Reply-To: <1149116010.351538.258990@g10g2000cwb.googlegroups.com> References: <1149116010.351538.258990@g10g2000cwb.googlegroups.com> Message-ID: Metalone wrote: > I would like to call > windll.user32.SendMessageA(hwnd, win32con.WM_COMMAND, wParam, lParam) > where > lParam represents a pointer to an object. and the others? > > And also convert this pointer back to an object reference inside of > wnd_proc > def wnd_proc(hwnd, msg, wParam, lParam): > > So something like this: > class X(Structure): > def __init__(self, x): > self.v = x > > What am I doing wrong? > I don't know if you want to create a "real" C structure. If yes this is the wrong method: >>> class X(Structure): ... _fields_ = [("x", c_int), ] ... >>> x1 = X(1) >>> x1.x 1 >>> http://starship.python.net/crew/theller/ctypes/tutorial.html -> Structures and Unions Michele From sybrenUSE at YOURthirdtower.com.imagination Thu Jun 1 10:02:34 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 1 Jun 2006 10:02:34 +0200 Subject: Best way to do data source abstraction References: Message-ID: Arthur Pemberton enlightened us with: > What is the best way to do data source abtraction? That depends on your data source. For files, file-like objects are an abstraction. For databases there is PEP 249. > I was thinking of almost having classA as my main class, and have > classA dynamically "absorb" classFood into to based on the extension > of the input file received by classA. But this doesn't seem > possible. You don't explain the most important part - "absorb". What does that mean? And what does it mean to have classA "almost" as your main class? Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From andyrsmith at googlemail.com Thu Jun 1 10:14:28 2006 From: andyrsmith at googlemail.com (andyrsmith at googlemail.com) Date: 1 Jun 2006 01:14:28 -0700 Subject: Best Python Editor References: Message-ID: <1149149668.113003.142940@j55g2000cwa.googlegroups.com> If we could go back to emacs again for a second... I'm still using emacs but have been playing with a few other ide's (wing, komodo + pydev) are the ones i've given a go recently. However I still end up coming back to emacs for what I consider to be emacs mode's piece of 'killer functionality', (well, killer for me anyway :-) ) which is the C-c C-c shortcut to send the contents of the current buffer to a running interpreter. (i.e. one long-running interpreter that behaves as if the entire buffer had been retyped). Not very useful on first glance, but compared with what I've found to be the 'standard' run-this-script-in-a-new-interpreter function the other ides seem to have it has the following advantages. 1/ No wait for another interpreter to start up 2/ It lets you do the following in a script which lends itself to a much tighter edit-run loop ... try: runOnce except: doSomePainfulDataGathering() runOnce = 1 doSomeLessPainfulDataProcessing() i.e. the painful part will only get executed once, so its cost can be amortized over multiple runs of the script. Of course care has to be taken to ensure the script doesn't violate causality (i.e. code can creep in that depends on variables that haven't yet been initialized) , but in practice I haven't found it to be much of a problem. (And can be checked quickly by simply killing the running interpreter and starting a fresh one). Anyway, the question is whether or not any of the other IDE's support this style of working, (I say I'd *played* with some of them but can't swear I'd dug through every nook and cranny of all of their menu options) Cheers, A. From yairchu at gmail.com Thu Jun 1 10:16:14 2006 From: yairchu at gmail.com (yairchu at gmail.com) Date: 1 Jun 2006 01:16:14 -0700 Subject: Best Python Editor References: Message-ID: <1149149773.999940.13500@i40g2000cwc.googlegroups.com> > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. WingIDE is very good. It gives very nice completions and has a nice thing called "source assistant" that shows the help of the function you're standing on and etc. But I don't think it's open-source and freei if that bothers you http://www.wingware.com/ Another good one is idlespoon. this one is open-source and freei http://idlespoon.python-hosting.com/ From tim.golden at viacom-outdoor.co.uk Thu Jun 1 10:23:06 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 1 Jun 2006 09:23:06 +0100 Subject: Is device Connected Windows? Message-ID: [placid] | Just wondering is there a way (not brute force) to check if a usb | storage device is connected? Hmmm. How do you identify "a usb storage device" to know that it is or isn't connected? You can certainly do something useful with wmi. eg, import wmi c = wmi.WMI () for usb_disk in c.Win32_DiskDrive (InterfaceType="USB"): print usb_disk.Caption print usb_disk.PNPDeviceID Now, assuming that the PNPDeviceID is unique enough for your purpose, you could probably do something with it to keep hold of it and then check later whether the same device is still inserted. One possibility is to use a WMI watcher to spot when devices are removed: import wmi c = wmi.WMI () usb_watcher = c.watch_for ( notification_type="Deletion", wmi_class="Win32_DiskDrive", delay_secs=2, InterfaceType="USB" ) while True: usb_removed = usb_watcher () # can optionally timeout print usb_removed.PNPDeviceID Lots of other possibilities, a polling loop, two watchers, one for creation one for deletion etc. Depends exactly what your requirements are. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From ray_usenet at yahoo.com Thu Jun 1 10:28:37 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Jun 2006 01:28:37 -0700 Subject: How do you practice Python? Message-ID: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> In our field, we don't always get to program in the language we'd like to program. So... how do you practice Python in this case? Say you're doing J2EE right now. How do you practice Python to keep your skills sharp? I liked Python Challenge, but there were too many PIL there, something that I doubt I'll ever use, so there must be a better way. Thanks Ray From ray_usenet at yahoo.com Thu Jun 1 10:38:17 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Jun 2006 01:38:17 -0700 Subject: How do you practice programming? Message-ID: <1149151097.741307.79440@f6g2000cwb.googlegroups.com> OK, maybe I shoot a more general question to the group since there are so many great programmers here: how do you practice your craft? I do it in the following way: 1. Set aside 30 minutes to 1 hour a day to read up on the latest development, be it about the tool I'm using, the language, or the platform, or the framework, etc. 2. Once every 1-2 months, go to Amazon, and look for the book with the best reviews in a particular technology (e.g.: SQL Cookbook, etc.) 3. Practice something that I may not be using currently at work, but always good to know, e.g.: I try to be reasonably competent in at least 2 major current languages--right now it's Java and C#, and 1 dynamic language, which has been Python for quite some time. SQL is always useful, so I try to practice that, especially the more complex queries involving group bys and window function, etc. How do you do your practice? From anthra.norell at tiscalinet.ch Thu Jun 1 10:51:57 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Thu, 1 Jun 2006 10:51:57 +0200 Subject: losing handles of open files Message-ID: <000c01c68558$a48a9680$0201a8c0@mcuf7> Hi If a piece of code exits with an exception before it closes an open file, that file seems to remain locked, which is real pain in the butt if I develop a file in parallel with a piece of code. Is there a way to close such lost files short of starting a new session? Frederic -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-list/attachments/20060601/dfdf4eef/attachment.htm From onurb at xiludom.gro Thu Jun 1 10:50:53 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 10:50:53 +0200 Subject: How do you practice Python? In-Reply-To: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> Message-ID: <447eaae0$0$20867$636a55ce@news.free.fr> Ray wrote: > In our field, we don't always get to program in the language we'd like > to program. So... how do you practice Python in this case? Say you're > doing J2EE right now. Hopefully not ! > How do you practice Python to keep your skills > sharp? How *would* I do ? Well, perhaps I'd use Jython ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ray_usenet at yahoo.com Thu Jun 1 10:56:54 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Jun 2006 01:56:54 -0700 Subject: How do you practice Python? In-Reply-To: <447eaae0$0$20867$636a55ce@news.free.fr> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <447eaae0$0$20867$636a55ce@news.free.fr> Message-ID: <1149152214.215907.31800@i39g2000cwa.googlegroups.com> bruno at modulix wrote: > > In our field, we don't always get to program in the language we'd like > > to program. So... how do you practice Python in this case? Say you're > > doing J2EE right now. > > Hopefully not ! I am :-( > > How do you practice Python to keep your skills > > sharp? > > How *would* I do ? Well, perhaps I'd use Jython ? Um, I mean, what if you have to use something other than Python/Jython/IronPython? :) How do you keep your Python skill sharp? > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From onurb at xiludom.gro Thu Jun 1 10:55:23 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 10:55:23 +0200 Subject: How do you practice programming? In-Reply-To: <1149151097.741307.79440@f6g2000cwb.googlegroups.com> References: <1149151097.741307.79440@f6g2000cwb.googlegroups.com> Message-ID: <447eabee$0$19567$636a55ce@news.free.fr> Ray wrote: > OK, maybe I shoot a more general question to the group since there are > so many great programmers here: how do you practice your craft? I'm certainly not one of them, but... (snip) > How do you do your practice? > 1/ programming 2/ programming 3/ lurking here, reading posts and sometimes trying to answer, reading source code of the oss apps/frameworks I'm working with, searching practical solutions in the cookbook etc 4/ programming -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ray_usenet at yahoo.com Thu Jun 1 11:00:28 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Jun 2006 02:00:28 -0700 Subject: How do you practice programming? In-Reply-To: <447eabee$0$19567$636a55ce@news.free.fr> References: <1149151097.741307.79440@f6g2000cwb.googlegroups.com> <447eabee$0$19567$636a55ce@news.free.fr> Message-ID: <1149152428.348192.106970@h76g2000cwa.googlegroups.com> bruno at modulix wrote: > 1/ programming > 2/ programming > 3/ lurking here, reading posts and sometimes trying to answer, reading > source code of the oss apps/frameworks I'm working with, searching > practical solutions in the cookbook etc > 4/ programming Yeah, but that's what most of us are doing too, we are programmers after all. But you know, it's like a boxer cannot get better just by going into a lot of fights, he needs good instruction from a good coach. So what would you do? (I guess it's your number #3 above). > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From onurb at xiludom.gro Thu Jun 1 11:20:22 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 11:20:22 +0200 Subject: Best way to do data source abstraction In-Reply-To: References: Message-ID: <447eb1ca$0$27292$626a54ce@news.free.fr> Arthur Pemberton wrote: > What is the best way to do data source abtraction? For example have > different classes with the same interface, but different > implementations. > > I was thinking of almost having classA as my main class, and have > classA dynamically "absorb" classFood into to based on the extension > of the input file received by classA. But this doesn't seem possible. Could you explain more accurately what you're trying to do ? FWIW, it seems that a plain old factory function would do ? class DatasourceAbstraction(object): """ base class, factoring common stuff """ # implementation here class JpegFile(DatasourceAbstraction): # .... class PdfFile(DatasourceAbstraction): # .... class TxtFile(DatasourceAbstraction): # .... # etc _classes = { 'jpg' : JpegFile, 'txt' : TxtFile, 'pdf' : PdfFile, # etc.. } def Datasource(inputfile): ext = os.path.splitext(inputfile) return _classes.get(ext, )(inputfile) The fact that there's no 'new' keyword in Python, and that classes are callable objects acting as factories means that it's a no-brainer to use a plain function (eventually disguised as a Class - the client code just doesn't care !-) as factory... Now if I missed the point, please give more explanations... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From petr at tpc.cz Thu Jun 1 12:05:21 2006 From: petr at tpc.cz (Petr Jakes) Date: 1 Jun 2006 03:05:21 -0700 Subject: what is the reasonable (best?) Exception handling strategy? Message-ID: <1149156321.440828.95150@g10g2000cwb.googlegroups.com> I am a little bit confused by all possibilities for exceptions handling in Python (probably because I am not skilled enough??) I did try to search trough this list and reading Python tutorial about Errors and Exceptions but didn't find some "general" answer about exception handling policy (strategy). In the following example each row can IMHO raise an exception (if the Firebird service is not running for example, if the database is corrupted etc.). Do I have to write "try/except" clause on each row? Or to write try/except block (function) where to handle (on one place) all exceptions expected in the program code is a good idea? Or do I have to write own "exception hook"? What about unexpected exceptions? :( def databasExample(h,d,u,p): import kinterbasdb; kinterbasdb.init(type_conv=200) con = kinterbasdb.connect(host=h, database=d,user=u, password=p) cur = con.cursor() insertStatement = cur.prep("some SQL statement......") cur.executemany(insertStatement, ListOfValues) con.commit() cur.close() Generally I am trying to find some general advices or suggestions about exception handling more than the specific answers to the above mentioned code example. Regards Petr Jakes From ullrich at math.okstate.edu Thu Jun 1 12:16:33 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Thu, 01 Jun 2006 05:16:33 -0500 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> <1149105576.321676.131600@j55g2000cwa.googlegroups.com> Message-ID: <69ft72516amvri3up8fop5rf543s6en1lg@4ax.com> On Wed, 31 May 2006 23:05:14 +0200, Fredrik Lundh wrote: >Roger Miller wrote: > >> DSU seems like a lot of trouble to go through in order to use an O(n >> log n) sorting algorithm to do what can be done in O(N) with a few >> lines of code. The core code of random.shuffle() shows how easy it is >> to do it right: >> >> for i in reversed(xrange(1, len(x))): >> # pick an element in x[:i+1] with which to exchange x[i] >> j = int(random() * (i+1)) >> x[i], x[j] = x[j], x[i] > >easy to do it right? you know, the main reason for adding shuffle to >the standard library was that its way too easy to get it wrong. Heh. And I thought it was just me. _I_ find it easy to get the "limits" wrong, even though I have the idea of the algorithm perfectly straight. Better yet is the number of times I've seen a simply wrong algorithm posted online: >see e.g. this thread: http://tinyurl.com/ppgzq Good example, because we know that EMF is not dumb. I've seen the same algorithm many times - the best example is http://www.cigital.com/papers/download/developer_gambling.php Some poker site posted the simply-wrong algorithm in an effort to convince people that their decks were properly shuffled! ************************ David C. Ullrich From bucodi at yahoo.fr.invalid Thu Jun 1 12:19:30 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Thu, 01 Jun 2006 12:19:30 +0200 Subject: Best Python Editor References: Message-ID: I have to admit that I'm testing eclipse with pydev at the moment, and it looks realy good Rony > Hi, > > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. > > Thank You, > -Manoj- > > > "SASKEN RATED Among THE Top 3 BEST COMPANIES TO WORK FOR IN INDIA - SURVEY > 2005 conducted by the BUSINESS TODAY - Mercer - TNS India" > > SASKEN BUSINESS DISCLAIMER > This message may contain confidential, proprietary or legally Privileged > information. In case you are not the original intended Recipient of the > message, you must not, directly or indirectly, use, Disclose, distribute, > print, or copy any part of this message and you are requested to delete it > and inform the sender. Any views expressed in this message are those of the > individual sender unless otherwise stated. Nothing contained in this message > shall be construed as an offer or acceptance of any offer by Sasken > Communication Technologies Limited ("Sasken") unless sent with that express > intent and with due authority of Sasken. Sasken has taken enough precautions > to prevent the spread of viruses. However the company accepts no liability > for any damage caused by any virus transmitted by this email -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From max at alcyone.com Thu Jun 1 12:25:23 2006 From: max at alcyone.com (Erik Max Francis) Date: Thu, 01 Jun 2006 03:25:23 -0700 Subject: shuffling elements of a list In-Reply-To: <69ft72516amvri3up8fop5rf543s6en1lg@4ax.com> References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> <1149105576.321676.131600@j55g2000cwa.googlegroups.com> <69ft72516amvri3up8fop5rf543s6en1lg@4ax.com> Message-ID: David C. Ullrich wrote: > Good example, because we know that EMF is not dumb. I've seen > the same algorithm many times - the best example is ... Man, an error made _six years ago_ and people are still bringing it up ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis The purpose of man's life is not happiness but worthiness. -- Felix Adler From bnblazer at gmail.com Thu Jun 1 12:29:35 2006 From: bnblazer at gmail.com (Brian) Date: 1 Jun 2006 03:29:35 -0700 Subject: TSV to HTML In-Reply-To: References: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> <447e268a$0$3699$4d3efbfe@news.sover.net> <1149126509.984331.306530@h76g2000cwa.googlegroups.com> Message-ID: <1149157775.490474.173970@y43g2000cwc.googlegroups.com> Dennis, Thank you for that response. Your code was very helpful to me. I think that actually seeing how it should be done in Python was a lot more educational than spending hours with trial and error. One question (and this is a topic that I still have trouble getting my arms around). Why is the text in STYLEBLOCK tripple quoted? Thanks again, Brian From grflanagan at yahoo.co.uk Thu Jun 1 12:37:10 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 1 Jun 2006 03:37:10 -0700 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149147164.012044.66960@u72g2000cwu.googlegroups.com> Message-ID: <1149158230.815685.167850@i39g2000cwa.googlegroups.com> Peter Otten wrote: > Gerard Flanagan wrote: > > > Ben Finney wrote: > > >> pile_index = 0 > >> for card in deck: > >> piles[pile_index].append(card) > >> pile_index = (pile_index + 1) % numpiles > >> > > > > no need to maintain an index ;-) > > > > piles = [ list() for _ in range(n) ] > > for i, card in enumerate(deck): > > piles[i % numpiles].append(card) > > No need to maintain an index ;-) > > piles = [deck[start::numpiles] for start in range(numpiles)] I am humbled :-) Gerard From duncan.booth at invalid.invalid Thu Jun 1 12:44:29 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Jun 2006 10:44:29 GMT Subject: what is the reasonable (best?) Exception handling strategy? References: <1149156321.440828.95150@g10g2000cwb.googlegroups.com> Message-ID: Petr Jakes wrote: > I am a little bit confused by all possibilities for exceptions handling > in Python (probably because I am not skilled enough??) I did try to > search trough this list and reading Python tutorial about Errors and > Exceptions but didn't find some "general" answer about exception > handling policy (strategy). It depends on what you are actually able to do about the exception. If you can recover from it meaningfully then you may want to handle it near the place it is thrown. If all you can do is abort the entire program then you handle that at the outermost level of the program. > > In the following example each row can IMHO raise an exception (if the > Firebird service is not running for example, if the database is > corrupted etc.). If a service isn't running that sounds pretty fatal. Handle it at the outer levels of your code. If the database is corrupted that might also be terminal unless you include bad data (e.g. invalid email address) in that definition, in that case it may be something you can fix, ignore, or live with: it should be obvious in this case where in your code you need to do the fixup or ignoring. > > Do I have to write "try/except" clause on each row? The processing you perform on a row might raise an exception for which the correct action would be to simply continue with the next row. In that case handle the exception inside the 'processRow' function so the code which iterates over the rows never sees it. If it is a more serious problem which is going to stop you processing any further rows then you let it propogate. > > Or to write try/except block (function) where to handle (on one place) > all exceptions expected in the program code is a good idea? > > Or do I have to write own "exception hook"? > > What about unexpected exceptions? :( Big errors, or unexpected errors you handle in one place usually by making sure a human is alerted to the problem. From fabiofz at gmail.com Thu Jun 1 12:46:51 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Thu, 1 Jun 2006 07:46:51 -0300 Subject: Best Python Editor In-Reply-To: <1149149668.113003.142940@j55g2000cwa.googlegroups.com> References: <1149149668.113003.142940@j55g2000cwa.googlegroups.com> Message-ID: On 1 Jun 2006 01:14:28 -0700, andyrsmith at googlemail.com < andyrsmith at googlemail.com> wrote: > > If we could go back to emacs again for a second... > > I'm still using emacs but have been playing with a few other ide's > (wing, komodo + pydev) are the ones i've given a go recently. > > However I still end up coming back to emacs for what I consider to be > emacs mode's piece of 'killer functionality', (well, killer for me > anyway :-) ) which is the C-c C-c shortcut to send the contents of the > current buffer to a running interpreter. (i.e. one long-running > interpreter that behaves as if the entire buffer had been retyped). > Have you checked pydev extensions? It has an 'interactive console' which can do what you just said (but different keybinding, as it would require you to select all you want: Ctrl+A and then send it to the buffer: Ctrl+Enter, but on the other hand, it can do much more too) You can check details at http://www.fabioz.com/pydev/manual_adv_interactive_console.html If there's something missing there, you can submit a feature-request... Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-list/attachments/20060601/23185d25/attachment.html From osv at javad.com Thu Jun 1 12:53:32 2006 From: osv at javad.com (Sergei Organov) Date: Thu, 01 Jun 2006 14:53:32 +0400 Subject: Watching serial port activity. References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> <127ncut3mpadoc5@corp.supernews.com> <1148962019.355956.124420@38g2000cwa.googlegroups.com> <127oj612scnl8a0@corp.supernews.com> <1148998176.105881.156310@g10g2000cwb.googlegroups.com> <127olia8pnldl90@corp.supernews.com> <127rccueg04oie5@corp.supernews.com> Message-ID: Grant Edwards writes: > On 2006-05-31, Sergei Organov wrote: > >> It seems that sniff on a real tty device could be implemented using the >> same technique strace uses to intercept and show syscalls, though I'm >> not aware of any sniffer application that does it. > > Using strace you can indeed trace read/write calls on user-specified > file descriptors. I've actually meant to take strace in source code and modify it for particular purpose. The fact that it almost can do it in unmodified form is quite impressive though. > Figuring out which file descriptors to trace is the tricky part. Provided I have port name, say, /dev/ttyM0, and have running application: osv at osv ~$ fuser /dev/ttyM0 /dev/ttyM0: 5134 osv at osv ~$ ls -l /proc/5134/fd | grep /dev/ttyM0 lrwx------ 1 osv osv 64 2006-05-29 15:33 8 -> /dev/ttyM0 osv at osv ~$ so I need to track fd #8 of the process with pid 5134. Guess one can attach to a running process as gdb does it. Alternatively, if the process to be sniffed sporadically opens/closes the port at run-time, it is required to track open()/close() syscalls as well as read()/write() ones, I think. Overall, seems not that trivial but doable. -- Sergei. From eric_brunel at despammed.com Thu Jun 1 13:12:18 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 01 Jun 2006 13:12:18 +0200 Subject: Function mistaken for a method Message-ID: Hi all, I just stepped on a thing that I can't explain. Here is some code showing the problem: ----------------------------- class C: f = None def __init__(self): if self.f is not None: self.x = self.f(0) else: self.x = 0 class C1(C): f = int class C2(C): f = lambda x: x != 0 o1 = C1() print o1.x o2 = C2() print o2.x ----------------------------- Basically, I want an optional variant function across sub-classes of the same class. I did it like in C1 for a start, then I needed something like C2. The result is... surprising: 0 Traceback (most recent call last): File "func-vs-meth.py", line 18, in ? o2 = C2() File "func-vs-meth.py", line 5, in __init__ self.x = self.f(0) TypeError: () takes exactly 1 argument (2 given) So the first works and o1.x is actually 0. But the second fails because self is also being passed as the first argument to the lambda. Defining a "real" function doesn't help: the error is the same. My actual question is: why does it work in one case and not in the other? As I see it, int is just a function with one parameter, and the lambda is just another one. So why does the first work, and not the second? What 'black magic' takes place so that int is not mistaken for a method in the first case? -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From maric at aristote.info Thu Jun 1 13:29:14 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 1 Jun 2006 13:29:14 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <200606011329.15661.maric@aristote.info> Le Jeudi 01 Juin 2006 13:12, Eric Brunel a ?crit : > class C1(C): > f = int int is not a function but a type, but it's callable so int(0) return 0. > class C2(C): > f = lambda x: x != 0 lambda is a function, applied as a class attribute it becomes a method so it's called with a first parameter representing the instance, self.f(0) in the __init__ becomes C2.f(self, 0), so the lambda should be : f = lambda s, x: x != 0 # s for self, some poeple use _ this exactly the same as : def f(self, val) : return x != 0 (that lambda will return True or False i expect this is not what you want) -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From maric at aristote.info Thu Jun 1 13:33:38 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 1 Jun 2006 13:33:38 +0200 Subject: Function mistaken for a method In-Reply-To: <200606011329.15661.maric@aristote.info> References: <200606011329.15661.maric@aristote.info> Message-ID: <200606011333.38780.maric@aristote.info> Le Jeudi 01 Juin 2006 13:29, Maric Michaud a ?crit?: > this exactly the same as : > > ? ?def f(self, val) : > ? ? ? ?return x != 0 oops, def f(self, val) : return val != 0 -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From __peter__ at web.de Thu Jun 1 13:34:53 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jun 2006 13:34:53 +0200 Subject: Function mistaken for a method References: Message-ID: Eric Brunel wrote: > My actual question is: why does it work in one case and not in the other? > As I see it, int is just a function with one parameter, and the lambda is > just another one. So why does the first work, and not the second? What > 'black magic' takes place so that int is not mistaken for a method in the > first case? A python-coded function has a __get__ attribute, a C-function doesn't. Therefore C1.f performs just the normal attribute lookup while C2.f also triggers the f.__get__(C2(), C2) call via the descriptor protocol which happens to return a bound method. Peter From maric at aristote.info Thu Jun 1 13:46:16 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 1 Jun 2006 13:46:16 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <200606011346.17442.maric@aristote.info> Le Jeudi 01 Juin 2006 13:34, Peter Otten a ?crit?: > A python-coded function has a __get__ attribute, a C-function doesn't. > Therefore C1.f performs just the normal attribute lookup while C2.f also > triggers the f.__get__(C2(), C2) call via the descriptor protocol which > happens to return a bound method. I don't think it's about c-coded versus python-coded stuff, C1.f is a type, C2.f is a method. In [14]: class t : pass ....: In [15]: class u : ....: f = t ....: ....: In [16]: u().f() Out[16]: <__main__.t instance at 0xa795a9ec> -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From onurb at xiludom.gro Thu Jun 1 13:49:18 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 13:49:18 +0200 Subject: How do you practice Python? In-Reply-To: <1149152214.215907.31800@i39g2000cwa.googlegroups.com> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <447eaae0$0$20867$636a55ce@news.free.fr> <1149152214.215907.31800@i39g2000cwa.googlegroups.com> Message-ID: <447ed4b1$0$20866$626a54ce@news.free.fr> Ray wrote: > bruno at modulix wrote: > >>>In our field, we don't always get to program in the language we'd like >>>to program. So... how do you practice Python in this case? Say you're >>>doing J2EE right now. >> >>Hopefully not ! > > > I am :-( > Can we do something to help you out of this bad situation ? (sorry...) >>>How do you practice Python to keep your skills >>>sharp? >> >>How *would* I do ? Well, perhaps I'd use Jython ? > > > Um, I mean, what if you have to use something other than > Python/Jython/IronPython? :) Ruby or Smalltalk, then ? No ? J2EE ? Argh ! (me run away) > How do you keep your Python skill sharp? Just by thinking about how I would solve the problem at hand in Python - and then cry :( -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From noway at sorry.com Thu Jun 1 13:52:56 2006 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 01 Jun 2006 11:52:56 GMT Subject: struct: type registration? References: <447e4b98$1@news.eftel.com> Message-ID: John Machin wrote: >> given the ongoing work on struct (which I thought was a dead >> module), I was wondering if it would be possible to add an API to >> register custom parsing codes for struct. Whenever I use it for >> non-trivial tasks, I always happen to write small wrapper functions >> to adjust the values returned by struct. >> >> An example API would be the following: >> >> ============================================ >> def mystring_len(): >> return 20 >> >> def mystring_pack(s): >> if len(s) > 20: >> raise ValueError, "a mystring can be at max 20 chars" >> s = (s + "\0"*20)[:20] > > Have you considered s.ljust(20, "\0") ? Right. This happened to be an example... >> s = struct.pack("20s", s) >> return s > > I am an idiot, so please be gentle with me: I don't understand why you > are using struct.pack at all: Because I want to be able to parse largest chunks of binary datas with custom formatting. Did you miss the whole point of my message: struct.unpack("3liiSiiShh", data) You need struct.unpack() to parse these datas, and you need custom packer/unpacker to avoid post-processing the output of unpack() just because it just knows of basic Python types. In binary structs, there happen to be *types* which do not map 1:1 to Python types, nor they are just basic C types (like the ones struct supports). Using custom formatter is a way to better represent these types (instead of mapping them to the "most similar" type, and then post-process it). In my example, "S" is a basic-type which is a "A 0-terminated 20-byte string", and expressing it in the struct format with the single letter "S" is more meaningful in my code than using "20s" and then post-processing the resulting string each and every time this happens. >>>>> import struct >>>>> x = ("abcde" + "\0" * 20)[:20] >>>>> x > 'abcde\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' >>>>> len(x) > 20 >>>>> y = struct.pack("20s", x) >>>>> y == x > True >>>>> > > Looks like a big fat no-op to me; you've done all the heavy lifting > yourself. Looks like you totally misread my message. Your string "x" is what I find in binary data, and I need to *unpack* into a regular Python string, which would be "abcde". > >> idx = s.find("\0") >> if idx >= 0: >> s = s[:idx] >> return s > > Have you considered this: > >>>>> z.rstrip("\0") > 'abcde' This would not work because, in the actual binary data I have to parse, only the first \0 is meaningful and terminates the string (like in C). There is absolutely no guarantees that the rest of the padding is made of \0s as well. -- Giovanni Bajo From __peter__ at web.de Thu Jun 1 14:03:27 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jun 2006 14:03:27 +0200 Subject: Function mistaken for a method References: Message-ID: Maric Michaud wrote: > Le Jeudi 01 Juin 2006 13:34, Peter Otten a ?crit?: >> A python-coded function has a __get__ attribute, a C-function doesn't. >> Therefore C1.f performs just the normal attribute lookup while C2.f also >> triggers the f.__get__(C2(), C2) call via the descriptor protocol which >> happens to return a bound method. > I don't think it's about c-coded versus python-coded stuff, C1.f is a > type, C2.f is a method. You are right, int is a type not a function, but presence (and implementation, of course) of __get__ is still the distinguishing factor: >>> class Int(int): ... class __metaclass__(type): ... def __get__(*args): print "XXX", args ... >>> class C: ... int = Int ... >>> C().int XXX (, <__main__.C instance at 0x402948cc>, ) Also: >>> from math import sin >>> sin >>> def son(x): pass ... >>> class C: ... sin = sin ... son = son ... >>> C().sin(0) 0.0 >>> C().son(0) Traceback (most recent call last): File "", line 1, in ? TypeError: son() takes exactly 1 argument (2 given) Peter From onurb at xiludom.gro Thu Jun 1 14:01:04 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 14:01:04 +0200 Subject: How do you practice programming? In-Reply-To: <1149152428.348192.106970@h76g2000cwa.googlegroups.com> References: <1149151097.741307.79440@f6g2000cwb.googlegroups.com> <447eabee$0$19567$636a55ce@news.free.fr> <1149152428.348192.106970@h76g2000cwa.googlegroups.com> Message-ID: <447ed774$0$12371$626a54ce@news.free.fr> Ray wrote: > bruno at modulix wrote: > >>1/ programming >>2/ programming >>3/ lurking here, reading posts and sometimes trying to answer, reading >>source code of the oss apps/frameworks I'm working with, searching >>practical solutions in the cookbook etc >>4/ programming > > > Yeah, but that's what most of us are doing too, we are programmers > after all. But you know, it's like a boxer cannot get better just by > going into a lot of fights, he needs good instruction from a good > coach. I learned the guitar mostly by watching other guitarists (good and bad ones), trying to teach whoever asked me what I already knew, and practicing many hours a day (until my fingers hurt too much in fact). In programming, like in any other form of art - and like in spirituality for that matters - *everyone* can be your master - sometimes without even being aware of it - if you let him teach you. > So what would you do? (I guess it's your number #3 above). The #3 only would not be of any use without at least the #1, the #2 and the #4. But I admit that #1, #2 and #4 would be equally useless without the #3 !-) How, and yes, also : using one's head - not only to wear a hat - may be of some help too. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sjmachin at lexicon.net Thu Jun 1 14:03:28 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 01 Jun 2006 22:03:28 +1000 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <447ED790.20101@lexicon.net> On 1/06/2006 9:46 PM, Maric Michaud wrote: > Le Jeudi 01 Juin 2006 13:34, Peter Otten a ?crit : >> A python-coded function has a __get__ attribute, a C-function doesn't. >> Therefore C1.f performs just the normal attribute lookup while C2.f also >> triggers the f.__get__(C2(), C2) call via the descriptor protocol which >> happens to return a bound method. > I don't think it's about c-coded versus python-coded stuff, C1.f is a type, > C2.f is a method. > Try putting f = chr (a C function); it behaves like int, not like a 1-arg Python function. See below. Cheers, John C:\junk>type func_meth.py class C: f = None def __init__(self): if self.f is not None: self.x = self.f(0) else: self.x = 99 # differs from int(0) :-) class C1(C): f = int class C2(C): def f(self, arg): return arg != 0 class C3(C): pass class C4(C): f = chr for cls in (C1, C2, C3, C4): o = cls() print "callable: %r; result: %r" % (o.f, o.x) C:\junk>func_meth.py callable: ; result: 0 callable: >; result: False callable: None; result: 99 callable: ; result: '\x00' C:\junk> From aljosa.mohorovic at gmail.com Thu Jun 1 14:09:14 2006 From: aljosa.mohorovic at gmail.com (aljosa) Date: 1 Jun 2006 05:09:14 -0700 Subject: py2exe & qt4/qimage Message-ID: <1149163754.826678.95920@h76g2000cwa.googlegroups.com> i'm trying to convert python (image resizer script using PyQt4) script to exe but support for jpeg and tiff image formats is located in Qt4.1\plugins\imageformats (dll files) and when script is converted exe file doesn't support jpeg and tiff. i tryed using all file formats in script: tmp1 = QImage('images/type.bmp') tmp2 = QImage('images/type.gif') tmp3 = QImage('images/type.jpg') tmp4 = QImage('images/type.png') tmp5 = QImage('images/type.tif') but it doesn't work when i convert script to exe. any tips on howto include jpeg and tiff image formats support in exe? From frithiof.jensen at die_spammer_die.ericsson.com Thu Jun 1 14:03:58 2006 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Thu, 1 Jun 2006 14:03:58 +0200 Subject: creating a new database with mysqldb References: Message-ID: "John Salerno" wrote in message news:gcKag.2113$No6.46302 at news.tufts.edu... > Since the connect method of mysqldb requires a database name, it seems > like you can't use it without having a database already created. The web hotel I use create *one* database together with the account. I.O.W: I cannot create any databases; I can create/delete as many tables as I like within the database (up to the disk space that I have). This is pretty normal, I think. From alanalan at newsgroup.nospam Thu Jun 1 14:11:32 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 08:11:32 -0400 Subject: DB-API: how can I find the column names in a cursor? Message-ID: Hi I use a code similar to this to retrieve data from Oracle database: import cx_Oracle con = cx_Oracle.connect("me/secret at tns") cur = con.cursor() outcur = con.cursor() cur.execute(""" BEGIN MyPkg.MyProc(:cur); END;""", cur=outcur) for row in out_cur: print row The problem is I don't know how to find out what are the column name and type that comes out of query (each row in cursor). Is there any possibility that my Python code can find out the column name and type in each row in cursor? The other problem is accessing data in each row by column name. In Ruby I can say: Print row["ColName"] In Python; however, I must access to row contents by integer index, like PRINT ROW[0], which reduces my program's readability. Can I access to row's contents by column name? Any help would be appreciated, Alan From vadim.feelsgood at gmail.com Thu Jun 1 14:26:31 2006 From: vadim.feelsgood at gmail.com (vadim.feelsgood at gmail.com) Date: 1 Jun 2006 05:26:31 -0700 Subject: Best Python Editor In-Reply-To: <1149149773.999940.13500@i40g2000cwc.googlegroups.com> References: <1149149773.999940.13500@i40g2000cwc.googlegroups.com> Message-ID: <1149164791.002020.210000@c74g2000cwc.googlegroups.com> I use WingIDE too. It is very convenient. Good auto-completion feature. It is not so heavy as Komodo. WingIDE was my the second step after Komodo. Just try it and u'll understand how it is good. yairchu at gmail.com wrote: > > Can anyone tell me a good python editor/IDE? > > It would be great if you can provide the download link also. > > WingIDE is very good. > It gives very nice completions and has a nice thing called "source > assistant" that shows the help of the function you're standing on and > etc. > But I don't think it's open-source and freei if that bothers you > http://www.wingware.com/ > > Another good one is idlespoon. > this one is open-source and freei > http://idlespoon.python-hosting.com/ From onurb at xiludom.gro Thu Jun 1 14:27:05 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 14:27:05 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <447edd8d$0$2135$636a55ce@news.free.fr> Peter Otten wrote: > Eric Brunel wrote: > > >>My actual question is: why does it work in one case and not in the other? >>As I see it, int is just a function with one parameter, and the lambda is >>just another one. So why does the first work, and not the second? What >>'black magic' takes place so that int is not mistaken for a method in the >>first case? > > > A python-coded function has a __get__ attribute, a C-function doesn't. > Therefore C1.f performs just the normal attribute lookup while C2.f also > triggers the f.__get__(C2(), C2) call via the descriptor protocol which > happens to return a bound method. FWIW: class Obj(object): def __new__(cls, val, *args, **kw): print "in Obj.__new__" print "- called with :" print " cls :", cls print " val :", val print " args:", str(args) print " kw :", kw obj = object.__new__(cls, *args, **kw) print "got : %s - %s" % (obj, dir(obj)) return obj class CPlus(C): f = Obj > Peter > > -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From m.yanowitz at kearfott.com Thu Jun 1 14:31:34 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Thu, 1 Jun 2006 08:31:34 -0400 Subject: Tkinter - changing existing Dialog? In-Reply-To: <447ED790.20101@lexicon.net> Message-ID: Hello: I have a Tkinter GUI Dialog with many buttons and labels and text widgets. What I would like to do is, can I: 1) Disable/deactivate/hide a button, text widget that is already drawn (and of course the opposite enable/activate/show it)? 2) Change the text of a label or button that is already drawn? based on actions taken by the user. Can it be done without destroying the present dialog or the objects in it and creating a new one? Sorry for what probably is such a trivial and basic question. I just can't find the answer or know what the technical term for what I want to do is to search for it myself. Thanks in advance: Michael Yanowitz From codecraig at gmail.com Thu Jun 1 14:30:32 2006 From: codecraig at gmail.com (abcd) Date: 1 Jun 2006 05:30:32 -0700 Subject: PythonDoc Ant Task Message-ID: <1149165032.870017.254980@i40g2000cwc.googlegroups.com> Anyone ever use the PythonDoc ant task? I have the following... ...this is a cut out of the build xml i am using...but it shows the relevant parts. Anyways I can run my "pyDoc" target and it runs successful with no errors. a "docs" directory is created but is empty. Any idea as to why? My "src" folder contains a python file, Foo.py. which looks like this class Bar: def printMe(self): """This method prints my data""" print "some data is being printed" ...Thanks in advance. From eric_brunel at despammed.com Thu Jun 1 14:37:33 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 01 Jun 2006 14:37:33 +0200 Subject: Function mistaken for a method References: Message-ID: On Thu, 01 Jun 2006 13:34:53 +0200, Peter Otten <__peter__ at web.de> wrote: > Eric Brunel wrote: > >> My actual question is: why does it work in one case and not in the >> other? >> As I see it, int is just a function with one parameter, and the lambda >> is >> just another one. So why does the first work, and not the second? What >> 'black magic' takes place so that int is not mistaken for a method in >> the >> first case? > A python-coded function has a __get__ attribute, a C-function doesn't. > Therefore C1.f performs just the normal attribute lookup while C2.f also > triggers the f.__get__(C2(), C2) call via the descriptor protocol which > happens to return a bound method. Thanks for your explanations, Peter. I'll have to find another way to do what I want... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From noway at sorry.com Thu Jun 1 14:35:16 2006 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 01 Jun 2006 12:35:16 GMT Subject: struct: type registration? References: <447e4b98$1@news.eftel.com> Message-ID: <8aBfg.20673$cX1.313575@twister2.libero.it> Giovanni Bajo wrote: > You need struct.unpack() to parse these datas, and you need custom > packer/unpacker to avoid post-processing the output of unpack() just > because it just knows of basic Python types. In binary structs, there > happen to be *types* which do not map 1:1 to Python types, nor they > are just basic C types (like the ones struct supports). Using custom > formatter is a way to better represent these types (instead of > mapping them to the "most similar" type, and then post-process it). > > In my example, "S" is a basic-type which is a "A 0-terminated 20-byte > string", and expressing it in the struct format with the single > letter "S" is more meaningful in my code than using "20s" and then > post-processing the resulting string each and every time this happens. Another compelling example is the SSH protocol: http://www.openssh.com/txt/draft-ietf-secsh-architecture-12.txt Go to section 4, "Data Type Representations Used in the SSH Protocols", and it describes the data types used by the SSH protocol. In a perfect world, I would write some custom packers/unpackers for those types which struct does not handle already (like the "mpint" format), so that I could use struct to parse and compose SSH messages. What I ended up doing was writing a new module sshstruct.py from scratch, which duplicates struct's work, just because I couldn't extend struct. Some examples: client.py: cookie, server_algorithms, guess, reserverd = sshstruct.unpack("16b10LBu", data[1:]) client.py: prompts = sshstruct.unpack("sssu" + "sB"*num_prompts, pkt[1:]) connection.py: pkt = sshstruct.pack("busB", SSH_MSG_CHANNEL_REQUEST, self.recipient_number, type, reply) + custom kex.py: self.P, self.G = sshstruct.unpack("mm",pkt[1:]) Notice for instance how "s" is a SSH string and unpacks directly to a Python string, and "m" is a SSH mpint (infinite precision integer) but unpacks directly into a Python long. Using struct.unpack() this would have been impossible and would have required much post-processing. Actually, another thing that struct should support to cover the SSH protocol (and many other binary protocols) is the ability to parse strings whose size is not known at import-time (variable-length data types). For instance, type "string" in the SSH protocol is a string prepended with its size as uint32. So it's actual size depends on each instance. For this reason, my sshstruct did not have the equivalent of struct.calcsize(). I guess that if there's a way to extend struct, it would comprehend variable-size data types (and calcsize() would return -1 or raise an exception). -- Giovanni Bajo From sjmachin at lexicon.net Thu Jun 1 14:37:16 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 01 Jun 2006 22:37:16 +1000 Subject: struct: type registration? In-Reply-To: References: <447e4b98$1@news.eftel.com> Message-ID: <447EDF7C.3080104@lexicon.net> On 1/06/2006 9:52 PM, Giovanni Bajo wrote: > John Machin wrote: > >>> given the ongoing work on struct (which I thought was a dead >>> module), I was wondering if it would be possible to add an API to >>> register custom parsing codes for struct. Whenever I use it for >>> non-trivial tasks, I always happen to write small wrapper functions >>> to adjust the values returned by struct. >>> >>> An example API would be the following: >>> >>> ============================================ >>> def mystring_len(): >>> return 20 >>> >>> def mystring_pack(s): >>> if len(s) > 20: >>> raise ValueError, "a mystring can be at max 20 chars" >>> s = (s + "\0"*20)[:20] >> Have you considered s.ljust(20, "\0") ? > > Right. This happened to be an example... > >>> s = struct.pack("20s", s) >>> return s >> I am an idiot, so please be gentle with me: I don't understand why you >> are using struct.pack at all: Given a choice between whether I was referring to the particular instance of using struct.pack two lines above, or whether I was doubting the general utility of the struct module, you appear to have chosen the latter, erroneously. > > Because I want to be able to parse largest chunks of binary datas with custom > formatting. Did you miss the whole point of my message: No. > > struct.unpack("3liiSiiShh", data) > > You need struct.unpack() to parse these datas, and you need custom > packer/unpacker to avoid post-processing the output of unpack() just because it > just knows of basic Python types. In binary structs, there happen to be *types* > which do not map 1:1 to Python types, nor they are just basic C types (like the > ones struct supports). Using custom formatter is a way to better represent > these types (instead of mapping them to the "most similar" type, and then > post-process it). > > In my example, "S" is a basic-type which is a "A 0-terminated 20-byte string", > and expressing it in the struct format with the single letter "S" is more > meaningful in my code than using "20s" and then post-processing the resulting > string each and every time this happens. > > >>>>>> import struct >>>>>> x = ("abcde" + "\0" * 20)[:20] >>>>>> x >> 'abcde\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' >>>>>> len(x) >> 20 >>>>>> y = struct.pack("20s", x) >>>>>> y == x >> True >> Looks like a big fat no-op to me; you've done all the heavy lifting >> yourself. > > Looks like you totally misread my message. Not at all. Your function: def mystring_pack(s): if len(s) > 20: raise ValueError, "a mystring can be at max 20 chars" s = (s + "\0"*20)[:20] s = struct.pack("20s", s) return s can be even better replaced by (after reading the manual "For packing, the string is truncated or padded with null bytes as appropriate to make it fit.") by: def mystring_pack(s): if len(s) > 20: raise ValueError, "a mystring can be at max 20 chars" return s # return s = (s + "\0"*20)[:20] # not needed, according to the manual # s = struct.pack("20s", s) # As I said, this particular instance of using struct.pack is a big fat no-op. > Your string "x" is what I find in > binary data, and I need to *unpack* into a regular Python string, which would > be "abcde". > And you unpack it with a custom function that also contains a fat no-op: def mystring_unpack(s): assert len(s) == 20 s = struct.unpack("20s", s)[0] # does nothing idx = s.find("\0") if idx >= 0: s = s[:idx] return s > >>> idx = s.find("\0") >>> if idx >= 0: >>> s = s[:idx] >>> return s >> Have you considered this: >> >>>>>> z.rstrip("\0") >> 'abcde' > > > This would not work because, in the actual binary data I have to parse, only > the first \0 is meaningful and terminates the string (like in C). There is > absolutely no guarantees that the rest of the padding is made of \0s as well. Point taken. Cheers, John From maric at aristote.info Thu Jun 1 14:44:37 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 1 Jun 2006 14:44:37 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <200606011444.38612.maric@aristote.info> Le Jeudi 01 Juin 2006 13:12, Eric Brunel a ?crit?: > Thanks for your explanations, Peter. I'll have to find another way to do ? > what I want... maybe : class C: ? ?f = None ? ?def __init__(self): ? ? ?if self.f is not None: ? ? ? ?self.x = self.f(0) ? ? ?else: ? ? ? ?self.x = 0 class C2(C): ? ?def __init__(self) : self.f = lambda x: x != 0 -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From sjmachin at lexicon.net Thu Jun 1 14:40:37 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Jun 2006 05:40:37 -0700 Subject: Tkinter - changing existing Dialog? In-Reply-To: References: <447ED790.20101@lexicon.net> Message-ID: <1149165637.162492.139380@j55g2000cwa.googlegroups.com> Michael Yanowitz wrote: > Hello: > > > I have a Tkinter GUI Dialog with many buttons and labels and text > widgets. > So start a *new* thread. From iainking at gmail.com Thu Jun 1 14:48:16 2006 From: iainking at gmail.com (Iain King) Date: 1 Jun 2006 05:48:16 -0700 Subject: Trying to get FreeImagePy to work. In-Reply-To: References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> Message-ID: <1149166096.176405.22780@i40g2000cwc.googlegroups.com> Michele Petrazzo wrote: > Iain King wrote: > > Michele Petrazzo wrote: > > > > I downloaded and installed 0.9.9.3, and it now works. Thanks! > > > > I advice you to don't use that ctypes version... Better is to use the > newest one and update freeimagepy! > > > Iain > > > > Michele OK, Ive installed the latest versions I can find, which are FreeImagePy 1.2.4 and ctypes 0.9.9.6, and I'm back to the error I had earlier. Do you know what's wrong? Iain From reply.in.the.newsgroup at my.address.is.invalid Thu Jun 1 14:49:33 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 01 Jun 2006 14:49:33 +0200 Subject: what is the reasonable (best?) Exception handling strategy? References: <1149156321.440828.95150@g10g2000cwb.googlegroups.com> Message-ID: Petr Jakes: >What about unexpected exceptions? :( I asked a similar question some time ago: http://groups.google.nl/group/comp.lang.python/browse_thread/thread/25963b99da4b2653 -- Ren? Pijlman From __peter__ at web.de Thu Jun 1 14:51:09 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jun 2006 14:51:09 +0200 Subject: Function mistaken for a method References: Message-ID: Eric Brunel wrote: > On Thu, 01 Jun 2006 13:34:53 +0200, Peter Otten <__peter__ at web.de> wrote: > >> Eric Brunel wrote: >> >>> My actual question is: why does it work in one case and not in the >>> other? >>> As I see it, int is just a function with one parameter, and the lambda >>> is >>> just another one. So why does the first work, and not the second? What >>> 'black magic' takes place so that int is not mistaken for a method in >>> the >>> first case? >> A python-coded function has a __get__ attribute, a C-function doesn't. >> Therefore C1.f performs just the normal attribute lookup while C2.f also >> triggers the f.__get__(C2(), C2) call via the descriptor protocol which >> happens to return a bound method. > > Thanks for your explanations, Peter. I'll have to find another way to do > what I want... Maybe just class C2(C): f?=?staticmethod(lambda?x:?x?!=?0) Peter From fredrik at pythonware.com Thu Jun 1 14:54:16 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 1 Jun 2006 14:54:16 +0200 Subject: DB-API: how can I find the column names in a cursor? References: Message-ID: "A.M" wrote: > The problem is I don't know how to find out what are the column name and type that comes out of > query (each row in cursor). > > Is there any possibility that my Python code can find out the column name and type in each row in > cursor? >From "cursor objects" in the DB-API documentation: .description "This read-only attribute is a sequence of 7-item sequences. Each of these sequences contains information describing one result column: (name, type_code, display_size, internal_size, precision, scale, null_ok). The first two items (name and type_code) are mandatory, the other five are optional and must be set to None if meaningfull values are not provided." The full spec is available here: http://www.python.org/dev/peps/pep-0249/ From onurb at xiludom.gro Thu Jun 1 15:07:26 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 15:07:26 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <447ee701$0$22029$626a54ce@news.free.fr> Eric Brunel wrote: > Hi all, > > I just stepped on a thing that I can't explain. Here is some code > showing the problem: > > ----------------------------- > class C: Do yourself a favour : use new-style classes. class C(object) > f = None > def __init__(self): > if self.f is not None: > self.x = self.f(0) > else: > self.x = 0 > > class C1(C): > f = int > > class C2(C): > f = lambda x: x != 0 > > o1 = C1() > print o1.x > > o2 = C2() > print o2.x > ----------------------------- > > Basically, I want an optional variant function across sub-classes of > the same class. > > I did it like in C1 for a start, then I needed > something like C2. The result is... surprising: > > 0 > Traceback (most recent call last): > File "func-vs-meth.py", line 18, in ? > o2 = C2() > File "func-vs-meth.py", line 5, in __init__ > self.x = self.f(0) > TypeError: () takes exactly 1 argument (2 given) Not surprising at all. Functions implement the descriptor protocol[1]. When bound to a class and looked up via an instance, it's the __get__ method of the function object that get called - with the instance as param, as defined by the descriptor protocol. This method then return the function wrapped - with the instance - in an Method object - which itself, when called, returns the result of calling the function *with the instance as first parameter*. Which is how methods can work on the instance, and why one has to explicitly declare the instance parameter in "functions to be used as methods", but not explicitly pass it at call time. (please some guru correct me if I missed something here, but AFAIK it must be a correct enough description of method invocation mechanism in Python). [1] about descriptors, see: http://docs.python.org/ref/descriptors.html http://www.geocities.com/foetsch/python/new_style_classes.htm#descriptors > So the first works and o1.x is actually 0. int is not a function. >>> type(int) int is a type. A Python type is a callable object, and act as a factory for instances of it. If the type doesn't implement the descriptor protocol, when bound to a class and looked up via an instance, normal lookup rules apply. So the type object is returned as is. In your case, since int does'nt implement the descriptor protocol, once looked up (and returned as is), it's called with a correct argument - so everything runs fine. Try this: class Obj(object): def __new__(cls, val, *args, **kw): print "in Obj.__new__" print "- called with :" print " cls :", cls print " val :", val print " args: %s" % str(args) print " kw : %s" % kw obj = object.__new__(cls, *args, **kw) print "got : %s - %s" % (obj, dir(obj)) return obj def __init__(self, *args, **kw): print "in Obj.__init__" print "- called with :" print " args: %s" % str(args) print " kw : %s" % kw class C4(C): f = Obj > But the second fails because > self is also being passed as the first argument to the lambda. Of course. It's a function, and it's bound to a class, and looked up via an instance of the class. Try this: def truc(*args, **kw): print "in truc()__" print "- called with :" print " args: %s" % str(args) print " kw : %s" % kw if len(args) > 1: return args[1] class C6(C): f = truc > Defining > a "real" function doesn't help: the error is the same. What' a "real" function ?-) lambdas *are* real functions. >>> type(lambda x: x) >>> > My actual question is: why does it work in one case and not in the > other? cf above. > As I see it, int is just a function with one parameter, Nope, it's a type. Functions are just one kind of callable. Types are callables too, as are any object overloading the call operator - which is '()' - by implementing the __call__(self, ...) method. class NotAFunc(object): def __call__(self): print "I'm not a function" return 42 func = NotAFunc() func() > and the > lambda is just another one. True. And functions implement the descriptor protocol. > So why does the first work, and not the > second? What 'black magic' takes place so that int is not mistaken for > a method in the first case? cf above. If you understood all my explanations, you now know how to solve the problem. Else, here the solution: class C3(C): f = lambda self, x: return x -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From codecraig at gmail.com Thu Jun 1 15:10:03 2006 From: codecraig at gmail.com (abcd) Date: 1 Jun 2006 06:10:03 -0700 Subject: PythonDoc Ant Task In-Reply-To: <1149165032.870017.254980@i40g2000cwc.googlegroups.com> References: <1149165032.870017.254980@i40g2000cwc.googlegroups.com> Message-ID: <1149167403.532618.22370@y43g2000cwc.googlegroups.com> i found that the problem is because of an import, which is strange. The imported module looks something like this [code] import time class Foo: pass class Bar: global javax.swing import javax.swing [/code] ....so it seems that pydoc cant giggity-giggit! From harry.g.george at boeing.com Thu Jun 1 07:00:28 2006 From: harry.g.george at boeing.com (Harry George) Date: Thu, 1 Jun 2006 05:00:28 GMT Subject: How do you practice Python? References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <447eaae0$0$20867$636a55ce@news.free.fr> <1149152214.215907.31800@i39g2000cwa.googlegroups.com> Message-ID: "Ray" writes: > bruno at modulix wrote: > > > In our field, we don't always get to program in the language we'd like > > > to program. So... how do you practice Python in this case? Say you're > > > doing J2EE right now. > > > > Hopefully not ! > > I am :-( > > > > How do you practice Python to keep your skills > > > sharp? > > > > How *would* I do ? Well, perhaps I'd use Jython ? > > Um, I mean, what if you have to use something other than > Python/Jython/IronPython? :) How do you keep your Python skill sharp? > > > -- > > bruno desthuilliers > > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > > p in 'onurb at xiludom.gro'.split('@')])" > Do projects at home. Either find an existing OSS project, or roll your own. Once you have the basics of the language, the skills are domain-specific: XML, GUIs, CAD, gaming, multithreading, numerical analysis, natural language progromming, etc. If you do an existing project, then you benefit from peer reviews and other informal learning opportunities. -- Harry George PLM Engineering Architecture From alanalan at newsgroup.nospam Thu Jun 1 15:20:09 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 09:20:09 -0400 Subject: DB-API: how can I find the column names in a cursor? References: Message-ID: Thank you Fredrik for help. Would you be able to help with the second part of question: The other problem is accessing data in each row by column name. In Ruby I can say: Print row["ColName"] In Python; however, I must access to row contents by integer index, like PRINT ROW[0], which reduces my program's readability. Can I access to row's contents by column name? Thanks again, Alan "Fredrik Lundh" wrote in message news:mailman.6403.1149166487.27775.python-list at python.org... > "A.M" wrote: > >> The problem is I don't know how to find out what are the column name and >> type that comes out of query (each row in cursor). >> >> Is there any possibility that my Python code can find out the column name >> and type in each row in cursor? > >>From "cursor objects" in the DB-API documentation: > > .description > > "This read-only attribute is a sequence of 7-item > sequences. Each of these sequences contains information > describing one result column: (name, type_code, > display_size, internal_size, precision, scale, > null_ok). The first two items (name and type_code) are > mandatory, the other five are optional and must be set to > None if meaningfull values are not provided." > > The full spec is available here: http://www.python.org/dev/peps/pep-0249/ > > > > From chris.cavalaria at free.fr Thu Jun 1 15:36:48 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 01 Jun 2006 15:36:48 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <447eed61$0$20860$626a54ce@news.free.fr> Eric Brunel a ?crit : > On Thu, 01 Jun 2006 13:34:53 +0200, Peter Otten <__peter__ at web.de> wrote: > >> Eric Brunel wrote: >> >>> My actual question is: why does it work in one case and not in the >>> other? >>> As I see it, int is just a function with one parameter, and the >>> lambda is >>> just another one. So why does the first work, and not the second? What >>> 'black magic' takes place so that int is not mistaken for a method >>> in the >>> first case? >> >> A python-coded function has