From carl at personnelware.com Fri Dec 21 17:35:42 2007 From: carl at personnelware.com (Carl K) Date: Fri, 21 Dec 2007 16:35:42 -0600 Subject: mac dashboad In-Reply-To: References: <4aWdnRg9NK_KsvHanZ2dnUVZ_rfinZ2d@comcast.com> Message-ID: Chris Mellon wrote: > On Dec 21, 2007 3:25 PM, Carl K wrote: >> ianar? wrote: >>> On Dec 21, 12:37 pm, Carl K wrote: >>>> How do I hang an app off the mac dashboard? >>>> >>>> The goal is a python version of Weatherbug. >>>> >>>> something like: >>>> read xml data from a URL, >>>> display some numbers, >>>> mouse over shows more details >>>> >>>> Carl K >>> What is the dashboard - is it anything like the taskbar in windows/ >>> Gnome? If it is, take a look at this: >>> >>> http://www.wxwidgets.org/manuals/2.6.3/wx_wxtaskbaricon.html >> Yes. But I don't want to rely on wx - trying to use just native mac python >> (whatever they ship with) >> > > > Dashboard widgets are written using HTML and Javascript. They are > rendered by a WebKit instance which, as far as I know, has no > mechanism for Python scripting. Unless it does, you can't write a > widget in Python, and even so you wouldn't use wx (or any other GUI > toolkit) to do so - your display medium is HTML and the Canvas object. > There's lots of articles on developer.apple.com about writing > Dashboard widgets. bah. takes the fun out of it. Thanks, Carl K From steve at REMOVE-THIS-cybersource.com.au Sat Dec 8 09:32:54 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Dec 2007 14:32:54 -0000 Subject: setattr getattr confusion References: <1hv6j.5022$fl7.3982@newssvr22.news.prodigy.net> Message-ID: <13llaom6l022j37@corp.supernews.com> On Sat, 08 Dec 2007 14:26:00 +0200, Donn Ingle wrote: >> So you might want to describe your use-case. > Um.. I wanted an object with Key to hold other data. I wanted a way to > set that *other* data within Key without having to specify the "object > in-between" everytime. That's called "automatic delegation". -- Steven From gile83 at gmail.com Sat Dec 15 14:09:58 2007 From: gile83 at gmail.com (gile83 at gmail.com) Date: Sat, 15 Dec 2007 11:09:58 -0800 (PST) Subject: Informations about hardware, computers, configurations... Message-ID: http://comp-hardware.blogspot.com/ If you looking for computer hardware... From george.sakkis at gmail.com Tue Dec 4 11:46:28 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 4 Dec 2007 08:46:28 -0800 (PST) Subject: Python surpasses Perl in TIOBE index References: <7e117be5-4308-43ae-a34b-cd9cb72f15b6@b40g2000prf.googlegroups.com> <75e8931d-87fa-45a3-8638-c5c8508d77e2@s12g2000prg.googlegroups.com> <87fxyifnpp.fsf@rudin.co.uk> Message-ID: On Dec 4, 11:07 am, Paul Rudin wrote: > George Sakkis writes: > > Even more amazing is the rate C++ is losing ground: > >http://www.tiobe.com/tiobe_index/C__.html > > I don't really find surprising that low level languages lose ground at > the expense of higher level ones. The developer-time/run-time > trade-off tends to move in favour of higher level languages as > hardware gets faster and cheaper. Well we Python folks are spoiled but for most people C++ counts as a high level language (hell, some consider even C high level). I'd be more interested though how well do these numbers correlate with actual penetration (new projects, job openings, etc.) George From http Sat Dec 1 17:13:33 2007 From: http (Paul Rubin) Date: 01 Dec 2007 14:13:33 -0800 Subject: Pickling dictionaries containing dictionaries: failing, recursion-style! References: <701fc2e8-54e3-4f4d-b30c-ec4b8f10d98e@l16g2000hsf.googlegroups.com> Message-ID: <7xve7iqd0y.fsf@ruckus.brouhaha.com> lysdexia writes: > self.wordDB[word] = [self.words.count(word), wordsWeights] what is self.words.count? Could it be an iterator? I don't think you can pickle those. From timr at probo.com Thu Dec 13 02:54:35 2007 From: timr at probo.com (Tim Roberts) Date: Thu, 13 Dec 2007 07:54:35 GMT Subject: sqlite weirdness References: <4c10d664-bc3f-4023-a54b-09105d72c4a1@j20g2000hsi.googlegroups.com> <078d03e3-6771-4547-907a-77f3c6bf77b4@x69g2000hsx.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > >Thanks Duncan and John! That makes sense. But why does the official >Python docs show an example that seems to imply that there is a "date" >type? See link below: You can certainly create fields of type "date" in sqlite, but sqlite doesn't understand any types. **ALL** types in sqlite are stored and compared as strings. You could declare your "date" field as type "frog" and it would work exactly the same. C:\tmp>sqlite x.db SQLite version 2.8.6 Enter ".help" for instructions sqlite> create table xyz ( ...> xxx frog ...> ); sqlite> insert into xyz values (123); sqlite> select * from xyz; 123 sqlite> Note that the example in the web page you quoted takes a Python variable of type datetime.date and converts it to a string, which produces "2007-12-12". Also note that the conversion on the OTHER end has to use the special sqlite adapter syntax ('select current_date as "d [date]"...'). In my opinion, it can be argued that the inclusion of sqlite in the Python standard library was a mistake. It is a great product, and I've used it many times in my own Python apps, but it has a number of unexpected idiosyncracies. When you download and install it yourself, you can evaluate the idiosyncracies and decide whether they are acceptable, but when its in the standard library, you don't expect to go through that. >I'll have to refactor my code somewhat to force it to use the 'YYYY-MM- >DD' format. Another possible solution is to use a real database. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From israelu at elbit.co.il Mon Dec 31 08:47:31 2007 From: israelu at elbit.co.il (iu2) Date: Mon, 31 Dec 2007 05:47:31 -0800 (PST) Subject: using super Message-ID: Hi I'm trying to make a method call automatically to its super using this syntax: class A: chained = ['pr'] def pr(self): print 'Hello from A' class B(A): def pr(self): print 'Hello from B' chain(B, A) b = B() b.pr() b.pr() will print Hello from B Hello from A I'm doing it using the 'chained' attribute in class A, and with this function: def chain(cls, sup): for m in dir(cls): if callable(getattr(cls, m)) and m in cls.chained: cm = getattr(cls, m) def m2(*p): cm(*p) return getattr(sup, m)(*p) setattr(cls, m, m2) return cls which seeks for all 'chained' methods and adjusts them accordingly. (had there been class decorators the syntax would have been simpler, something like class A: @make_chained def pr(): print 'Hello from A' @chained class B: def pr(): print 'Hello from B' ) My problem is this: Currently I pass the base class to 'chain' - chain(B, A) I prefer to write chain(B) and let 'chain' use the super of B. So: def chain(cls): for m in dir(cls): if callable(getattr(cls, m)) and m in cls.chained: print 'chaning', cls, m cm = getattr(cls, m) def m2(*p): cm(*p) return getattr(super(cls), m)(*p) setattr(cls, m, m2) This is probably wrong because I don't give the object instance to super (I don't have it!) and I also get the error TypeError: super() argument 1 must be type, not classobj Can you please help me with this? Thanks iu2 From charl.loubser at gmail.com Thu Dec 13 07:39:04 2007 From: charl.loubser at gmail.com (Merrigan) Date: Thu, 13 Dec 2007 04:39:04 -0800 (PST) Subject: E-Mail Parsing References: <53d05498-d057-4e8f-90c8-48bb1cdf233f@t1g2000pra.googlegroups.com> Message-ID: <004ac706-e25d-4ad1-8e6a-0246a7e13b2f@d4g2000prg.googlegroups.com> On Dec 13, 9:29 am, Matt Nordhoff wrote: > Merrigan wrote: > > I am writing a script to administer my E-Mail Server. The One thing > > I'm currently struggling with is kind of Parsing the E-Mail adress > > that I supply to the script. > > > I need to get the username (The part BEFORE the @ sign) out of the > > address so that I can use it elsewhere. The problem I have with this > > is that both the domain, and the username are variable lenghts and > > that I have no idea how to split the two parts. > > > Is there any way that I can do this? > > > Thank ye very much. > >>> addr = "u... at example.com" > >>> addr.split("@") > > ['user', 'example.com'] > > If it's formatted like a To header ("User "), use > email.Utils.parseaddr() to get the address out of it.\ > > The email modules might help you a lot: > > > -- Hi Matt, Thank you very much for the help. It was exactly what I was looking for, and made my script much safer and easier to use. Blessings! -- Merrigan From ms at cerenity.org Sun Dec 9 09:54:31 2007 From: ms at cerenity.org (Michael Sparks) Date: Sun, 09 Dec 2007 14:54:31 +0000 Subject: Minimalistic Software Transactional Memory References: <13lm7nd85v7jk70@corp.supernews.com> Message-ID: <13lo00ugtuk5nf8@corp.supernews.com> Duncan Booth wrote: > Michael Sparks wrote: > >> I'm interested in writing a simple, minimalistic, non persistent (at >> this stage) software transactional memory (STM) module. The idea being >> it should be possible to write such a beast in a way that can be made >> threadsafe fair easily. >> >> For those who don't know, STM is a really fancy way of saying >> variables with version control (as far as I can tell :-) designed to >> enable threadsafe shared data. >> >> I'm starting with the caveat here that the following code is almost >> certainly not threadsafe (not put any real thought into that as yet), >> and I'm interested in any feedback on the following: >> >> * Does the API look simple enough? >> * Are there any glaring mistakes in the code ? (It's always harder >> to see >> your own bugs) >> * What key areas appear least threadsafe, and any general >> suggestions >> around that. >> >> If I get no feedback I hope this is of interest. Since these things >> get archived, if you're reading this a month, 6 months, a year or more >> from now, I'll still be interested in feedback... > > Unless you really are desperate to reinvent the wheel, have you looked at > ZODB? https://launchpad.net/zodb > > ZODB gives you the transactional model you want. It also gives you > persistence, but if you don't want that you can simply connect to a non- > persistent store. That seems somewhat overkill for my needs. ZODB's distribution is 3.3MB in size, whereas the system I want a minimalistic, non-persistant[1] transactional memory for is 345K in size. (The Axon part of kamaelia) I'll take a look though. [1] I said "at this stage" because its something I *may* want in future for some possible usecases, but generally I'm not really very interested in persistence. (At least not where I'm putting this :-) Context: I want thing that use the following class threadsafe, and can think of a few ways of doing this, and STM seems one of the more "nicer" ways of doing so. (it's clients are currently just generators which makes it safe at the moment) https://kamaelia.svn.sourceforge.net/svnroot/kamaelia/branches/private_MPS_Scratch/Axon/Axon/CoordinatingAssistantTracker.py It's used to provide an ENVironment like facility (similar to os.environ) for generator based Kamaelia components. Thanks for the feedback :-) Michael. From bertrand.croq at gmail.com Mon Dec 17 08:27:53 2007 From: bertrand.croq at gmail.com (bcroq) Date: Mon, 17 Dec 2007 05:27:53 -0800 (PST) Subject: arrays in lists References: Message-ID: On 17 d?c, 14:05, "Peter Stahlir" wrote: > For example: > from numpy import array > a = array([1]) > b = array([2]) > c = [a,b] > d = c.index(a) No problem here, Python 2.4.4 From carsten at uniqsys.com Tue Dec 4 08:47:20 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 04 Dec 2007 08:47:20 -0500 Subject: Delete a instance passed by reference into a method In-Reply-To: <56105f35-ae52-4b4b-afac-a4084d6cb920@p69g2000hsa.googlegroups.com> References: <855405.74475.qm@web90502.mail.mud.yahoo.com> <56105f35-ae52-4b4b-afac-a4084d6cb920@p69g2000hsa.googlegroups.com> Message-ID: <1196776040.3443.7.camel@dot.uniqsys.com> On Mon, 2007-12-03 at 18:27 -0800, hdante wrote: > (note, you don't want to do this, it's a proof of concept) > > import sys > > class A(object): > def __init__(self): > pass > def m1(self, x = None): > if x == None: > x = sys._getframe(1).f_locals > ab = 'aB' > x[ab].i = 10 > del x[ab] > print 'No more B' > class B(object): > def __init__(self, i): > self.i = i > def __del__(self): > print 'delete B' > > aA = A() > aB = B(i = 6) > print str(aB.i) > aA.m1() > print str(aB.i) That's not much of a proof of anything. It only works because the last block happens to only use globals. If you stick it inside a function with local names, it'll cease to "work". The bottom line is that you can not modify the namespace of the caller within a function, unless you only use globals, and I hope I don't have to tell you what a fundamentally bad idea that is. My question to the OP is, what are you actually trying to accomplish? -- Carsten Haese http://informixdb.sourceforge.net From tjreedy at udel.edu Wed Dec 19 01:51:33 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Dec 2007 01:51:33 -0500 Subject: New+old-style multiple inheritance References: <6c9623c6-04d5-4600-9f3a-9179c1345eec@w40g2000hsb.googlegroups.com> Message-ID: wrote in message news:a966bab6-fdc8-4bcb-aaaa-00c5e43d7a1d at t1g2000pra.googlegroups.com... | Thank Gabriel, | | That sounds exactly right and your work-around provides confirmation. | This code is an expedient solution for us so I expect we'll go with | forcing a slot update. Hopefully the library concerned is going to | fix the problem in a future release. To work with 3.0, they will have to, or rather it will be done for them, since there will only be new style classes. From comp_lexx at hotmail.com Thu Dec 20 19:00:47 2007 From: comp_lexx at hotmail.com (lex __) Date: Fri, 21 Dec 2007 00:00:47 +0000 Subject: replace c-style comments with newlines (regexp) Message-ID: I'm tryin to use regexp to replace multi-line c-style comments (like /* this /n */ ) with /n (newlines). I tried someting like re.sub('/\*(.*)/\*' , '/n' , file) but it doesn't work for multiple lines. besides that I want to keep all newlines as they were in the original file, so I can still use the original linenumbers (I want to use linenumbers as a reference for later use.) I know that that will complicate things a bit more, so this is a bit less important. background: I'm trying to create a 'intelligent' source-code security analysis tool for c/c++ , python and php files, but filtering the comments seems to be the biggest problem. :( So, if you have an answer to this , please let me know how to do this! thanks in advance, - Alex _________________________________________________________________ Download de nieuwe Windows Live Messenger! http://get.live.com/messenger/overview From kar1107 at gmail.com Sat Dec 8 19:58:25 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Sat, 8 Dec 2007 16:58:25 -0800 (PST) Subject: auto-increment operator - why no syntax error? Message-ID: <828df43b-9a63-4bb5-81cb-67937ae1fe01@e6g2000prf.googlegroups.com> I see python doesn't have ++ or -- operators unlike say, C. I read some reasonings talking about immutable scalars and using ++/-- doesn't make much sense in python (not sure if ++i is that far-fetched compared to the allowed i += 1) In any case, I accidentally wrote ++n in python and it silently accepted the expression and it took me a while to debug the problem. Why are the following accepted even without a warning about syntax error? (I would expect the python grammar should catch these kind of syntax errors) >>> n = 1 >>> 2 * +++++ n 2 >>> n += 1 >>> n 2 >>> ++n 2 Karthik From bret.wortman at gmail.com Wed Dec 5 16:20:35 2007 From: bret.wortman at gmail.com (Bret) Date: Wed, 5 Dec 2007 13:20:35 -0800 (PST) Subject: SimpleXMLRPCServer interruptable? References: <394f2fdb-72de-4cc2-b95a-9e7867d0d134@f3g2000hsg.googlegroups.com> Message-ID: <0e9b0524-2b03-444b-b718-b67a7ff3ec04@e6g2000prf.googlegroups.com> I just tried changing this so that I now have a threading.Event() called self.done, which is set within the body of the shutdown() method. The serverWrapper loop now looks like this: def serverWrapper(): while True: server.handle_request() if self.done.isSet(): break This works, but only if I follow the shutdown() rpc call a few seconds later with ... something else to cause handle_request() to complete again. Obviously, not quite the right approach.... On Dec 5, 2:00 pm, Bret wrote: > I'm coming back to Python after an absence and it's surprising how > many things I've forgotten since wandering (against my will) into Java > land. > > Anyway, I have a need for a way to make SimpleXMLRPCServer > interruptable. Basically, I have a main server that, in response to > certain RPC calls, creates additional servers on different ports. I > then need to be able to shut these additional servers down. > > I've got something like this in the __init__ of the class which > contains the spawned servers: > > def __init__(self, host, port): > : > : > server = SimpleXMLRPCServer((host, port)) > : > : Bunch of server.register_function calls > : > def serverWrapper(): > try: > while True: > server.handle_request() > except: > pass > > One of the methods that I register is: > > def shutdown(self): > raise "Quitting time" > > Through watching logs and such I can see that the shutdown() method is > getting called, but the loop isn't getting broken. I've done > something like this before in a previous job (so I don't have my > source in front of me, more's the pity) and am hoping someone can > chime in with a good idea. > > Thanks in advance! > > Bret Wortman From exarkun at divmod.com Wed Dec 19 15:08:14 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 19 Dec 2007 15:08:14 -0500 Subject: help displaying pdf thru client/server In-Reply-To: Message-ID: <20071219200814.8162.690453727.divmod.quotient.47253@ohm> On Wed, 19 Dec 2007 13:50:10 -0600, Larry Bates wrote: >PaulS wrote: >> Connecting to a Linux server from XP pc using a telnet program, I run a >> report and convert it to a pdf document(using Reportlab) which I need to >> display. The pdf is on the Linux server. Ideas how to display to the pc >> would be appreciated. thanks, paul >> >> >You will need webserver running (Apache?) on Linux server that shows a page that >has a link to the pdf file that you created. > >Alternatively you can use SimpleHTTPServer module or Twisted to make a more >stripped down webserver but it is probably easier just to use Apache. Serving static files with Twisted is pretty easy: twistd web --port abcd --path /foo/bar I don't think any way you can set up Apache is easier than that. ;) > >You didn't say if the Linux server was local or not. If local, you could use >SAMBA to create a SMB share and have the XP PC get to it that way. There are >other ways, but these should get you started. > >-Larry Jean-Paul From asgarde at msn.com Tue Dec 25 09:41:42 2007 From: asgarde at msn.com (asgarde at msn.com) Date: Tue, 25 Dec 2007 06:41:42 -0800 (PST) Subject: Pexpect and a Linux Terminal References: Message-ID: Yes it's work ! :-D I use prompt = '.*#' to detect the prompt expect. Thank you for you'r help ! Vive Python et TK :-D From jeremy at omba.demon.co.uk Sun Dec 9 19:05:02 2007 From: jeremy at omba.demon.co.uk (Jeremy C B Nicoll) Date: Mon, 10 Dec 2007 00:05:02 +0000 Subject: searching a value of a dict (each value is a list) References: <3a5df6df-89dc-484e-a5d7-88d0de02ef73@l1g2000hsa.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Jeremy C B Nicoll: > > The code someone else posted ... > > If you are talking about my D code then I know it... No I meant the code that used python to iterate over the dict and create zillions of extra keys. I've deleted earlier posts in the thread and wasn't sure who suggested that. -- Jeremy C B Nicoll - my opinions are my own. From guptaabhishek1983 at gmail.com Wed Dec 19 00:19:09 2007 From: guptaabhishek1983 at gmail.com (abhishek) Date: Tue, 18 Dec 2007 21:19:09 -0800 (PST) Subject: Problem untaring python2.5 Message-ID: Hi everyone , i am not able to untar python 2.5 source code using " tar -xvzf " . Is it a problem with my system settings or python 2.5 itself. When i tried to do it it resulted in following errors -- tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/English.lproj/Documentation/ide/ new_window_made.gif tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ Documentation/ide/new_window_made.gif: Cannot open: No such file or directory tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/English.lproj/Documentation/ide/ output_window.gif tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ Documentation/ide/output_window.gif: Cannot open: No such file or directory tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/English.lproj/Documentation/ide/ simple_commands.gif tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ Documentation/ide/simple_commands.gif: Cannot open: No such file or directory tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/English.lproj/Documentation/ doc/ tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ Documentation/doc: Cannot mkdir: No such file or directory Python-2.5/Mac/Resources/app/Resources/English.lproj/Documentation/doc/ index.html tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ Documentation/doc/index.html: Cannot open: No such file or directory tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/English.lproj/Documentation/ scripting.html tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ Documentation/scripting.html: Cannot open: No such file or directory tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/English.lproj/Documentation/ python.gif tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ Documentation/python.gif: Cannot open: No such file or directory tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/English.lproj/Documentation/ pythonsmall.gif tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ Documentation/pythonsmall.gif: Cannot open: No such file or directory tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/English.lproj/Documentation/ community.html tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ Documentation/community.html: Cannot open: No such file or directory tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/English.lproj/Documentation/ gui.html tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ Documentation/gui.html: Cannot open: No such file or directory tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/English.lproj/Documentation/ PackageManager.gif tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ Documentation/PackageManager.gif: Cannot open: No such file or directory tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/English.lproj/Documentation/ finder.html tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ Documentation/finder.html: Cannot open: No such file or directory tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/English.lproj/Documentation/ index.html tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ Documentation/index.html: Cannot open: No such file or directory tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/English.lproj/Documentation/ shell.html tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ Documentation/shell.html: Cannot open: No such file or directory tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/English.lproj/Documentation/ packman.html tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ Documentation/packman.html: Cannot open: No such file or directory tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/English.lproj/Documentation/ intro.html tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ Documentation/intro.html: Cannot open: No such file or directory tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/English.lproj/InfoPlist.strings tar: Python-2.5/Mac/Resources/app/Resources/English.lproj/ InfoPlist.strings: Cannot open: No such file or directory tar: Skipping to next header Python-2.5/Mac/Resources/app/Resources/PythonInterpreter.icns tar: Python-2.5/Mac/Resources/app/Resources/PythonInterpreter.icns: Cannot open: No such file or directory tar: Skipping to next header tar: Error exit delayed from previous errors From carl at personnelware.com Mon Dec 24 00:53:16 2007 From: carl at personnelware.com (Carl K) Date: Sun, 23 Dec 2007 23:53:16 -0600 Subject: convert pdf to png Message-ID: I need to take the take the pdf output from reportlab and create a preview image for a web page. so png or something. I am sure ghostscript will be involved. I am guessing PIL or ImageMagic ? all sugestions welcome. Carl K From ndbecker2 at gmail.com Sat Dec 8 16:22:42 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Sat, 08 Dec 2007 16:22:42 -0500 Subject: Recommendations for writing a user guide with examples? Message-ID: I'm looking for recommendations for writing a user manual. It will need lots of examples of command line inputs and terminal outputs. I'd like to minimize the effort to integrate the terminal input/output into my document. I have lots of experience with latex, but I wonder if there may be some other choices. Maybe docutils, pydoc, something else? The code I'm documenting is written in python, if that matters. From igor.tatarinov at gmail.com Sat Dec 15 00:47:06 2007 From: igor.tatarinov at gmail.com (igor.tatarinov at gmail.com) Date: Fri, 14 Dec 2007 21:47:06 -0800 (PST) Subject: opposite of zip()? Message-ID: <34df25b7-96fa-4d79-9802-11ace50f1754@s19g2000prg.googlegroups.com> Given a bunch of arrays, if I want to create tuples, there is zip(arrays). What if I want to do the opposite: break a tuple up and append the values to given arrays: map(append, arrays, tupl) except there is no unbound append() (List.append() does not exist, right?). Without append(), I am forced to write a (slow) explicit loop: for (a, v) in zip(arrays, tupl): a.append(v) I assume using an index variable instead wouldn't be much faster. Is there a better solution? Thanks, igor From kyosohma at gmail.com Thu Dec 27 16:53:58 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 27 Dec 2007 13:53:58 -0800 (PST) Subject: "Impure" Python modules Message-ID: <1eeacf71-9385-47eb-beeb-b8dd4c8f9ab5@s27g2000hsb.googlegroups.com> Hi, Is there some way to get a list of "impure" Python modules/extensions from PyPI? I know the mySQL module is a good example, but I am working on creating some decent instructions on how to create Windows installers from impure modules and am having a hard time finding them. Thanks! Mike From mdelliot at gmail.com Thu Dec 27 10:53:57 2007 From: mdelliot at gmail.com (Micah Elliott) Date: Thu, 27 Dec 2007 07:53:57 -0800 (PST) Subject: Building Python statically on linux Message-ID: <0300530c-5550-4fff-bac6-66dbfa1b82b9@d21g2000prf.googlegroups.com> Are there instructions somewhere on how to build Python (on linux) statically? This seems like a common thing to do want to do, but my searching isn't turning up much. If it is common, it would be nice to see a configure option like I've seen in other tools: --enable-all-static Build completely static (standalone) binaries. I'm ./configure-ing with "--disable-shared" (because this must mean "enable static", right?), and (based on some other posts here) tried adding "*static*" near the top of Modules/Setup. I'd like to see ldd tell me "not a dynamic executable", but alas, it's presently: $ ldd /path/to/new/bin/python libpthread.so.0 => /lib/tls/libpthread.so.0 (0x008e9000) libdl.so.2 => /lib/libdl.so.2 (0x007f0000) libutil.so.1 => /lib/libutil.so.1 (0x00df6000) libm.so.6 => /lib/tls/libm.so.6 (0x007cb000) libc.so.6 => /lib/tls/libc.so.6 (0x0069f000) /lib/ld-linux.so.2 (0x00682000) Do I just need to be passing something like LDFLAGS="-static ???" to configure? I just tried that and got a bunch of "symbol rename" warnings during the compilation, and then "make install" mysteriously failed. Thanks for any pointers. -- Micah From srikrishnamohan at gmail.com Fri Dec 28 08:08:20 2007 From: srikrishnamohan at gmail.com (km) Date: Fri, 28 Dec 2007 18:38:20 +0530 Subject: comparing dictionaries to find the identical keys In-Reply-To: References: Message-ID: Hi On Dec 28, 2007 4:55 PM, Beema shafreen wrote: > hi everybody , > i need to compare two dictionary's key. I have written a script > gene_symbol = {} > probe_id = {} > result = {} > def getGene(fname): > fh = open(fname , 'r') > for line in fh: > yield line > fh.close() > for line in getGene("symbol_hu133"): > data1= line.strip().split('#') > probe_give = data1[0].strip() > gene_give = data1[1].strip() > gene_symbol[probe_give] = gene_give > #print gene_symbol.keys() > for line in getGene("gds1428.csv"): > data = line.strip().split(',') > probe_get = data[0].strip() > probe_id[probe_get] = data > if gene_symbol.keys() == probe_id.keys(): > print gene_symbol.keys(), probe_id.values() > > > can anybody show me the error I make here ,while comparing the keys of > two dictionaries so that i print the values of the dictionaries whoes Keys > are Identical > > Remember that ur looking for commonly occuring keys between the two dictionaries. And dictionary.keys() generates a 'list' of keys in that dictionary. So, u r comparing a list with another in an if construct and printing the same which is not what u want to do. Ideally u should iterate over a list of items and check out if it is present or not in the other list and then print corresponding values. Alternately this can also be done with sets module by converting the list into a set object and do a simple intersection of the two sets, by which u get the commonly occuring items. HTH KM > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael at stroeder.com Sat Dec 8 08:26:44 2007 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Sat, 08 Dec 2007 14:26:44 +0100 Subject: Running unmodified CGI scripts persistently under mod_wsgi. In-Reply-To: <13ljk3r3miln8e2@corp.supernews.com> References: <226020ef-3955-43e8-b1f6-2ba9ba43d45e@c29g2000hsa.googlegroups.com> <5qga2mFvuljgU1@mid.uni-berlin.de> <160f8bbc-70be-4dcb-8874-de72588c1d10@d61g2000hsa.googlegroups.com> <1b343163-e755-44f8-b5c3-4af56c61e817@c29g2000hsa.googlegroups.com> <93a92a82-cf3c-4ebb-a93f-180374e5f75a@e4g2000hsg.googlegroups.com> <00c0167e-3b4c-4476-b473-1f938a54db63@e1g2000hsh.googlegroups.com> <2ecd5c1e-d779-4fd6-9d73-4a0f1cfc1f04@s36g2000prg.googlegroups.com> <13klrcs87qivl5f@corp.supernews.com> <13ljk3r3miln8e2@corp.supernews.com> Message-ID: Jeffrey Froman wrote: > > I'd still be interested in a mod_wsgi wrapper for 3rd-party CGI scripts. I doubt that this is possible, not because of the interface. But conventional CGI scripts are implemented with the assumption of being stateless. You would have to completely reinitialize them for each hit. Without knowledge about the internal CGI script processing this would mean reinitializing the whole Python run-time environment. So IMHO there's no real gain. Just my 2 c. Ciao, Michael. From dave.dex at googlemail.com Thu Dec 13 05:56:09 2007 From: dave.dex at googlemail.com (dave.dex at googlemail.com) Date: Thu, 13 Dec 2007 02:56:09 -0800 (PST) Subject: MySQLdb extracting to a list References: <6b8888e2-ee92-4122-929a-4b2034ab297a@e10g2000prf.googlegroups.com> Message-ID: On Dec 13, 10:40 am, John Machin wrote: > On Dec 13, 9:03 pm, dave.... at googlemail.com wrote: > > > > > Hi all, > > > I've been searching the docs like mad and I'm a little new to python > > so apologies if this is a basic question. > > > I would like to extract the results of the following query into a list > > - SELECT columnname FROM tablename. I use the following code. > > > # Create a connection object and create a cursor > > db = MySQLdb.Connect( > cursor = db.cursor() > > # Make SQL string and execute it > > sql = "SELECT columnname FROM tablename" > > cursor.execute(sql) > > # Fetch all results from the cursor into a sequence and close the > > connection > > results = cursor.fetchall() > > db.close() > > print results > > > The output from the above gives the following: > > > (('string1',), ('string2',), ('string3',)) > > > When I'm expecting > > ('string1', 'string2', 'string3') > > > I could pass this through some string manipulation but I'd guess I'm > > doing something wrong. Please could someone point me in the right > > direction. > > Your SQL query has returned 3 rows. Each row contains only 1 column. > > Each row is returned as a tuple of 1 element. The whole result is a > tuple of 3 rows. You don't need string manipulation, you need tuple > manipulation. > > Better example: > select name, hat_size from friends; > results in: > (('Tom', 6), ('Dick', 7), ('Harry', 8)) > > so:>>> result = (('Tom', 6), ('Dick', 7), ('Harry', 8)) > >>> [row[0] for row in result] > > ['Tom', 'Dick', 'Harry']>>> for n, h in result: > > ... print 'Name: %s; hat size: %d' % (n, h) > ... > Name: Tom; hat size: 6 > Name: Dick; hat size: 7 > Name: Harry; hat size: 8 > > >>> result[2][1] > 8 > > HTH, > John Many thanks John, Really well explained and I understand what to do now. It's much appreciated. Thanks again. From usenet.kadin at xoxy.net Wed Dec 5 16:19:00 2007 From: usenet.kadin at xoxy.net (Kadin2048) Date: Wed, 05 Dec 2007 16:19:00 -0500 Subject: Converting LF/FF delimited logs to XML w/ Python? Message-ID: This is a very noob-ish question so I apologize in advance, but I'm hoping to get some input and advice before I get too over my head. I'm trying to convert some log files from a formfeed- and linefeed-delimited form into XML. I'd been thinking of using Python to do this, but I'll be honest and say that I'm very inexperienced with Python, so before I dive in I wanted to see whether some more experienced minds thought I was choosing the right tool. Basically, what I want to do is convert from instant messaging logs produced by CenterIM, which look like this (Where "^L" represents ASCII 12, the formfeed character): ^L IN MSG 1190126325 1190126325 hi ^L OUT MSG 1190126383 1190126383 hello To an XML-based format* like this: hi hello Obviously there's information in the bottom example not present in the top (account names, protocol), but I'll grab those from the file name or prompt the user. Given that I'd be learning as I go along, is Python a good tool for doing this? (Am I totally insane to be trying this as a beginner?) And if so, where should I start? I'd like to avoid massive wheel-reinvention if at all possible. I'm not afraid to RTFM but there's a lot of information around on Python and I'm not sure what's most relevant. Suggestions on what to read, books to buy, etc., are all welcomed. Thanks in advance, Kadin. * For the curious, this is sort of poor attempt at the "Universal Log Format" as used by Adium on OS X. -- http://kadin.sdf-us.org/ From ptmcg at austin.rr.com Mon Dec 17 09:23:42 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 17 Dec 2007 06:23:42 -0800 (PST) Subject: programming container object References: <13mc8ljr9b8dg81@corp.supernews.com> <97e13b40-f5c3-490e-b029-444d0d279584@f3g2000hsg.googlegroups.com> Message-ID: On Dec 17, 2:31 am, Paul McGuire wrote: > On Dec 17, 1:18 am, "bambam" wrote: > > > > > > > I wish to create a generic container object, devlist, such that > > > devlist.method(arguments) > > > runs as > > > for each dev in devlist.pool: > > dev.method(arguments) > > > and > > s = devlist.method(arguments) > > > runs as > > > for each dev in devlist.pool: > > s.append(dev.method(arguments)) > > > ...but it is outside my ability to do so. > > > Can anyone provide an example of how to do that? > > > Thanks, > > Steve > > Ok, I'll take a stab at it. > > -- Paul > > class DevList(object): > def __init__(self, objs): > self.devpool = objs > > def __getattribute__(self,attrname): > if attrname == "devpool": > return object.__getattribute__(self,attrname) > def ret(*args): > return [ getattr(p,attrname)(*args) for p in > self.devpool ] > return ret > > dl = DevList([1,2,3]) > print dl.__str__() > > prints: > > ['1', '2', '3']- Hide quoted text - > > - Show quoted text - Here's some expanded demo code for the previously-posted DevList class: from math import sqrt class NumberWrapper(object): def __init__(self,value=0): self.value = value def inverse(self): if self.value != 0: return 1.0/self.value else: return None def sqrt(self): return sqrt(self.value) def incrBy(self,offset): self.value += offset return self.value dl = DevList([NumberWrapper(i) for i in range(5)]) print dl.sqrt() print dl.inverse() print dl.incrBy(10) print dl.sqrt() print dl.inverse() prints: [0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0] [None, 1.0, 0.5, 0.33333333333333331, 0.25] [10, 11, 12, 13, 14] [3.1622776601683795, 3.3166247903553998, 3.4641016151377544, 3.6055512754639891, 3.7416573867739413] [0.10000000000000001, 0.090909090909090912, 0.083333333333333329, 0.076923076923076927, 0.071428571428571425] -- Paul From m.gritsch at gmail.com Tue Dec 25 04:43:01 2007 From: m.gritsch at gmail.com (Markus Gritsch) Date: Tue, 25 Dec 2007 10:43:01 +0100 Subject: Python DLL in Windows Folder In-Reply-To: <0f90f7bc-2faa-4a21-99c3-28ad2e074e89@a35g2000prf.googlegroups.com> References: <533b7d320712230652w6bd4e90dv905d7112d337d0fd@mail.gmail.com> <533b7d320712231027h26623fffi3b471b6c85873a64@mail.gmail.com> <4866bea60712241007r1db5de8w75abab3c8a2e024e@mail.gmail.com> <0f90f7bc-2faa-4a21-99c3-28ad2e074e89@a35g2000prf.googlegroups.com> Message-ID: <533b7d320712250143te07c86ch4b47e79c3a55d331@mail.gmail.com> On 24/12/2007, Lie wrote: > > (good programs are not DLL implementation specific Assume an application embedding Python being compiled with MSVC 8.0. It uses the runtime msvcr80.dll. If you now pass objects created in your application to the Python interpreter which is compiled with MSVC 7.1 which uses msvcr71.dll, you are asking for serious trouble. It is not a matter of being a "good program". > If that's the case, just use the MSVC 7.1's compiled code, there won't > be much difference. See above. > If you insist to use your own version (or don't > have a choice), you could instead pack your own DLL, use the local > DLL, and ignore the system's DLL. Yes, that works fine when deploying the application. However, during development it is inconveninent to put our own Python DLL beside our executable every time. Our Python DLL (compiled with MSVC 8.0) is in the PATH. If the original Python DLL would be located in the Python installation folder, there would be no problem. But since it is placed in the system32 folder which is searched before the PATH (http://msdn2.microsoft.com/en-us/library/ms682586(VS.85).aspx), the original Python DLL (compiled with MSVC 7.1) is used instead of your own one. Kind regards, Markus From robert.kern at gmail.com Mon Dec 17 15:27:09 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 17 Dec 2007 14:27:09 -0600 Subject: OpenOpt install In-Reply-To: <89ecef85-b670-40ab-bc8a-74271ff4cff0@y5g2000hsf.googlegroups.com> References: <65e61980-a21b-4ba2-81f2-a2c23ccb43f2@1g2000hsl.googlegroups.com> <89ecef85-b670-40ab-bc8a-74271ff4cff0@y5g2000hsf.googlegroups.com> Message-ID: dmitrey wrote: > Use > python setup.py install People should be able to run the distutils commands independently. What are you trying to achieve with this block of code that follows the setup() call? new_name = 'tmp55' os.rename('scikits', new_name) newPath = [] for directory in sys.path: if not 'scikits' in directory: newPath.append(directory)# something wrong with list.remove() sys.path = newPath import scikits reload(scikits) Path = scikits.__path__[0] NewPath = os.path.join(Path, 'openopt') rmtree(NewPath, True) # True means ignore errors copytree(os.path.join(os.path.curdir, new_name, 'openopt'), NewPath) NewPath = Path compileall.compile_dir(NewPath) os.rename(new_name, 'scikits') This just looks like a really bad idea. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From kf9150 at gmail.com Thu Dec 6 15:21:40 2007 From: kf9150 at gmail.com (Kelie) Date: Thu, 6 Dec 2007 12:21:40 -0800 (PST) Subject: sqlite or xml Message-ID: Hello group, If I need store and use a couple thousand of people's contact info: first name, last name, phone, fax, email, address, etc. I'm thinking of using either sqlite or xml. Which one is better? My understanding is if there is large amount of data, sqlite would be better as far as speed is concerned. But how much data is considered to be "large amount"? Thank you! From aaron.watters at gmail.com Mon Dec 10 10:34:44 2007 From: aaron.watters at gmail.com (Aaron Watters) Date: Mon, 10 Dec 2007 07:34:44 -0800 (PST) Subject: Best way to merge/sort two sorted lists?... References: <1230064b-603d-4386-b68c-a913c5cf80d3@s12g2000prg.googlegroups.com> <60572417-9e83-4d0c-80da-2c99a9bd19e4@b40g2000prf.googlegroups.com> Message-ID: <65f52a5f-f16d-4fde-be25-20edf31d5fe9@d4g2000prg.googlegroups.com> On Dec 6, 2:01 pm, Raymond Hettinger wrote: > On Dec 6, 9:30 am, Aaron Watters wrote: > > See recipes: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491285 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305269 I previously noted in that I found the first recipe slow and obscure. Raymond pointed out privately that it is designed to minimize memory requirements when merging possibly many files from a filesystem. It does that very well, and I apologize for the offensive tone of my comment. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=cryptic+code+performance+hacks From deets at nospam.web.de Sun Dec 30 17:32:48 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 30 Dec 2007 23:32:48 +0100 Subject: What is the best way to do dynamic imports ? In-Reply-To: References: Message-ID: <5tqkl1F1e90dvU1@mid.uni-berlin.de> marcroy.olsen at gmail.com schrieb: > First of thanks to all for you, especially for the quick replys. > > Just need to walk the dog then I giv it a short. Please, don't kill your dog! We're a peace-loving community here that respects dogs, and snakes and even trolls. SCNR, Diez From ndbecker2 at gmail.com Fri Dec 14 10:29:59 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 14 Dec 2007 10:29:59 -0500 Subject: simple string formatting question Message-ID: I have a list of strings (sys.argv actually). I want to print them as a space-delimited string (actually, the same way they went into the command line, so I can cut and paste) So if I run my program like: ./my_prog a b c d I want it to print: './my_prog' 'a' 'b' 'c' 'd' Just print sys.argv will almost work, but it's comma-delimited. There must be some clever way to do this. Any ideas? From damonjulian at yahoo.com Tue Dec 25 09:50:28 2007 From: damonjulian at yahoo.com (damonjulian at yahoo.com) Date: Tue, 25 Dec 2007 06:50:28 -0800 (PST) Subject: why does a disabled button respond to clicks References: <9168ecd1-1100-47db-83b7-6e3f04a44cd3@d21g2000prf.googlegroups.com> <476f89d3$0$85782$e4fe514c@news.xs4all.nl> Message-ID: thank you for the reply..that solves my problem damon From tamim.shahriar at gmail.com Sat Dec 22 22:58:10 2007 From: tamim.shahriar at gmail.com (subeen) Date: Sat, 22 Dec 2007 19:58:10 -0800 (PST) Subject: 5 queens References: <9639f80c-5722-40c6-bd7b-b727d0a7804e@n20g2000hsh.googlegroups.com> Message-ID: Hi, The problem you are trying to solve is a very famous and common problem which can be solved by backtracking. Please try google with 8 queens problem or n queens problem. > > I designed in JavaScript a small program on my website called 5 > queens. > (http://www.cf29.com/design/dame5_eng.php) > > The goal is to control all the chess board with five queens that do > not attack each other. I found "manually" many solutions to this > problem (184 until now) and wanted to create a Python script to find > them all. As I am new to Python, I struggle a lot. > > I found a way to create: > - a board where each square is defined by its row, column and if it is > controlled or not > - a function that tells which squares are controlled by a queen on a > particular square > - a function that counts how many squares are controlled > - a function that can reset all squares control to 0 > - a function that can place 5 queens safely on the board > - I can find the first solution and register it in a list > > My problem starts now. How can I find the next solution and append it > to the list? Has anyone tried to do a such script? If anyone is > interested to help I can show what I've done so far. Try to generate the next permutation and check if it's a valid solution. Need to use recursion for this. regards, Subeen. From arnodel at googlemail.com Sun Dec 23 03:18:10 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 23 Dec 2007 00:18:10 -0800 (PST) Subject: Modify arguments between __new__ and __init__ References: <13mrr0dl4mjnh0c@corp.supernews.com> Message-ID: <23ead0bf-b27d-4374-a169-4f692cf07479@l1g2000hsa.googlegroups.com> On Dec 23, 5:03?am, Steven D'Aprano wrote: > When you call a new-style class, the __new__ method is called with the > user-supplied arguments, followed by the __init__ method with the same > arguments. > > I would like to modify the arguments after the __new__ method is called > but before the __init__ method, somewhat like this: > > >>> class Spam(object): > > ... ? ? def __new__(cls, *args): > ... ? ? ? ? ? ? print "__new__", args > ... ? ? ? ? ? ? x = object.__new__(cls) > ... ? ? ? ? ? ? args = ['spam spam spam'] > ... ? ? ? ? ? ? return x > ... ? ? def __init__(self, *args): > ... ? ? ? ? ? ? print "__init__", args ?# hope to get 'spam spam spam' > ... ? ? ? ? ? ? return None > > but naturally it doesn't work: > > >>> s = Spam('spam and eggs', 'tomato', 'beans are off') > > __new__ ('spam and eggs', 'tomato', 'beans are off') > __init__ ('spam and eggs', 'tomato', 'beans are off') > > Is there any way to do this, or am I all outta luck? > > -- > Steven The ususal way is to override the __call__ method of the metaclass. HTH -- Arnaud From gc284 at vif.com Sun Dec 2 20:00:15 2007 From: gc284 at vif.com (Gordon C) Date: Sun, 2 Dec 2007 20:00:15 -0500 Subject: Limit Guessing Algorithm References: <6527e349-27ba-4de4-bc29-75ff4511787c@b40g2000prf.googlegroups.com> <7xtzn022c4.fsf@ruckus.brouhaha.com> <1fe85625-a278-401f-8a9f-ccd8a29276bf@w34g2000hsg.googlegroups.com> <7x63zgoiv8.fsf@ruckus.brouhaha.com> <6806734e-e28f-415d-8a34-fc45ccb33caf@x69g2000hsx.googlegroups.com> Message-ID: <1196694675.909255@www.vif.com> One of the difficulties of this kind of a problem is that one is looking for a solution to a limited number of data points for which it may be possible to define a function. There can never be a guarantee that the chosen "fit" can be reliably extrapolated. You need to tie a possible solution to the realworld characteristics of that data. Just taking a bunch of data by itself cannot be sufficient. Gord From rw at smsnet.pl Thu Dec 6 12:57:50 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Thu, 06 Dec 2007 18:57:50 +0100 Subject: pipeline encoding References: Message-ID: <871w9zln8h.fsf@merkury.smsnet.pl> Tomasz Toczyski writes: > My locale is set to UTF-8. The command: > python -c "print u'\u03A9'" > gives me the desired result and doesn't produce any error. > > But when I want to redirect the output to a file I invoke: > python -c "print u'\u03A9'" > file.txt > I get an error: > > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\u03a9' in > position 0: ordinal not in range(128) > > How to cope with it? If you print to a terminal Python can use terminal encoding, but if you redirect to a file Python doesn't know what encoding to use (e.g. how was encoded existing file) and refuses to guess. You have to specify that encoding explicit: python -c "print u'\u03A9'.encode('utf-8')" > file.txt HTH, Rob From gnewsg at gmail.com Fri Dec 21 17:23:19 2007 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Fri, 21 Dec 2007 14:23:19 -0800 (PST) Subject: Understanding memory leak reports References: Message-ID: <219ccd88-6656-4b2a-a6f7-42932fdb25b0@l1g2000hsa.googlegroups.com> On 21 Dic, 20:10, kyoso... at gmail.com wrote: > On Dec 21, 12:44 pm, "Giampaolo Rodola'" wrote: > > > > > > > Hi, > > I'm in a big trouble since I don't know how to find some memory leaks > > I just discovered in a program of mine. > > By putting: > > > import gc > > gc.set_debug(gc.DEBUG_LEAK) > > > ..at the end of a script which imports a module I wrote it seems I > > have some memory leaks scattered around. > > The message printed on screen is the following: > > > gc: collectable > > gc: collectable > > gc: collectable > > gc: collectable > > gc: collectable > > gc: collectable > > gc: collectable > > > Since the main module is very big (more than 2800 lines of code) I do > > not understand which objects are not garbage collected. > > Is there a way to have a more detailed message to know which objects > > are not garbage collected? > > For example "function foo", "method MyClass.bar", "dict my_dict"... > > "function 00C70E70" and "tuple 00C09900" are too much generic messages > > which don't give me an idea about where the leak could be. > > I've never done this before, but here's what I found while Googling: > > Recipe that supposedly gives more info:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65333 > > Another thread on the same topic that looks quite detailed:http://www.thescripts.com/forum/thread22097.html > > An article or two on memory leaks in Python:http://utcc.utoronto.ca/~cks/space/blog/python/DebuggingPythonMemoryL...http://www.nightmare.com/medusa/memory-leaks.html > > I hope they help. > > Mike- Nascondi testo tra virgolette - > > - Mostra testo tra virgolette - Thanks for your search but I haven't actually found a solution yet. I've tried to search into the cookbook. I found other recipes playing with the gc module but it seems that none of them are useful for finding out the names of the objects causing the memory leak. I've tried to play with gc.get_objects() in the hope to find the real names manually but it returns a very large number of objects. If only I could find a way to make gc.get_objects() returning leaking objects only it would be a step forward... Does someone have an idea about how doing such a thing? From robin at NOSPAMreportlab.com Sat Dec 8 11:46:47 2007 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Sat, 08 Dec 2007 16:46:47 +0000 Subject: distutils & OS X universal binaries In-Reply-To: <475ab088$0$19620$9b622d9e@news.freenet.de> References: <475AA774.7020904@jessikat.plus.net> <475ab088$0$19620$9b622d9e@news.freenet.de> Message-ID: <475ACA77.5030802@jessikat.plus.net> Martin v. L?wis wrote: ......... > > In the specific case, just use the WORDS_BIGENDIAN macro defined in > pyconfig.h; it will be defined if the target is bigendian, and > undefined otherwise. In the case of a universal build, it will be > undefined in the x86 compiler invocation, and defined in the ppc > invocation. > > If you are curious as to how it arranges that, read the source. ...... OK I read the source and am slightly puzzled by the code in pyconfig.h.in which reads #ifdef __BIG_ENDIAN__ #define WORDS_BIGENDIAN 1 #else #ifndef __LITTLE_ENDIAN__ #undef WORDS_BIGENDIAN #endif #endif I'm puzzled why WORDS_BIGENDIAN is undefined if both __BIG_ENDIAN__ and __LITTLE_ENDIAN__ are undefined. Surely in that case WORDS_BIGENDIAN should be left alone (if it is already defined). If there's a compiler for a bigendian architecture which doesn't define the gcc macros the we seem to get the wrong result. -- Robin Becker From senux at senux.com Sun Dec 9 11:23:37 2007 From: senux at senux.com (Seongsu Lee) Date: Sun, 9 Dec 2007 08:23:37 -0800 (PST) Subject: searching a value of a dict (each value is a list) Message-ID: Hi, I have a dictionary with million keys. Each value in the dictionary has a list with up to thousand integers. Follow is a simple example with 5 keys. dict = {1: [1, 2, 3, 4, 5], 2: [10, 11, 12], 900000: [100, 101, 102, 103, 104, 105], 900001: [20, 21, 22], 999999: [15, 16, 17, 18, 19]} I want to find out the key value which has a specific integer in the list of its value. For example, if I search 104 in the list, 900000 must be returned. How can I do this with Python? Ideas? From msunderwd at gmail.com Wed Dec 5 09:50:00 2007 From: msunderwd at gmail.com (msunderwd at gmail.com) Date: Wed, 5 Dec 2007 06:50:00 -0800 (PST) Subject: Tkinter vs. py2exe problem Message-ID: <4ac67d5e-1969-48c5-8bec-85327f91498b@t47g2000hsc.googlegroups.com> Having a problem with "compiling" a Tkinter/python program using py2exe (and pyinstaller, for that matter)... I have several dialogs that are derived from the tkSimpleDialog.Dialog class. These work just fine if run through the interpreter. When I "compile" this with py2exe, I don't see any errors, and when I execute the resulting program, it "appears" to work fine until I invoke one of the derived dialogs. Then, I get the "body" of the dialog, but no "OK" or "Cancel" button, and I get the following exception: AttributeError: MyDialog instance has no attribute 'buttonbox' For reference, MyDialog is declared as follows: #-------------------------------------------------------------------------------- from Tkinter import * import tkSimpleDialog class MyDialog(tkSimpleDialog.Dialog) #-------------------------------------------------------------------------------- And my setup.py file looks like this: #-------------------------------------------------------------------------------- from distutils.core import setup import py2exe setup(console=['tcgui3.py']) #-------------------------------------------------------------------------------- I'm invoking py2exe like this: C:\python setup.py py2exe -p Tkinter -p tkSimpleDialog ?????? From perosine at gmail.com Sat Dec 29 04:53:38 2007 From: perosine at gmail.com (Petar) Date: Sat, 29 Dec 2007 01:53:38 -0800 (PST) Subject: OOP: How to implement listing al 'Employees'. References: <6a600f6a-76f1-4397-9fc8-6f5bab63913a@f53g2000hsg.googlegroups.com> <13nagskoscc5fad@corp.supernews.com> Message-ID: <05b3c0a6-7985-4f0c-b4a9-5ffa59993b43@v32g2000hsa.googlegroups.com> On 28 dec, 19:42, Dennis Lee Bieber wrote: > On Fri, 28 Dec 2007 04:05:59 -0800 (PST), Petar > declaimed the following in comp.lang.python: > > > I was just wondering. > > > What if you have a 'Employees' class and you want to list all the > > employees. Currenlty i'm seeing to possibilities: > > > - create a 'listAll' function inside the class which returns all the > > employees in a array. > > - create multiple instances, putting them in a array, by calling the > > Employees class multiple times in a loop (thus not creating a listAll > > function in the class). > > > What is the better way of doing this? And should a class always > > reference only on 'item'? > > ? ? ? ? Bottom-up responses... > > ? ? ? ? Unless you are contaminated by Java's need for a class to hold > static functions, classes are just templates for an undefined object. > You create an instance of the class to create a defined object. It is > not common in Python to create a class that is not meant to be > instantiated at least once (something that is just static methods is > probably easier implemented as an import module with plain functions and > module level globals). > > ? ? ? ? Now, by "name", an "Employees" (plural s) class, to me, implies a > class to represent a group of employees -- as a group! It would NOT have > methods or members (both of which are just attributes in generic Python > hissing) that refer to information about any specific employee -- such > information should be part of an "Employee" (no S) class. > > aDept = Employees(dept="Finance") > aDept.manager = Employee(name="John Dont", ID=3141596, phone="123-4567") > aDept.addEmployee(Employee(name=....)) > aDept.addEmployee(Employee(...)) > ... > ? ? ? ? Note that this does not enforce any particular storage concept. The > Employees (with the S) class could be using a list to store each > employee, or a dictionary (maybe keyed by ID), or even an RDBM with a > join (where one has tables for, say, department, employee, and > intersection linking department to employee): > > select e.* from employees as e > inner join dept_employee as de > on de.empID = e.ID > inner join departments as d > on d.id = de.deptID > where d.name = "Finance"; > > aBody = aDept.employee(id=....) > > aDept.removeEmployee(id=...) > > aDept.printEmployees() > > ? ? ? ? If all you need is a "list" of raw employees, with no meaning > associated to the list... Then just use a list... > > aList = [] > aList.append(Employee(name=...)) > aList.append(Employee(...)) > > for e in aList: > ? ? ? ? e.printEmployee() > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ I'm sorry if my question wasn't clear enough. But I think it has been answered. Let me explain how I got to this question. I had written een Article class which handled the articles that I had. On a certain page I wanted to show all the articles. That got me wondering about what to do. Should I make a method in my Article.class which returned multiple articles, or should I just use my current Article.class and fill a list (with a loop) with articles. The first solution thus meaning writing another method, the latter method to just use the current Article.class and call it multiple times. The post of Dennis made me realize of another solution though. To create another class called Articles which return multiple articles. The only problem I forsee with this that's it's gonna be a very empty class. Thank you all for your response, it has pointed me in the right direction. From bdesth.quelquechose at free.quelquepart.fr Fri Dec 21 16:46:33 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 21 Dec 2007 22:46:33 +0100 Subject: detecting property modification In-Reply-To: References: Message-ID: <476c343d$0$5462$426a34cc@news.free.fr> Mangabasi a ?crit : (snip) > > When you say "The Body gets asked for the value of the attribute" that > means that Body's __dict__ is being asked to provide a value > corresponding to its 'pos' key, right? Wrong. That means that attribute lookup rules are invoked, which may *or not* end up calling the Body *intance*'s __dict__ __setitem__ method to be called. Anyway: > Now I may want to ask a more > specific question here. How do I modify Body's __dict__ so that I can > perform a task when __getitem__ method of the __dict__ is called? This still won't solve your problem. What you want to trace are method calls on the objects returned by attribute lookup on instances of Body - not calls to instances __dict__ methods. In your example, what you want to trace are calls to pos.__getitem__, not calls to b.__dict__.__getitem__. And if you what you really want is to trace any mutator call to any arbitrary object that may become an attribute of b, then I'm afraid you're in for a hard time... From nobody at heavilyweeded.com Fri Dec 21 20:14:52 2007 From: nobody at heavilyweeded.com (Anton Tropashko) Date: Fri, 21 Dec 2007 19:14:52 -0600 Subject: 2.5.1 rpms? In-Reply-To: <467d0168-d3d2-464b-ba14-46741dce1437@a35g2000prf.googlegroups.com> References: <467d0168-d3d2-464b-ba14-46741dce1437@a35g2000prf.googlegroups.com> Message-ID: gamename wrote: > Hi, > > Where can I find python 2.5.1 rpm's for redhat9 and fedora6/7? did you check on the fedora7 dvd? btw building from sources if completely straigtforward (meaning that it does not build character and leaves your with a sense of accomplishment the way building x.org code does) From sean.berry at cox.net Tue Dec 18 14:41:12 2007 From: sean.berry at cox.net (Breal) Date: Tue, 18 Dec 2007 11:41:12 -0800 (PST) Subject: Funny python cartoon... hope it's not a repost Message-ID: <231a52e2-3ce4-490f-a519-bed52201ba6d@i29g2000prf.googlegroups.com> http://xkcd.com/353/ From martin at v.loewis.de Fri Dec 28 04:58:37 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 28 Dec 2007 10:58:37 +0100 Subject: Python DLL in Windows Folder In-Reply-To: References: <533b7d320712230652w6bd4e90dv905d7112d337d0fd@mail.gmail.com> <47744b3a$0$32140$9b622d9e@news.freenet.de> <477467f9$0$20364$9b622d9e@news.freenet.de> Message-ID: <4774c8ce$0$4658$9b622d9e@news.freenet.de> > As I said before, I know how futile it is to argue that Python should > change it's behaviour. I'm not going to waste my time telling you what > to do. If you really want to know how side-by-side installation works, > you can try reading the Windows SDK documentation. I did, and determined that it's not possible. We would have to use assembly manifests, and can't, as the tool chain doesn't support them. > No, simply by changing the name you've prevented backwards compatiblity > with the old DLL. First, the requirement for backwards compatibility is not normative. Section 2.6 is entitled "Install any shared files that are not side-by-side to the correct locations". python25.dll, as a matter of fact, *is* a shared file that is not side-by-side; the *only* location I can install in according to 2.6 is the System folder. > You can't argue you're trying to maintain backwards > compatibilty with an old DLL when you've already broken compatibility > with it. Furthermore, it says "to ensure backward compatibility with those applications", not "to ensure backward compatibility with the old DLL". I'm not trying to maintain compatibility with the binaries of those applications, but with their source. > Since the existing applications have to be rebuilt to use the > new DLL they also can be changed to use it from a new shared location. No, they can't, because there is not enough manpower available to change them. Regards, Martin From pavlovevidence at gmail.com Wed Dec 19 17:13:57 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 19 Dec 2007 14:13:57 -0800 (PST) Subject: In an inherited class, "embedded" classes is referenced? References: <877ijabcpt.fsf@jamie.razor.dk> Message-ID: On Dec 19, 4:23 pm, Christian Joergensen wrote: > Hello > > I stumpled upon this "feature" during my work tonight, and found it > a bit confusing: > > >>> class A(object): > > ... class C: > ... foobar = 42 > ...>>> class B(A): pass > ... > >>> A.C > > >>> B.C > > >>> B.C.foobar = 60 > >>> A.C.foobar > > 60 > > When I inherit B from A, I would expect that A.C and B.C would be two > different classes? But apparently not. No, when a class inherits a class member from a subclass, both classes reference the same object. This is true of any object: classes, lists, sets, etc. For instance, if you were to do this, class A(object): class C(object): pass d = [1,2,3,4] e = set(("a","b","c","d")) class B(A): pass Then you would find that A.C is B.C A.d is B.d A.e is B.e They are all the same object. Perhaps you are misled by the example methods? Even them, the same function object is referenced by both classes. The difference is, when accessing a method, a class doesn't return the function object itself, but a method object instead (which is a binding between a function and a class, used to set the value of "self" when calling it). But only functions do something like that, not classes. > Can anyone give me an explanation? Or a better workaround than > something along the line of: > > >>> B.C = type("C", (object,), {'foobar': 60}) Well you could do this and not bother with the type call (but you'd still have to do it by hand). class B(A): class C(A.C): foobar = 60 Metaclass programming, or at least some clever properties, would be required to do it automatically. You could try something like this (untested) to automatically subclass any class variables that are instances of type: class AutoSubclassMetaclass(type): def __new__(cls,name,bases,clsdict): for key,value in clsdict.iteritems(): if isinstance(value,type): clsdict[key] = type(value.__name__,(value,),{}) type.__new__(cls,name,bases,clsdict) class A(object): __metaclasS__ = AutoSubclassMetaclass class C(object): foobar = 40 class B(A): pass Carl Banks From tinnews at isbd.co.uk Tue Dec 11 16:15:04 2007 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: 11 Dec 2007 21:15:04 GMT Subject: mailbox.Maildir question/problem Message-ID: <475efdd8$0$514$bed64819@news.gradwell.net> I am trying to write a utility to remove empty maildir mailboxes. It sounds like this should be very simple but it's proving really difficult. I'm doing this on a Fedora 7 system with python 2.5. The first question is how to detect whether a directory is a maildir mailbox. The following code snippet *never* says that a directory is not a maildir:- try: x = mailbox.Maildir(dirpath, None, False) except: print dirpath, "is not a maildir" The "x = mailbox.Maildir(dirpath, None, False)" always succeeds even when dirpath is most definitely *not* a maildir (i.e. it doesn't have cur, new and tmp sub-directories). It's only when you try calling a method of x that an exception results. The second question is how to manage a hierarchy of directories with maildirs in them. For example I have:- Mail Mail/bcs Mail/ben Mail/cg Mail/spam Mail/usenet Where bcs ben cg spam usenet are maildir mailboxes, I can't get python's mailbox.Maildir to do anything useful with them at all. My test program currently is:- #!/usr/bin/python # # # Remove empty maildir mailboxes # import mailbox import os.path import sys def checkDir(dummy, dirpath, filelist): print "Directory is ", dirpath try: x = mailbox.Maildir(dirpath, None, False).list_folders() except: print dirpath, "is not a maildir" return for msg in x: print msg for d in sys.argv[1:]: if os.path.isdir(d): os.path.walk(d, checkDir, None) It would seem that the list_folders() method only works with the Courier style maildirs where the diretory name of the maildir starts with a dot. Is there *any* way I can get python to access maildirs which are not named using this (IMHO stupid) convention? I know my test program is far from complete but I can't get it to do anything sensible at present. -- Chris Green From awnl at arcor.net Mon Dec 3 05:03:28 2007 From: awnl at arcor.net (Albert Retey) Date: Mon, 03 Dec 2007 11:03:28 +0100 Subject: Limit Guessing Algorithm In-Reply-To: <6527e349-27ba-4de4-bc29-75ff4511787c@b40g2000prf.googlegroups.com> References: <6527e349-27ba-4de4-bc29-75ff4511787c@b40g2000prf.googlegroups.com> Message-ID: <4753d471$0$16667$9b4e6d93@newsspool3.arcor-online.net> Hi, > > I'm looking for a piece of code, preferably in Python, that will do > the following. It will accept a few data points (x,f(x)) of a function > that converges to some finite value when x converges to infinity. I > need the algorithm to guess what that limit is, to whatever precision > it can. > > For example, if the input is: > > [ > [1,8], > [2,7.5], > [3,7.25], > [4,7.125] > ] > > Then the output will be 7. Or at least something close. > > Does anyone know anything like that? It is obvious that in general this is an unsolvable problem. But if you know for some reason that your series/functions are "well behaved" in some sense it still might be possible to do something reasonable and there has some work been done on these things. You might e.g. google for Wynns epsilon method which gives some examples and references for related stuff. hth, albert From tjreedy at udel.edu Sun Dec 9 22:26:44 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 9 Dec 2007 22:26:44 -0500 Subject: Is a "real" C-Python possible? References: <7tOdnRb-5fMW_MHanZ2dnUVZ_tmhnZ2d@comcast.com> Message-ID: "Jack" wrote in message news:vLadnbUkzunUHsHanZ2dnUVZ_judnZ2d at comcast.com... | The second articple does have a column for Psyco. It helps in some areas | but still not good enough to stand up against Java. Plus, Psyco is not the | main stream and has stopped development. It further development is effectively part of the PyPy project, which includes some jit work. | I'm also wondering, if Psyco is the right way to do, any reason it's not | being integrated into standard Python? It does not accelerate everything and may slow somethings, it was (is?) not compatible with everything, it bloats space requirements, it competes with C/Fortran coded extensions (such as NumPy), it was originally I386 specific, its development cycle was much faster than Python's release cycle, ... The cutoff between what goes in the core/stdlib is arbitrary in borderline cases, but some cutoff is necessary. tjr From mark.english at rbccm.com Wed Dec 19 04:28:03 2007 From: mark.english at rbccm.com (MarkE) Date: Wed, 19 Dec 2007 01:28:03 -0800 (PST) Subject: operator module isSequenceType with builtin set produces False References: <15e46d41-7534-4d9a-8939-bb3a8bf11ca0@e23g2000prf.googlegroups.com> Message-ID: On 19 Dec, 10:03, MarkE wrote: > > No, sets aren't sequences, as they have no order. Same as dicts, which > > aren't sequences either. > > Oops. I was under the misapprehension that they were sequences I realise now that this is even explicitly documented: http://docs.python.org/lib/typesseq.html "There are six sequence types: strings, Unicode strings, lists, tuples, buffers, and xrange objects." > Is there a short Pythonic way to determine whether an object is > iterable (iteratable ??) that I haven't thought of (getattr(obj, > '__iter__') ?). Would operator.isIterable() be at all a useful > addition ? And here I probably meant container (although the url says sequence when the article meant container, bit like me): http://docs.python.org/ref/sequence-types.html "Containers usually are sequences (such as lists or tuples) or mappings (like dictionaries), but can represent other containers as well" So same question, but perhaps "isContainer()" rather than "isIterable()" From sgeiger at ncee.net Thu Dec 20 03:47:48 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Thu, 20 Dec 2007 02:47:48 -0600 Subject: Problem untaring python2.5 In-Reply-To: <31e0c4b8-e720-4340-8ea5-aa57f89245b3@w56g2000hsf.googlegroups.com> References: <8e5c1fd6-8060-4df0-80d3-51a716693dc5@i29g2000prf.googlegroups.com> <31e0c4b8-e720-4340-8ea5-aa57f89245b3@w56g2000hsf.googlegroups.com> Message-ID: <476A2C34.4090403@ncee.net> You might want to try an all-python implementation for sanity testing. I haven't tested this snippet much. I am not sure it handles nested files all that well. import tarfile tar = tarfile.open("TarTest.tar.gz2", "r:gz") # other options: "r:bz2", and ?? file_list = tar.getnames() import os os.mkdir('new_dir') # write the files out to new files for fname in tar.getnames(): # extract/decompress the data of each file data = tar.extractfile(fname).read() # optionally change the filename new_file = "new_dir/" + fname print "File %s written!" % new_file # write the decompressed data to a file fout = open(new_file, "w") fout.write(data) fout.close() # done, close the tar file ... tar.close() > On Dec 19, 12:16 pm, samuel.pro... at gmail.com wrote: > >> Hello, >> >> It is not possible to give sharp hints without more relevant >> information like: >> - What is your platform? >> - Which version of python? >> - What is the version of: $tar--version (GNUtar, other proprietarytar, according to my personal experience, AIXtarmay fail) >> - Is your disk full or do you have the correct permissions with your >> current user? >> >> ++ >> >> Sam >> > > Hi Sam , > I am using windows server 2003, python2.5.1 and version 1.16 of tar > > and as per disk full issues i dont think that my systems hard disk is > full > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Dec 7 07:22:02 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 07 Dec 2007 13:22:02 +0100 Subject: File to dict In-Reply-To: References: Message-ID: <47593ae3$0$14897$426a74cc@news.free.fr> mrkafk at gmail.com a ?crit : > Hello everyone, (snip) > Say, I would like to transform a file containing entries like > the following into a list of lists with doublecolon treated as > separators, i.e. this: > > tm:$1$aaaa$bbbb:1010:6::/home/owner1/imap/domain1.tld/tm:/sbin/nologin > > would get transformed into this: > > [ ['tm', '$1$aaaa$bbbb', '1010', '6', , '/home/owner1/imap/domain1.tld/ > tm', '/sbin/nologin'] [...] [...] ] The csv module is your friend. From danb_83 at yahoo.com Sat Dec 29 15:31:49 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Sat, 29 Dec 2007 12:31:49 -0800 (PST) Subject: Optional code segment delimiter? References: Message-ID: <0c5ef982-309d-4ba9-b783-c3af814d76e3@s8g2000prg.googlegroups.com> On Dec 29, 12:41 pm, Matt Nordhoff wrote: > xkenneth wrote: > > Is it possible to use optional delimiters other than tab and colons? > > > For example: > > > if this==1 { > > print this > > } > > > > Heheheh.. Wow! I never thought of (ab)using encodings like that. And sure enough, it's perfectly legal to write: # -*- encoding: rot-13 -*- cevag h"Uryyb, jbeyq!" From cjw at sympatico.ca Sat Dec 8 10:23:59 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 08 Dec 2007 10:23:59 -0500 Subject: a Python person's experience with Ruby In-Reply-To: <17975.12459.qm@web33510.mail.mud.yahoo.com> References: <17975.12459.qm@web33510.mail.mud.yahoo.com> Message-ID: <475AB70F.4060408@sympatico.ca> Steve Howell wrote:> Thanks for the interesting comparison. [snip] > 3) I actually like being able to omit parentheses in > method definitions and method calls. In Ruby you can > express "add(3,5,7)" as both "add(3,5,7)" and "add 3, > 5, 7." The latter syntax is obviously more error > prone, but I don't think I've ever actually gotten bit > by it, and the code appears more clean to me. > [snip] I'm not sure that I like add 3, 5, 7 but it would be nice to be able to drop the parentheses when no argument is required. Thus: close; could replace close(); Colin W. From bdesth.quelquechose at free.quelquepart.fr Fri Dec 28 13:23:53 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 28 Dec 2007 19:23:53 +0100 Subject: Compiler or stg. to get exe! In-Reply-To: References: Message-ID: <47753f39$0$32454$426a74cc@news.free.fr> SMALLp a ?crit : > Hy! > I have question. After short goggling, I haven't found anything good. So > my question is: > I wrote a program in python and i Get .py files and some .pyc in working > folder. Now i want program tu run under windows, so i need to get exe > files or something. Strictly speaking, you don't *need* this. Now depending on the target audience of your app, you may want to provide a "black-box" bundle of your app and all the dependencies, including the python runtime. AFAICT (not being a Window user), py2exe might be what you're looking for. > And what do i need to do to make program for linux. (stg. like .deb > package) A debian package (or any other similar stuff) is not a "program", it's distribution system format. You'll find relevant doc on the related distribution system. Note that almost each linux distro has it's own system... Anyway, since part of your audience may include "power users", don't forget to also provide either a simpler distrib using either distutils and/or setuptools (Python Egg): http://docs.python.org/dist/dist.html http://peak.telecommunity.com/DevCenter/setuptools http://peak.telecommunity.com/DevCenter/PythonEggs HTH From showell30 at yahoo.com Sat Dec 8 20:25:12 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 8 Dec 2007 17:25:12 -0800 (PST) Subject: auto-increment operator - why no syntax error? In-Reply-To: <5s0tqlF16tekoU2@mid.uni-berlin.de> Message-ID: <136678.20766.qm@web33512.mail.mud.yahoo.com> --- Marc 'BlackJack' Rintsch wrote: > On Sat, 08 Dec 2007 16:58:25 -0800, Karthik Gurusamy > wrote: > > > Why are the following accepted even without a > warning about syntax > > error? > > (I would expect the python grammar should catch > these kind of syntax > > errors) > >>>> 2 * +++++ n Does pychecker catch this? Although I see why the language allows it, my guess is that most people chain unary plus operations accidentally, not intentionally. ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs From horpner at yahoo.com Wed Dec 12 13:07:12 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 12 Dec 2007 18:07:12 GMT Subject: __init__ method for containers References: <2599b4c4-fa78-4047-89a6-d6803e9c52f0@l1g2000hsa.googlegroups.com> Message-ID: On 2007-12-12, Raymond Hettinger wrote: > On Dec 12, 7:22 am, Neil Cerutti wrote: >> List and deque disagree on what __init__ does. Which one is >> right? > > File a bug report and assign to me. Will do. Registration in progress. -- Neil Cerutti From mensanator at aol.com Sat Dec 15 12:42:06 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sat, 15 Dec 2007 09:42:06 -0800 (PST) Subject: Convert a sequence of bits to a bit-string References: <90d507ea-08cb-4311-9b44-57f6cccd4918@i29g2000prf.googlegroups.com> Message-ID: On Dec 15, 10:39?am, te... at york.ac.uk wrote: > First of all I'd like to thank you all for your advices. Before I check all > your hints I want to clarify what I'm trying to do. The question says > "write a function that takes a sequence of bits as an input and return how > many 1s are in the sequence", nothing more. Except that there is no such thing in Python as there is no binary representation. You could enter a sequence of characters, where each character represents a bit, such as s='1111' for 15. > This is quite simple for string > inputs but tricky for "number inputs". I've notice that if I try to convert > a number starting with 0 to a string using str(), then I take a string > representing another number (probably converted to decimal). So what I want > to do is to write a generic version of a function that takes as an input a > sequence of 1s and 0s in any format. That's probably not what you want. You don't want to enter 1's and 0's in any format, you want to accept a number in any format. Remember, the format does not change the number (assuming you always use the correct format representation). So if the input is s=017 (octal), the number is fifteen. If s=0xf (hexadecimal), the number is fifteen. If s=15 (decimal), the number is fifteen. Once you've got that straight, you can calculate the base 2 representation of fifteen and count the ones. > The only way I can think to achieve > that is by converting the "number inputs" to a string and then using the > count() function. Do you know how base conversion is done manually? In base 2, each bit represents a power of 2, and there are only two possibilities for each digit, 0 and 1. So, in base 2, the digit positions are ... 2**7 2**6 2**5 2**4 2**3 2**2 2**1 2**0 128 64 32 16 8 4 2 1 Now, for fifteen, what's the largest position that doesn't exceed 15? The fourth (counting from the right). Therefore, there's a 1 bit in position four and all higher positions would be 0. At this point, we have '1???'. To get the next lower position, subtract 8 from fifteen, leaving seven. Now repeat until you fill all positions, eventually reaching '1111'. But, if the highest position that doesn't exceed skips some positions, then those positions have '0'. So for nine, the highest position is still the fourth, giving us '1???'. But after subtracting eight, we're left with one. But the highest position not exceeding one is the first, giving us '1??1'. We skipped positions 2 & 3, so they must be '0' making nine '1001' in base 2. Now all you have to do is count the 1's. However, if doing > Thomas From martin at v.loewis.de Wed Dec 19 14:27:53 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 19 Dec 2007 20:27:53 +0100 Subject: Static linking of python and pyqt In-Reply-To: <200712191326.51407.dahlbokum@intes.de> References: <200712191147.45256.dahlbokum@intes.de> <4768FB1E.3040204@v.loewis.de> <200712191326.51407.dahlbokum@intes.de> Message-ID: <476970B9.9000805@v.loewis.de> > I need an environment that can be delivered to our customers without > installing python, qt and pyqt. We want to provide the complete package. > In order to do so I need to link at least python and qt. How can this be done? You should link all extension modules into the Python executable, through Setup.local > Of course a complete package with python, qt and pyqt would be the best > solution but there seem to be even more complications that way. If you can > help me with this I would be very grateful. Not sure. You didn't explain what the precise problem is, so it's difficult to help in correcting it. Regards, Martin From george.sakkis at gmail.com Fri Dec 14 11:55:55 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 14 Dec 2007 08:55:55 -0800 (PST) Subject: Job Offer: Python Ninja or Pirate! References: <475d8f43$0$31216$9b622d9e@news.freenet.de> <475e0cf6$0$19333$9b622d9e@news.freenet.de> <7bcbdd36-f4f1-419f-9866-b9c06dcf9b38@b1g2000pra.googlegroups.com> <476299ee$0$4006$9b622d9e@news.freenet.de> Message-ID: <91a9d2fc-3e22-4d11-9a62-8b21829536d9@d21g2000prf.googlegroups.com> On Dec 14, 9:57 am, Stargaming wrote: > On Tue, 11 Dec 2007 08:57:16 -0800, George Sakkis wrote: > > Closer, but still wrong; for some weird reason, __import__ for modules > > in packages returns the top level package by default; you have to use > > the 'fromlist' argument: > > >>>> __import__('xml.dom.minidom') is __import__('xml') > > True > > >>>> __import__('xml.dom.minidom', fromlist=True) > > > minidom.pyc'> > > > George > > No, it's perfectly right:: > > >>> __import__('xml.dom.minidom').dom.minidom > '/usr/lib/python2.5/xml/dom/minidom.pyc'> Sure, if you remember to repeat all.the.subpackages.after.the.top. Instead of __import__ I use a more intuitive and general version that doesn't stop at module boundaries but acts as getattr() within a module: for name in ['xml', 'xml.dom', 'xml.dom.minidom', 'xml.dom.minidom.parse', 'xml.dom.minidom.parse.__name__']: print '%s: %r\n' % (name, import_name(name)) #### output xml: xml.dom: xml.dom.minidom: xml.dom.minidom.parse: xml.dom.minidom.parse.__name__: 'parse' #=== import_name ============================= def import_name(name, globals={}, locals={}): prefix,sep,tail = name.partition('.') obj = __import__(prefix, globals, locals) is_module = True while sep: head,sep,tail = tail.partition('.') if is_module: prefix += '.' + head try: __import__(prefix, globals, locals) except ImportError: is_module = False try: obj = getattr(obj,head) except AttributeError: raise ImportError('No name %s' % name) return obj George From cwitts at gmail.com Thu Dec 13 09:50:20 2007 From: cwitts at gmail.com (Chris) Date: Thu, 13 Dec 2007 06:50:20 -0800 (PST) Subject: determining bytes read from a file. References: <1918acae-1417-4b88-84ee-3d751d619f77@a35g2000prf.googlegroups.com> <5scm02F17rr6tU1@mid.uni-berlin.de> Message-ID: <99513d86-0a03-4344-8a48-fbe566593273@e25g2000prg.googlegroups.com> A couple potential optimizations: > > # create the member variable name. > mem_var_name = options.inputfilename > mem_var_name = mem_var_name.replace(' ','_') > mem_var_name = mem_var_name.replace('.','_') > mem_var_name = options.inputfilename.replace(' ','_').replace('.','_') No need to assign it 3 times. > while i < len(hex_data): > outfile_c.write( "0x%c%c" % ( hex_data[i],hex_data[i+1] ) ) > i += 2 > if i != len(hex_data): > outfile_c.write(",") > if i % 32 == 0: > outfile_c.write("\n") This could be re-written as such: for x in xrange(0, len(hex_data), 32): output_c.write('%s\n' % ','.join(['0x%s'%''.join(['%c'%a for a in hex_data[x:x+32][i:i+2]]) for i in xrange(0, 32, 2)] From sjmachin at lexicon.net Wed Dec 12 15:34:05 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 12 Dec 2007 12:34:05 -0800 (PST) Subject: Is anyone happy with csv module? References: <15ab759b-0aec-45dd-88b9-c446c2b7d299@e10g2000prf.googlegroups.com> <88102e1b-c54a-4216-a71e-017a0a243aeb@b40g2000prf.googlegroups.com> <516581dc-a2d7-452a-8988-89c381e086e8@r29g2000hsg.googlegroups.com> Message-ID: On Dec 13, 12:58 am, Neil Cerutti wrote: > On 2007-12-12, John Machin wrote: > > >> It's clear that I am thinking to completely different usages > >> for CSV than what most people in this thread. I use csv to > >> export and import numerical data columns to and from > >> spreadsheets. > > > For that purpose, CSV files are the utter pox and then some. > > Consider using xlrd and xlwt (nee pyexcelerator) to read (resp. > > write) XLS files directly. > > I can vouch for that advice. I was exporting .xls files to csv > text files for over a year before I tried the xlrd solution--the > whole process is less cumbersome now, though it was bewildering > at first working with Excel in Python. Actually, surprises still > crop up now and then, mostly to do with cell types. Hi Neil, I'd be interested in hearing from you what caused the initial bewilderment with xlrd, and could it have been reduced by better documentation? What kinds of surprises? > The advantage > of working with csv was that everything was a string. It depends of your point of view. I'd regard that as a DISadvantage :-) With xlrd, if you have no expectation about the type of data in a cell, but need/want to know, xlrd will tell you. If you do have an expectation, you can check if actual == expected. Here's an example. Create a tiny csv file with dates in a format that's NOT appropriate to your locale (e.g. if you are in the USA, like the ddmmyyyy_dates.csv below). Open it with Excel by double- clicking on the name in Windows Explorer. Make the column twice its initial width. You'll notice some of the data (about 60% in a large dataset with approx. uniform distribution e.g. birth-dates) is LEFT- justified (text) and the remainder is RIGHT-justified (date). If you were given the xls file in that state, using xlrd the problem could be detected and worked around. Alternatively, go into user emulation mode: "fix" the problem with some formulas, forget immediately what you did, save the result as a new csv file, pass that on to the next user without a murmur, and delete the original csv file and the xls file. This is based on a true story, with one difference: the dates in the original csv file were formatted correctly for the DD/MM/YYYY-using locale; however Excel 97 would ignore the locale and assume MM/DD/YYYY if you opened the file from within Excel instead of double-clicking in Explorer (or vice versa; I forget which). 8<== ddmmyyyy_dates.csv 01/01/2007 31/01/2007 01/12/2007 31/12/2007 8<== mmddyyyy_dates.csv 01/01/2007 01/31/2007 12/01/2007 12/31/2007 8<== Cheers, John From showell30 at yahoo.com Sun Dec 9 10:49:25 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 9 Dec 2007 07:49:25 -0800 (PST) Subject: Serializing Python compiled code. In-Reply-To: Message-ID: <680307.20033.qm@web33506.mail.mud.yahoo.com> --- renjipanicker at gmail.com wrote: > In a C++ application having a Python interpreter > embedded, is it > possible to compile a small Python snippet into > object code and > serialize the compiled object code to, for example, > a database? I am > exploring the possibility of writing a data driven > application, where > small-sized object code can be read from a database > and executed. > Keeping aside all other considerations such as > security, etc for a > moment, is this feasible? > This might be too coarse for you, but you could serialize the .pyc files that get created from your modules. If you drop a .pyc file into a directory, and you make sure that you don't have a corresponding .py file of the same basename, and new date, in the directory, then Python will still execute it. This is a bit of a gotcha of Python for naive users, but this feature helps in use cases like yours, where you don't want to pay the lexing step, and for whatever reason, you don't want to simply use the file system as your store for code. ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs From sjmachin at lexicon.net Tue Dec 11 19:24:37 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 11 Dec 2007 16:24:37 -0800 (PST) Subject: Help needed with python unicode cgi-bin script References: <475cefe8$0$31165$9b622d9e@news.freenet.de> <8tj7j.5048$bW.4346@trnddc07> <24f3c1af-bf57-4b94-8d02-d7e956764f90@s8g2000prg.googlegroups.com> <0f09d97f-d742-4a3e-a459-91e730748d7e@b1g2000pra.googlegroups.com> <_vE7j.5156$bW.2309@trnddc07> <475f1dc4$0$19340$9b622d9e@news.freenet.de> Message-ID: On Dec 12, 11:06 am, "weheh" wrote: > p.s. I modified the code to break things out more explicitly: > > #!C:/Program Files/Python23/python.exe > import cgi, cgitb > import sys, codecs > import os,msvcrt > > cgitb.enable() > > print u"""Content-Type: text/html > > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" > > xml:lang="en,sp,fr"> > > While enjoying the dynamic feature of Python I find it difficult to refactor code without breaking it. For example, if I modify a function to take more arguments, or arguments of different types, I'll need to manually find out all places where the function is called and make sure I modify them all, unlike in C/Java, where the compiler will do the work of checking function signatures, etc. I suppose there isn't a strict mode in Python. It would be helpful though, when I don't need things to be so dynamic, and this is often the case, when it comes to function arguments and return values, for example. Even a module level or function level flag would be very helpful to find broken code. Or, are there any third party tools that do this? From showell30 at yahoo.com Sat Dec 8 19:19:50 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 8 Dec 2007 16:19:50 -0800 (PST) Subject: a Python person's experience with Ruby In-Reply-To: <475b2a25$0$7421$afc38c87@news.optusnet.com.au> Message-ID: <14753.87508.qm@web33514.mail.mud.yahoo.com> --- Richard Jones wrote: > > class A(object): > def set_a(self, value): > self._a = value > a = property(lambda self: self._a, set_a) > > Note that this differs from a regular attribute > because "a" is not deletable > from instances (the property defines no deleter). > The use case I was actually considering actually doesn't require much magic in either language. I commonly want to write code like this: e = Employee('jim', 'accounting', 50) print e.name print e.department print e.salary e.update_salary(percent=.10) e.update_salary(percent=.5) I want the name, department, and salary always exposed to me. But suppose in Employee's innards, it keeps a cache of the number of raises Jim has been given, and this cache is very implementation-sensitive. The way I achieve this is different in each language: 1) In Python I get name, department, and salary exposed for free, but I need to make a more conscious decision to hide e.compensation_tracker, which I do by renaming it to e.__compensation_tracker. 2) In Ruby I get compensation_tracker fully hidden/encapsulated for free, but I have to make a more conscious decision to expose name, department, and salary, which I get by saying: attr_reader :name, :department, :salary Obviously, things can get a lot more complicated than this scenario, and I think both languages are pretty flexible, but flexible in a different way. ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From k_vinoj at yahoo.com Mon Dec 10 00:56:25 2007 From: k_vinoj at yahoo.com (vinoj davis) Date: Mon, 10 Dec 2007 11:26:25 +0530 (IST) Subject: Converting HTML TO PDF using PYTHON Message-ID: <641899.27646.qm@web94603.mail.in2.yahoo.com> An HTML attachment was scrubbed... URL: From iddw at hotmail.com Thu Dec 13 20:05:54 2007 From: iddw at hotmail.com (Dave Hansen) Date: Thu, 13 Dec 2007 17:05:54 -0800 (PST) Subject: Finding overlapping times... References: Message-ID: <5b9ed697-a4e9-4a62-b1a2-1437fd0bafde@t1g2000pra.googlegroups.com> On Dec 13, 5:45 pm, Breal wrote: > I have a list that looks like the following > [(100000, 100010), (100005, 100007), (100009, 100015)] > > I would like to be able to determine which of these overlap each > other. So, in this case, tuple 1 overlaps with tuples 2 and 3. Tuple > 2 overlaps with 1. Tuple 3 overlaps with tuple 1. > > In my scenario I would have hundreds, if not thousands of these > ranges. Any nice pythonic way to do this? > What are you going to do with the result? Do you need to know if there are any overlaps? The number of overlaps? Given any particular range, what ranges overlap? There's really no way, other than to compare each range. Note that the relationship is symmetric, so you can save half you work. A simple-minded approach might be --- def overlaps(t1, t2): return (t2[1] >= t1[0]) and (t2[0] <= t1[1]) in_data = [(100000, 100010), (100005, 100007), (100009, 100015)] while (len(in_data) > 1): target = in_data.pop(0) for test in in_data: if overlaps(target,test): print "%s overlaps with %s" % (repr(target),repr(test)) --- If you want to save the information for later retrieval, you could build a dictionary with the ranges as keys: --- ovr_map = {} while len(in_data) > 1: target = in_data.pop(0) for test in in_data: if overlaps(target,test): if ovr_map.has_key(target): ovr_map[target].append(test) else: ovr_map[target] = [test] if ovr_map.has_key(test): ovr_map[test].append(target) else: ovr_map[test] = [target] for target in ovr_map.keys(): for test in ovr_map[target]: print "%s overlaps with %s" % (repr(target),repr(test)) --- I don't know that there isn't a more Pythonic way, I'm not much of an expert. HTH, -=Dave From deets at nospam.web.de Tue Dec 11 13:08:05 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 11 Dec 2007 19:08:05 +0100 Subject: Matching XML Tag Contents with Regex References: <38ea9cbc-a222-4c0f-ba2d-f6b415d02fb1@d27g2000prf.googlegroups.com> <4e09aece-f39f-4c5b-a966-ac6abfb3f7de@p69g2000hsa.googlegroups.com> <3cdbc226-bb3a-4945-949b-a0ec28b0e5c0@e6g2000prf.googlegroups.com> Message-ID: <5s8205F186vhuU1@mid.uni-berlin.de> Chris wrote: > On Dec 11, 11:41 am, garage wrote: >> > Is what I'm trying to do possible with Python's Regex library? Is >> > there an error in my Regex? >> >> Search for '*?' onhttp://docs.python.org/lib/re-syntax.html. >> >> To get around the greedy single match, you can add a question mark >> after the asterisk in the 'content' portion the the markup. This >> causes it to take the shortest match, instead of the longest. eg >> >> <%(tagName)s\s[^>]*>[.\n\r\w\s\d\D\S\W]*?[^(%(tagName)s)]* >> >> There's still some funkiness in the regex and logic, but this gives >> you the three matches > > Thanks, that's pretty close to what I was looking for. How would I > filter out tags that don't have certain text in the contents? I'm > running into the same issue again. For instance, if I use the regex: > > <%(tagName)s\s[^>]*>[.\n\r\w\s\d\D\S\W]*?(targettext)+[^(% > (tagName)s)]* > > each match will include "targettext". However, some matches will still > include , presumably from the tags which didn't contain > targettext. Stop using the wrong tool for the job. Use lxml or BeautifulSoup to parse & access HTML. Diez From gherron at islandtraining.com Tue Dec 4 18:51:18 2007 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 04 Dec 2007 15:51:18 -0800 Subject: Python Class Best Practice In-Reply-To: <20071204181804.70edef0a@atomizer.opensourcebeef.net> References: <20071204181804.70edef0a@atomizer.opensourcebeef.net> Message-ID: <4755E7F6.7030008@islandtraining.com> Rod Person wrote: > I've been doing python programming for about 2 years as a hobby and now > I'm finally able to use it at work in an enterprise environment. Since > I will be creating the base classes and libraries I wondering which why > is consider best when creating python classes: > > 1: > class Foo(object): > member1='' > member2=0 > > def __init__(self,member1='',member2=0): > self.member1 = member1 > self.member2 = member2 > > 2: > class Foo(object): > def __init__(self,member1='',member2=0): > self.member1 = member1 > self.member2 = member2 > > Both examples will store values for member1 and member2 in every instance. Any code that accesses self.member1 (or 2) will get the value stored in the instance. Example 1 which also creates two *class* members of the same name won't affect the conclusion of the previous paragraph. The two values in the class will be shadowed by each instances members of the same name. But now I need to ask, what did you expect to happen here? * If you thought those two extra assignments in example 1 effected the execution or storage in the __init__ (or any other method), you were mistaken. * If you really wanted class members (i.e., values shared by ALL instances), then they really shouldn't have the same name as instance members. You would surely confuse them at some point. * If you *really* wanted two class members *AND* two instance members with the same names, (WHY???) then example 1 will do so, but you'll have to access the instance members as self.member1 and the class members as Foo.member1. Gary Herron From gfixler at gmail.com Wed Dec 19 18:41:13 2007 From: gfixler at gmail.com (Gary) Date: Wed, 19 Dec 2007 15:41:13 -0800 (PST) Subject: Allowing Arbitrary Indentation in Python References: <5169ce7e-a092-47fc-b121-cd86e4916aa5@p69g2000hsa.googlegroups.com> <92ab48e1-c5f9-496a-a8ae-a0bf9ef957b1@d4g2000prg.googlegroups.com> <13mj9o53n2kpc34@corp.supernews.com> Message-ID: <5073c28e-77c7-4f8c-a2ff-b568c951c54a@t1g2000pra.googlegroups.com> On Dec 19, 3:19 pm, Grant Edwards wrote: > The problem is that to everybody else in the world, indentation > in Python represents control flow nesting, not GUI widget > nesting. Thanks, Grant. That's the first solid reasoning I've seen, and it's a very solid argument, as well. To that end, I'm thinking a few things. For one, your argument correctly puts forth that using the code in 2 separate ways is not good. Despite doing just that for 6 years with no problems, I can agree with you on that point. For another, I don't really think the proposals, or hints at how to do it in Python are all that great, either, because they create what I believe to be a bigger mess. I'm kind of leaning toward a Glade approach, wherein I wrap the UI elements up with an XML parser (I'm sure those exist for me already), and have some set of UI building functions build the UI for me with the crappy Maya calls underneath, based on data extracted from the XML. Then the UIs would be built as part of the parsing effort. This sort of hides the ugly stepchild of the Maya method of creating UIs under calls that each only do one thing, which rids the need to nest anything directly in Python, and separates out the UI data into XML - a language specifically made to be indented in a readable fashion, perfect for UI information. The extra benefit is that UI snippets can then be reused in the manner of templates, and even 'widgets,' from which all of my UIs can potentially benefit. I'm sure there's more to think about in regards to all of this, but it's not only the basis for a game plan, but it has precedent in places like Glade, to suggest that it's a viable, and decent option. Again, thanks. -g From bdesth.quelquechose at free.quelquepart.fr Sat Dec 8 12:21:38 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 08 Dec 2007 18:21:38 +0100 Subject: setattr getattr confusion In-Reply-To: References: <34fd1d8a-fa21-4c13-be10-822520093c4c@j44g2000hsj.googlegroups.com> Message-ID: <475ad2b2$0$29825$426a34cc@news.free.fr> Donn Ingle a ?crit : >>class Key(object): >>def __init__self): >>self.__dict__['props'] = KeyProps() > > Okay - that's weird. No, that's coherent. The default behavior (I mean, when there's no descriptor involved etc) of __setattr__ is to store attributes in instance.__dict__. So as long a you override __setattr__, you have to take care of this by yourself. > Is there another way to spin this? > >>def __setattr__(self,var,val): >>setattr(self.props,var,val) > > Perhaps by changing this one? If you know by advance which names should live in your object and/or which should belong to the KeyProps instance, then you can check and dispatch, ie: class Key(object): # names that must not be delegated to instance.props _mynames = ['props', 'foo', 'bar'] def __setattr__(self, name, value): if name in self._mynames: object.__setattr__(self, name, value) else: setattr(self.props, name, value) From mdelliot at gmail.com Thu Dec 27 16:29:09 2007 From: mdelliot at gmail.com (Micah Elliott) Date: Thu, 27 Dec 2007 13:29:09 -0800 (PST) Subject: Building Python statically on linux References: <0300530c-5550-4fff-bac6-66dbfa1b82b9@d21g2000prf.googlegroups.com> Message-ID: <9c2ead09-d84d-4972-b3a2-8bff510fcb94@b40g2000prf.googlegroups.com> On Dec 27, 8:32 am, Zentrader wrote: > I think you can just add -static to the gcc Flag line in the > makefile. Doing that (or CFLAGS=-static, or LDFLAGS=-static, or other Makefile tweaks) gets me linker errors. Sounds like there's not a simple prescribed means to do this (that anyone has documented). So now I'm open to hearing about other hacks people have done to get this to work. (Hopefully a config weenie heard my plea for --enable-all- static) -- Micah From pavlovevidence at gmail.com Thu Dec 27 14:59:01 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 27 Dec 2007 11:59:01 -0800 (PST) Subject: list in a tuple References: <13n3ad4fef122ef@corp.supernews.com> <141330e6-0f52-4145-b020-7f8e42efa2f4@w56g2000hsf.googlegroups.com> Message-ID: <845c1197-2ba1-4af5-9e8a-bf5fa0a6fc74@i72g2000hsd.googlegroups.com> On Dec 27, 12:38 pm, montyphy... at gmail.com wrote: > After some tought I must agree that this is a wart more than > a bug and that it will probably be best not to mess with it. > However, what do you guys think about the print wart in Py3k > described athttp://filoxus.blogspot.com/2007/12/python-3000-how-mutable-is-immuta... > (im not trying to advertise my blog, I just don't feel like > typing the whole problem all over again)? 1. Tuples are immutable. None of the tuples in your example were modified. The behavior you want (which is not immutability of tuples, which Python already has, but *recursive* immutability of all objects contained within the tuple) is not an unreasonable thing to ask for, but the design of Python and common usage of tuples makes it all but impossible at this point. There is no general way to determine whether an object is mutable or not. (Python would have to add this capability, an extremely substantial change, to grant your wish. It won't happen.) Tuples are used internally to represent the arguments of a function, which are often mutable. Tuples are sometimes used to return multiple values from a function, which could include mutable values. Tuples are used to specify multiple arguments to a format string, some of which could be mutable, though I guess this is going away in Python 3. 2. The issue with print in your example is a bug, not a wart. It'll be fixed. (This is just a guess, but I think it might have something to do with the flux of the new bytes type. The behavior manifested itself when trying to print a self-referencing structure probably only because that section of code was lagging behind.) 3. You're still top posting, which goes against this group's conventions and annoys quite a few people. When you reply to a message, please move your cursor to below the quoted message before you begin typing. Thank you Carl Banks From steve at REMOVE-THIS-cybersource.com.au Sat Dec 8 19:33:53 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Dec 2007 00:33:53 -0000 Subject: new style class References: <1194002609.296417.111050@v3g2000hsg.googlegroups.com> <472b09dd$1_7@news.bluewin.ch> <1194003093.338406.300870@y42g2000hsy.googlegroups.com> Message-ID: <13lmdvh6lk732b9@corp.supernews.com> On Sat, 08 Dec 2007 23:14:44 +0000, Bruce Coram wrote: >> http://www.catb.org/~esr/faqs/smart-questions.html >> > Eric Raymond's advice on how to ask questions the smart way would seem > to provide an excuse for people with ego control problems to indulge > themselves at the expense of others. While it is undoubtedly true that > there are people who post who should spend more time reading and > researching the problem, that is no excuse for replies that are rude, > hostile or exhibit similar displays of ill-tempered arrogance. Pointing somebody at Eric Raymond's advice is neither rude, hostile or arrogant. It may be brusque. It may fail to sugar-coat the message sufficiently, and hurt some recipient's feelings, but that's their problem, not that of the sender. > Eric > Raymond should perhaps re-read his advice and re-draft it to avoid > providing cover for those 'experts' who are either rude or ignorant - or > both. Why don't you do so yourself? He solicits suggestions and revisions. Or ask for permission to fork the document and come up with your own. (You have to ask first, because as far as I can see the document is not released with an open licence.) > If an 'expert' has time to indulge his/her ego is such an > intemperate manner then he/she probably doesn't have enough to do, or > enjoys being rude. Dare I suggest that perhaps YOU should read smart-questions? In particular, the bits where Raymond writes about RTFM: "You shouldn't be offended by this; by hacker standards, your respondent is showing you a rough kind of respect simply by not ignoring you. You should instead be thankful for this grandmotherly kindness." Pointing somebody at smart-questions is a rather more polite form of RTFM. > The best response to those who can not be bothered > to do the necessary work is either no reply Ignoring people's request for help to punish them for poor behaviour is not only rude but it is counter-productive. Not only do you not solve their immediate problem, but you keep them in a state of ignorance as to why they are being shunned -- thus guaranteeing that they will invariably transgress again. > or a simple "You would be > well advised to do some research before asking your question." Again leaving them no better off and still likely to transgress in the future. How much is "some"? What sort of research? Asking on Usenet is research isn't it? Why should I be expected to struggle with this on my own when there are people out there who already know the answer? These are all reasonable thoughts that a poster might have. Then there are the unreasonable thoughts, like the poster who once told me off for asking for a traceback so we could see what his error was. He actually took the time to write to me to abuse me for wasting *his* time, when I could "just as easily" copy the code from his post, fix the broken indentation and typos, save it to a file and run it myself. How do you expect people to learn better if we follow your advice? > We do not need to make life any more difficult than it already is. Following your advise will make life worse. > Civility costs nothing. Teaching people to ask appropriate questions is being civil. > Eric Raymond's article, which offer's good advice, is > rather misguided in not only providing an excuse for poor behaviour but > almost actively encouraging it. This is a pity since the essence of the > document is very good advice. Shame you haven't understood it, because your suggestions are diametrically opposed to his message. Raymond's message is about teaching people how to learn for themselves. Your message is to ignore their request for help and let them keep floundering in the dark. -- Steven. From zorg724 at yahoo.fr Mon Dec 3 17:53:20 2007 From: zorg724 at yahoo.fr (sccs cscs) Date: Mon, 3 Dec 2007 23:53:20 +0100 (CET) Subject: Delete a instance passed by reference into a method Message-ID: <855405.74475.qm@web90502.mail.mud.yahoo.com> Hello, I am very surprising by the Python interpreter behavior : see code I initialize a 'A' and a 'B', and i give a B instance reference to the instance A in 'm1' method. I can modify (IN/OUT mode) the 'i' attribute ( aB.i = 10 ) , BUT I CANNOT DELETE "aB" into the fonction m1 ! the code " del aB " or " aB= None" has no effect. 'aB' still exists when m1() is finsihed! WHY ? How can i do that? Thank you. Zorgi class A(object): def __init__(self): pass def m1 (self, aB ): aB.i = 10 del aB print "no more B" class B(object): def __init__(self,i): self.i = i def __del__(self): print "delete B" aA = A () aB = B ( i = 6) unA.m1 (aB ) print str( aB .i ) #---> Display 10, aB is not destroy ! --------------------------------- Ne gardez plus qu'une seule adresse mail ! Copiez vos mails vers Yahoo! Mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From james.b.looney at lmco.com Tue Dec 11 16:58:15 2007 From: james.b.looney at lmco.com (Looney, James B) Date: Tue, 11 Dec 2007 14:58:15 -0700 Subject: Building Python2.4.1 with idle on HPUX11 Message-ID: I've been trying to build Python 2.4.1 on an HPUX11. Python builds ok, but idle has issues. And what I don't know is how to determine whether or not Python discovers the tcl/tk libraries (.sl) and headers, or if there's some other problem. If someone has thoughts on either how to invoke 'configure' or how to debug this issue, please let me know. I'm executing them from an HPUX directory (different for each one) to isolate the different platform's objects/libraries since I also build and run from IRIX646 and SunOS5 (both of which work find). Here's my configure lines: Tcl8.4.9: /bin/env SHLIB_LD_FLAGS=-fPIC /usr/local/openSource/off.the.net/www.tcl.tk/tcl8.4.9/unix/configure --prefix=/usr/local/openSource/architectureIndependent --exec-prefix=/usr/local/openSource/HPUX11; make; make install Tk8.4.9: /bin/env SHLIB_LD_FLAGS=-fPIC /usr/local/openSource/off.the.net/www.tcl.tk/tk8.4.9/unix/configure --with-tcl=/usr/local/openSource/off.the.net/www.tcl.tk/tcl8.4.9/unix/pl atforms/HPUX11 --prefix=/usr/local/openSource/architectureIndependent --exec-prefix=/usr/local/openSource/HPUX11; make; make install Python 2.4.1: ./configure --prefix=/lds/tools/openSource/mainline/architectureIndependant --exec-prefix=/lds/tools/openSource/mainline/HPUX11 --enable-shared; make; make install Thanks, -James -------------- next part -------------- An HTML attachment was scrubbed... URL: From sergio.correia at gmail.com Mon Dec 10 14:05:39 2007 From: sergio.correia at gmail.com (Sergio Correia) Date: Mon, 10 Dec 2007 14:05:39 -0500 Subject: Job Offer: Python Ninja or Pirate! In-Reply-To: References: Message-ID: > import sys, xml, urllib > > dummy = [sys.stdout.write(city + ': ' + str(num) + '\n') for city, num in > set([[(a, o.count(a)) for a in p] for o, p in [2*tuple([[city for city in > ((xml.dom.minidom.parseString(urllib.urlopen(' > http://api.etsy.com/feeds/xml_user_details.php?id=' > + str(id)).read()).getElementsByTagName('city')[0].childNodes + [(lambda > t: (setattr(t, 'data', 'no city'), > t))(xml.dom.minidom.Text())[1]])[0].data.lower().replace(' ', ' ') for id > in [71234, 71234, 71234, 71234, 71234, 71234, 42792])]])]][0])] > Is that python or perl? -------------- next part -------------- An HTML attachment was scrubbed... URL: From limodou at gmail.com Wed Dec 12 05:06:46 2007 From: limodou at gmail.com (limodou) Date: Wed, 12 Dec 2007 18:06:46 +0800 Subject: ANN: UliPad 3.8.1 released! In-Reply-To: <475FB0AF.9030905@islandtraining.com> References: <475FB0AF.9030905@islandtraining.com> Message-ID: <505f13c0712120206u4427511ej8b6aab069e8173f2@mail.gmail.com> Please visit the site: http://code.google.com/p/ulipad I'm sorry forgot that. -- I like python! UliPad <>: http://code.google.com/p/ulipad/ meide <>: http://code.google.com/p/meide/ My Blog: http://www.donews.net/limodou From bdesth.quelquechose at free.quelquepart.fr Fri Dec 21 18:13:07 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 22 Dec 2007 00:13:07 +0100 Subject: detecting property modification In-Reply-To: <4876f94c-386b-44a2-8b1d-e9c5cf6f6d79@r60g2000hsc.googlegroups.com> References: <476c343d$0$5462$426a34cc@news.free.fr> <4876f94c-386b-44a2-8b1d-e9c5cf6f6d79@r60g2000hsc.googlegroups.com> Message-ID: <476c4887$0$15769$426a74cc@news.free.fr> Mangabasi a ?crit : > On Dec 21, 4:46 pm, Bruno Desthuilliers > wrote: > >>Mangabasi a ?crit : >>(snip) >> >> >> >> >>>When you say "The Body gets asked for the value of the attribute" that >>>means that Body's __dict__ is being asked to provide a value >>>corresponding to its 'pos' key, right? >> >>Wrong. That means that attribute lookup rules are invoked, which may *or >>not* end up calling the Body *intance*'s __dict__ __setitem__ method to >>be called. Anyway: >> >> >>> Now I may want to ask a more >>>specific question here. How do I modify Body's __dict__ so that I can >>>perform a task when __getitem__ method of the __dict__ is called? >> >>This still won't solve your problem. What you want to trace are method >>calls on the objects returned by attribute lookup on instances of Body - >>not calls to instances __dict__ methods. In your example, what you want >>to trace are calls to pos.__getitem__, not calls to b.__dict__.__getitem__. >> >>And if you what you really want is to trace any mutator call to any >>arbitrary object that may become an attribute of b, then I'm afraid >>you're in for a hard time... > > > Now I am curious about these "attribute lookup rules". > My understanding was: > > When an attribute name is accessed in an instance > > First __getattribute__(self, name) is called. Which is itself resolved first (methods being attributes) !-) __getattribute__ can itself be overloaded, so the only thing you can bet is that the first __getattribute__ method found in the mro will be called. All the rest is the *default* lookup rule: > This guy looks into the > instance's dictionary for the name, Yes. > if not found then looks into the > parent class's dictionary, You mean : the class's dictionnary. > if not found searches the base classes, if > not found checks __getattr__, and invoke it if found > still not found raises an > AttributeError. > Does this look right? Given the above corrections, mostly, yes. Note that the first one already makes a big difference. Also, it doesn't take into accounts __slots__ and descriptors. Let's ignore slots for the moment - we still have descriptors (property, functions, and other computed attributes), which have their __get__ method invoked when looked up. > If not, are these attribute lookup rules > documented somewhere? I have not been paying much attention to the > new style classes, have things changed with the introduction of these > new style classes? Well, yes, somewhat. Else we wouldn't have them, isn't it ? Anyway, wrt/ your problem, wether you use old-style or new-style classes won't make much difference: hooking into Body's instances attribute lookup won't let you trace attribute lookup on objects that are themselves attributes of a Body instance (hmmm, not very clear, sorry...re-reading it slowly, it should make sens. Hopefully...). From michele.simionato at gmail.com Sun Dec 30 00:17:01 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 29 Dec 2007 21:17:01 -0800 (PST) Subject: Fate of itertools.dropwhile() and itertools.takewhile() References: <7a86a421-089f-4634-8902-e9edfe139f03@e23g2000prf.googlegroups.com> Message-ID: <1a35dcbb-593c-45b8-a450-5245e75b1c9d@21g2000hsj.googlegroups.com> On Dec 30, 12:10 am, Raymond Hettinger wrote: > I'm considering deprecating these two functions and would like some > feedback from the community or from people who have a background in > functional programming. I am with Steven D'Aprano when he says that takewhile and dropwhile are clear enough. On the other hand, in my code base I have exactly zero occurrences of takewhile and dropwhile, even if I tend to use the itertools quite often. That should be telling. If my situations is common, that means that takewhile and dropwhile are useless in practice and should be deprecated. But I will wait for other respondents. It may just be that I never needed them. I presume you did scans of large code bases and you did not find occurrences of takewhile and dropwhile, right? Michele Simionato From carl at personnelware.com Thu Dec 27 01:16:22 2007 From: carl at personnelware.com (Carl K) Date: Thu, 27 Dec 2007 00:16:22 -0600 Subject: Counter-spam: Change the subject In-Reply-To: References: <1b648cf1-ee24-4132-9c15-b293d12907cf@i29g2000prf.googlegroups.com> <13ltsmo5rcl50ba@corp.supernews.com> <640971a3-61bf-44cc-8b95-754425008b29@j20g2000hsi.googlegroups.com> Message-ID: <4dGdnbOFyaWu3u7anZ2dnUVZ_o3inZ2d@comcast.com> Jan Claeys wrote: > Op Tue, 11 Dec 2007 14:19:20 -0800, schreef Paul McGuire: > >> My ISP's news server only works for me when I am connected locally, not >> when I am travelling. Same here, so I use: sudo ssh -L119:newsgroups.comcast.net:119 carl at my.box.at.home.com carl at asus17:~$ cat /etc/hosts 127.0.0.1 localhost 127.0.0.1 asus17.personnelware.com asus17 127.0.0.1 newsgroups.comcast.net Carl K From dotancohen at gmail.com Sun Dec 2 03:01:46 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 2 Dec 2007 10:01:46 +0200 Subject: "Python" is not a good name, should rename to "Athon" In-Reply-To: References: <78bdd499-a263-4c68-8e43-e3e59b111c7e@a39g2000pre.googlegroups.com> <5rcq90F13re18U1@mid.individual.net> Message-ID: <880dece00712020001w6d4848abyb01dc034edadd888@mail.gmail.com> On 01/12/2007, Russ P. wrote: > > So what dou you think about D language? :) Or F or F#? > > I think that one-letter names are even worse for languages than they > are for variables. And they are impossible to google. Update: well, they were when _I_ needed to... I just tried, and both "C" and "C++" gave relevant results. A few years ago, "C" would not return anything programming-related, and "C++" returned exactly the same results as "C". Google has improved (I say that weekly). Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From newsgroups at debain.org Sun Dec 9 15:43:01 2007 From: newsgroups at debain.org (Samuel) Date: Sun, 9 Dec 2007 20:43:01 +0000 (UTC) Subject: a strange SyntaxError References: <5f9860da-0763-47bd-a5d9-c5649f98254d@b1g2000pra.googlegroups.com> Message-ID: On Sun, 09 Dec 2007 12:35:46 -0800, CoolGenie wrote: > OK, sorry, this was about indents. Stupid VIM! $ mkdir -p $HOME/.vim/ftplugin/ $ echo "setlocal sw=4 setlocal ts=4 noremap py o/**************/ " >> ~/.vim/ftplugin/python.vim $ echo "syntax on set sw=2 set ts=2 set nu set nuw=3 set autoindent set expandtab" >> $HOME/.vimrc --------------- Problem solved, never to be found again. Bye, -Sam From sajmikins at gmail.com Fri Dec 21 16:11:40 2007 From: sajmikins at gmail.com (Simon Forman) Date: Fri, 21 Dec 2007 13:11:40 -0800 (PST) Subject: Odd behavior in Python/Tkinter? References: <3e6fc1b0-ac5e-42ed-8fe1-76da015c46ac@i29g2000prf.googlegroups.com> Message-ID: <5c69cf62-d770-439a-a7ee-ea92626a03ad@18g2000hsf.googlegroups.com> On Dec 21, 12:30 pm, Lie wrote: > Inspect the following code: > > --- start of code --- > import Tkinter as Tk > from Tkconstants import * > > root = Tk.Tk() > > e1 = Tk.Entry(root, text = 'Hello World') > e2 = Tk.Entry(root, text = 'Hello World') > > e1.grid(row = 1, column = 1) > e2.grid(row = 2, column = 1) > > e1.insert(END, 'Hello Python') > > root.mainloop() > > --- end of code --- > > What do you expect the result should be? > a. Two textboxes: One contains 'Hello Python', the other 'Hello World' > b. Two textboxes: Both containing 'Hello World' > c. Two textboxes: Both containing 'Hello Python' > d. Two textboxes: Both empty > e. Don't know > > Check your guess with your Python 2.5.1 (AFAIK, the latest version at > the moment of writing) Huh. I got C (using python 2.4.3 on Ubuntu Linux..) That ain't right. From bj_666 at gmx.net Fri Dec 14 11:59:08 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 14 Dec 2007 16:59:08 GMT Subject: Compressing a text file using count of continous characters References: Message-ID: <5sfr2sF196svmU1@mid.uni-berlin.de> On Fri, 14 Dec 2007 08:54:58 -0800, nirvana wrote: > I need to count the number of continous character occurances(more than > 1) in a file, and replace it with a compressed version, like below > XYZAAAAAAAADEFAAcdAA --> XYZ8ADEF2Acd2A Great. Then go ahead an implement it. :-) `itertools.groupby()` might be handy. And you have to think about digits in the source if that's allowed. Ciao, Marc 'BlackJack' Rintsch From florencio.cano at gmail.com Mon Dec 24 07:42:54 2007 From: florencio.cano at gmail.com (Florencio Cano) Date: Mon, 24 Dec 2007 13:42:54 +0100 Subject: Damn error! In-Reply-To: References: Message-ID: One linha in tabela doesn't have the syntax "something:something" so split() returns a 0 or 1 sized list and tmp[0] or tmp[1] points outside the list. 2007/12/24, Vaurdan : > Hello, > I've this code: > def print_tabela(tabela): > print "Tabela 1 | Tabela 2" > for linha in tabela: > tmp = linha.split(":") > print tmp[0] + " | " + tmp[1], > > But give me this error: > Tabela 1 | Tabela 2 > Traceback (most recent call last): > File "./teste.py", line 126, in > print_tabela(conteudo) > File "./teste.py", line 58, in print_tabela > print tmp[0] + " | " + tmp[1], > IndexError: list index out of range -- Florencio Cano Gabarda From hniksic at xemacs.org Tue Dec 11 02:44:38 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 11 Dec 2007 08:44:38 +0100 Subject: Is a "real" C-Python possible? References: <7tOdnRb-5fMW_MHanZ2dnUVZ_tmhnZ2d@comcast.com> <9c4dd9b6-acc1-478d-bba2-a1ba223c660f@f3g2000hsg.googlegroups.com> <475dc3ba$0$17415$426a74cc@news.free.fr> <112b5a80-42d4-4298-82a3-e9e25aa23b75@y5g2000hsf.googlegroups.com> Message-ID: <87d4tdu13t.fsf@mulj.homelinux.net> sturlamolden writes: > On 10 Des, 23:54, Bruno Desthuilliers > wrote: > >> Or a lack of time and money. Lisp is one of the older programming >> languages around, and at a time had BigBucks(tm) invested on it to try >> and make it practically usable. > > Yes. But strangely enough, the two Lisp implementations that really > kick ass are both free and not particularly old. Not two, but one -- SBL is simply a fork of CMU CL. As for their age, the CMU CL states that it has been "continually developed since the early 1980s". From MrJean1 at gmail.com Wed Dec 26 15:28:24 2007 From: MrJean1 at gmail.com (MrJean1) Date: Wed, 26 Dec 2007 12:28:24 -0800 (PST) Subject: CPython and a C extension using Boehm GC References: <3aa7bd0a-acd2-4d1e-b647-d300fc2ae20d@s8g2000prg.googlegroups.com> Message-ID: <88409ef1-c417-4c52-8671-4b7dc6e9989c@e10g2000prf.googlegroups.com> FWIIW, I built GC 6.7 on a RHEL 3 (Opteron) system using ./configure --prefix=... --enable-redirect-malloc --enable- threads=posix --enable-thread-local-alloc make; make check; make install Then, I tried running a few examples with 3 different, existing Python binaries each pre-loaded with the libgc.so library env LD_PRELOAD=.../libgc.so .... One is Python 2.2.3 included in RHEL 3, one is a Python 2.5.1 build and is a Python 3.0a2 build, all 64-bit. All seemed to work OK. These are 3 existing Python binaries without any call to GC_INIT(). AFAICT, on Linux, GC_INIT is a no-op anyway. /Jean Brouwers On Dec 26, 7:14?am, MrJean1 wrote: > It depends on how the GC inside the extension is built. ?If it is a > drop-in replacement for malloc, then GC *must* be loaded and > initialized upfront if possible. ?There is no need to memcpy anything > between Python and the extension. > > However, if GC does not replace malloc, etc., then GC-ed memory is > only used within the extension. ?GC_INIT can be called when the > extension is loaded and memcpy-ing between Python and the extension is > mandatory. > > There are other details to consider. ?For example, on some platforms, > GC *must* be initialized from the main executable. ?That may preclude > both scenarios, altogether. > > /Jean Brouwers > > On Dec 25, 7:35?pm, Andrew MacIntyre > wrote: > > > malkarouri wrote: > > > Is it possible to write a Python extension that uses the Boehm garbage > > > collector? > > > I have a C library written that makes use ofboehm-gcfor memory > > > management. To use that, I have to call GC_INIT() at the start of the > > > program that uses the library. Now I want to encapsulate the library > > > as a CPython extension. The question is really is that possible? And > > > will there be conflicts between theboehm-gcand Python memory > > > management? And when should I call GC_INIT? > > > It probably should be possible with some caveats: > > - memory allocated by Python is never passed into the library such that > > ? ?it also ends up being subject toboehm-gc; > > - memory allocated by the library is never used by Python objects. > > > So memcpy()ing between library allocated and Python allocated memory > > would seem to be a way to achieve this. > > > I would call GC_INIT in the extension's import routine > > (init()) for a C extension, and immediately after loading > > the library if using ctypes. > > > -- > > ------------------------------------------------------------------------- > > Andrew I MacIntyre ? ? ? ? ? ? ? ? ? ? "These thoughts are mine alone..." > > E-mail: andy... at bullseye.apana.org.au ?(pref) | Snail: PO Box 370 > > ? ? ? ? andy... at pcug.org.au ? ? ? ? ? ? (alt) | ? ? ? ?Belconnen ACT 2616 > > Web: ? ?http://www.andymac.org/?? ? ? ? ? ? | ? ? ? ?Australia From asgarde at msn.com Tue Dec 25 11:42:58 2007 From: asgarde at msn.com (asgarde at msn.com) Date: Tue, 25 Dec 2007 08:42:58 -0800 (PST) Subject: Pexpect and a Linux Terminal References: Message-ID: <698f7cc7-ffae-4a59-a9ac-a02f0d8d1247@w56g2000hsf.googlegroups.com> On 25 d?c, 10:14, "asga... at msn.com" wrote: > On 25 d?c, 09:41, "asga... at msn.com" wrote: > > > Yes it's work ! :-D > > > I use prompt = '.*#' to detect the prompt expect. Thank you for you'r > > help ! > > > Vive Python et TK :-D > > I have another probleme, not directly from Pexpect() function. There > is my code : > > from Tkinter import * > from sys import * > import tkMessageBox > from tkColorChooser import askcolor > from tkFileDialog import askopenfilename > import tkFileDialog as Selector > from os.path import exists, join > from os import pathsep > import pexpect > import os, sys > def test(): > cmd1="su -" > pwd="mypass" > prompt ='.*#' > iso=Selector.askopenfilename(initialdir="/home/user",filetypes = > [("iso", "*.iso")]) > lbl2=Label(fen1) > cmd2="mount -o loop "+iso+" /mnt/disk" > child = pexpect.spawn(cmd1) > child.expect('Mot de passe :') > child.sendline(pwd) > child.expect(prompt) > child.send(cmd2) > lbl2.configure(text=cmd2) > lbl2.pack() > fen1=Tk() > entr1=Entry(fen1) > lbl1=Label(fen1) > entr1.pack() > lbl1.pack() > bou1= Button(fen1,text='Parcourir',command=test) > bou1.pack() > fen1.mainloop() > > All that's ok when if cmd2 command like : mkdir /root/toto but when i > want to replace it for : mount loop -o /home/user/myiso.iso /mnt/disk > nothing happened :-( I tryed the command during many times and i don't > know why it doesn't work :s > > if you can help me another time i will be apprecied :-P > > Thank you :) When want to test the mkdir command, it work but ONLY if my TTY as root is closed, very weired no ? the mount command still not work :s From lists at cheimes.de Fri Dec 7 06:07:07 2007 From: lists at cheimes.de (Christian Heimes) Date: Fri, 07 Dec 2007 12:07:07 +0100 Subject: Can I embed Windows Python in C# or VC++? In-Reply-To: <8e07e800-eab0-46c3-b3ed-d518f1d54e11@e25g2000prg.googlegroups.com> References: <7520d659-deae-403c-a788-14a70977a09d@e6g2000prf.googlegroups.com> <54927654-314c-46a4-be30-13d1fc4d343d@s12g2000prg.googlegroups.com> <8e07e800-eab0-46c3-b3ed-d518f1d54e11@e25g2000prg.googlegroups.com> Message-ID: <4759295B.8030209@cheimes.de> sturlamolden wrote: > The answer is YES. C# can access C functions exported by any DLL with > platform invoke. Since the Python C API is plain C and not C++ you can > gain access to it from C#. Import System.Runtime.InteropServices and > write wrappers like > > [DllImport("Python25.dll"), CallingConvention=CallingConvention.Cdecl] > public static void Py_Initialize(); There is no need for that. PythonDotNET wraps the P/Invokes and internal C API of CPython in a nice .NET API. Christian From gagsl-py2 at yahoo.com.ar Thu Dec 20 01:10:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 20 Dec 2007 03:10:48 -0300 Subject: Allowing Arbitrary Indentation in Python References: <5169ce7e-a092-47fc-b121-cd86e4916aa5@p69g2000hsa.googlegroups.com> <92ab48e1-c5f9-496a-a8ae-a0bf9ef957b1@d4g2000prg.googlegroups.com> <31267f9b-753c-4c7a-9b05-6a6ea458db44@e23g2000prf.googlegroups.com> Message-ID: En Thu, 20 Dec 2007 00:46:50 -0300, Gary escribi?: > 1) Is it best/more standard to read in, and parse the XML into some > kind of Python hierarchy first, and then build the UI out of the data > in that structure, or call out UI commands as say, callbacks from the > parser live - as it wades through the data? I lean toward the former, > as it means having one standard set of functions to read in, and parse > the XML data, which can then be used for anything, like displaying the > UI to the client, or creating an editable version of the UI in the UI > build tool. The modified version can then be saved back out as well. ElementTree is a good candidate for processing xml: http://effbot.org/zone/element.htm It provides a "natural" way to access elements and attributes, instead of writing the same handler again and again or using slow DOM functions of gigantic names. > 2) Is XML fairly standard for this in Python? I recently learned about/ > was frightened by pickling. Is that worth learning? Does anyone bother > with it? Pickle is good for storing data that will be loaded again by (the same, or another) Python program. The format isn't portable to other languages, it isn't readable, may have security issues. But it's extensible and much more flexible than the other builtin alternative, marshal. You can use pickle as a serializer if you're aware of its limitations. -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Thu Dec 27 07:24:29 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 27 Dec 2007 12:24:29 -0000 Subject: getting n items at a time from a generator References: Message-ID: <13n76btksnmf1ed@corp.supernews.com> On Thu, 27 Dec 2007 03:34:57 -0800, Kugutsumen wrote: > I am relatively new the python language and I am afraid to be missing > some clever construct or built-in way equivalent to my 'chunk' generator > below. > > def chunk(size, items): > """generate N items from a generator.""" [snip code] Try this instead: import itertools def chunk(iterator, size): # I prefer the argument order to be the reverse of yours. while True: chunk = list(itertools.islice(iterator, size)) if chunk: yield chunk else: break And in use: >>> it = chunk(iter(xrange(30)), 7) >>> for L in it: ... print L ... [0, 1, 2, 3, 4, 5, 6] [7, 8, 9, 10, 11, 12, 13] [14, 15, 16, 17, 18, 19, 20] [21, 22, 23, 24, 25, 26, 27] [28, 29] -- Steven From gagsl-py2 at yahoo.com.ar Mon Dec 31 02:35:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Dec 2007 05:35:44 -0200 Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <4a5d4311-c5ec-4f3c-8800-c30ac30e399d@t1g2000pra.googlegroups.com> <601e4a81-a69a-4576-a276-41d82a256482@e50g2000hsh.googlegroups.com> <13nganfbu52dnff@corp.supernews.com> <13nh4uvkq9cmo81@corp.supernews.com> Message-ID: En Mon, 31 Dec 2007 05:01:51 -0200, Steven D'Aprano escribi?: > On Sun, 30 Dec 2007 20:00:14 -0800, bukzor wrote: > >> I also see this as the main use of the >> 'notlocal' keyword to be introduced in py3k (it also fixes the example >> given by Istvan above). > > There doesn't appear to be any reference to a "notlocal" keyword in > Python 3 that I can find. Have I missed something? It sounds like an > April Fool's gag to me. Do you have a reference to a PEP or other > official announcement? No, it's a real keyword in python 3, but it's spelled "nonlocal". See http://www.python.org/dev/peps/pep-3104/ -- Gabriel Genellina From sdementen at gmail.com Sat Dec 29 07:51:12 2007 From: sdementen at gmail.com (seb) Date: Sat, 29 Dec 2007 04:51:12 -0800 (PST) Subject: Brussels Python Interest/Users Group Message-ID: Hi Pythonistas, Is anyone interested in forming a Brussels(Belgium) area Python User Group ? I am not aware of any python focused group in this area. Language could be whatever fits the bill (English/French/Dutch/...) Focus would be python, ironpython/silverlight, scipy, ORMs, web frameworks, and whatever is of interest to us. Interested ? Please post on this thread. Seb From sturlamolden at yahoo.no Mon Dec 10 19:59:19 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 10 Dec 2007 16:59:19 -0800 (PST) Subject: Any way to program custom syntax to python prompt? >> I want to edit matrices. References: <639ad9a8-83ac-41b3-abf2-0759e70eb839@r60g2000hsc.googlegroups.com> Message-ID: <0da0f06e-ccf7-4cd5-8cbc-a06901e0de4e@n20g2000hsh.googlegroups.com> On 11 Des, 01:54, mosi wrote: > Python matrices are usually defined with numpy scipy array or similar. > e.g.>>> matrix1 = [[1, 2], [3, 4], [5, 6]] That is a list of Python lists, not a NumPy array or matrix. > For example:>>> matrix + 2 > > [ 3, 4; > 5, 6; > 7, 8;] > > Possibly with operator overloading? Go and get NumPy: www.scipy.org Then buy Travis Oliphant's book. From jzgoda at o2.usun.pl Fri Dec 14 15:53:41 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 14 Dec 2007 21:53:41 +0100 Subject: High speed web services In-Reply-To: <0e0b02d9-0229-4ea1-8009-57dafec65941@t1g2000pra.googlegroups.com> References: <0e0b02d9-0229-4ea1-8009-57dafec65941@t1g2000pra.googlegroups.com> Message-ID: herbasher pisze: > How do I built highly available and lighting fast Python webservice? Write optimized code and use it in conjunction with twisted.web. -- Jarek Zgoda http://zgodowie.org/ From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Dec 13 05:31:34 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 13 Dec 2007 11:31:34 +0100 Subject: Is Python really a scripting language? In-Reply-To: References: <009101c83c55$4ee07a00$6501a8c0@aristotle> <4761011a$0$5462$426a74cc@news.free.fr> Message-ID: <476109f3$0$13493$426a74cc@news.free.fr> Marco Mariani a ?crit : > Bruno Desthuilliers wrote: > >> As far as I'm concerned, anyone (I mean, anyone pretending to be a >> programmer) being ignorant enough to ask such a question ranks high in >> my bozo list. Don't waste time with bozos. > > > Alan Kay said it well enough without using words like "pretending", > "ignorant" and "bozo" :) Probably. But I do like using these words, and having the opportunity to use them three in a same post really made me happy !-) > http://acmqueue.com/modules.php?name=Content&pa=showpage&pid=273 > > It's worth a read. Whenever I'll get a couple minutes. From ecir.hana at gmail.com Sat Dec 15 19:44:34 2007 From: ecir.hana at gmail.com (ecir.hana at gmail.com) Date: Sat, 15 Dec 2007 16:44:34 -0800 (PST) Subject: Inter-process communication, how? Message-ID: Hi, let's say I have two scripts: one does some computations and the other one is a graphical front end for launching the first one. And both run in separate processes (front end runs and that it spawns a subprocess with the computation). Now, if the computation has a result I would like to display it in the front end. In another words, I would like to pass some data from one process to another. How to do that? I'm affraid I can't use a pipe since the computation could print out some logging (if I understant pipes correctly). Thanks! From g.bassi at iperbole.bologna.it Sun Dec 2 09:51:56 2007 From: g.bassi at iperbole.bologna.it (Giancarlo Bassi) Date: Sun, 2 Dec 2007 15:51:56 +0100 Subject: question involving installation of python applications Message-ID: Why python interpreter has two copies ?: so that: ls -l python* -rwxr-xr-x 1 root root 2288515 Nov 10 13:41 python lrwxrwxrwx 1 root root 16 Jul 3 02:06 python-config -> python2.5-config -rwxr-xr-x 1 root root 2288515 Nov 22 00:25 python2.3 -rwxr-xr-x 1 root root 1424 Jul 3 02:06 python2.5-config --------------------------------------------------------------- If someone wants to keep more python interpreters how can avoid to superpose them. Only by renaming ? Is there reference into documentation ? I want to keep python 2.3.5 and Zope-2.8-final for FLE3 (future learning environment) and install also pychess, requiring pygtk 2.x , (possibly for python 2.5.1) While I managed to install FLE3 , after installing python2.5.1 I didn't success to run again the daemon for running Zope-2.8. I got somewhat like that: aka-ankku at aka-ankku:/home/aka-ankku/Zope-2.8.0-final$ bin/zopectl Traceback (most recent call last): File "/mnt/hd/home/aka-ankku/Zope-2.8.0-final/lib/python/Zope2/Startup/zopectl.py ", line 43, in ? import Zope2.Startup File "/mnt/hd/home/aka-ankku/Zope-2.8.0-final/lib/python/Zope2/__init__.py", line 60, in ? from Zope2.Startup.run import configure File "/mnt/hd/home/aka-ankku/Zope-2.8.0-final/lib/python/Zope2/Startup/__init__.p y", line 24, in ? import ZConfig File "/mnt/hd/home/aka-ankku/Zope-2.8.0-final/lib/python/ZConfig/__init__.py", line 21, in ? from ZConfig.loader import loadConfig, loadConfigFile File "/mnt/hd/home/aka-ankku/Zope-2.8.0-final/lib/python/ZConfig/loader.py", line 26, in ? import ZConfig.schema File "/mnt/hd/home/aka-ankku/Zope-2.8.0-final/lib/python/ZConfig/schema.py", line 44, in ? class BaseParser(xml.sax.ContentHandler): AttributeError: 'module' object has no attribute 'ContentHandler' -------------------------------------------------------------------------- Why 'module' object has no attribute 'ContentHandler' ? THX, GB --- "I'm no Pawn, I'm Donald Duck ! " -- Donald in MathMagic Land From kevin.p.dwyer at gmail.com Fri Dec 7 17:07:06 2007 From: kevin.p.dwyer at gmail.com (kdwyer) Date: Fri, 7 Dec 2007 14:07:06 -0800 (PST) Subject: "finding hostid with python" References: <73cc5d9f-a3d3-4c3a-9893-24f35dffd831@d21g2000prf.googlegroups.com> Message-ID: <96011a4a-72dd-4c26-afa4-8524832a608c@e10g2000prf.googlegroups.com> On Dec 7, 9:10 pm, farsheed wrote: > I,m searching for a way to obtain hostid in windows. > Any ideas? IIRC, MArk Hammond's extensions for windows have a method for obtaining the fully qualified hostname of a machine. Kev From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Dec 4 07:11:04 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 04 Dec 2007 13:11:04 +0100 Subject: Why use Slot? from Peter Norvig's AI code In-Reply-To: <70161450-5ea7-4527-9228-70b397dce0af@d27g2000prf.googlegroups.com> References: <70161450-5ea7-4527-9228-70b397dce0af@d27g2000prf.googlegroups.com> Message-ID: <475543d7$0$9188$426a74cc@news.free.fr> Davy a ?crit : > Hi all, > > When reading Python source code of Peter Norvig's AI book, I found it > hard for me to understand the idea of slot (function nested in > function). First point : this code seems to be based on an older (way older) Python version, so some things would not be done that way no more. Also, in newer (well... not that new, but...) Python versions, the term 'slot' has a quite different meaning (for short: a memory optimization for attributes...). FWIW, what the author names 'slots' here are really instance attributes - not the use of inner functions (please refer to the class's docstring and __init__ method code). > Please see "program()" nested in "make_agent_program()", > why not use program() directly? It's a local variable of make_agent_program, so unless you bind it to another name (which is done in the __init__), you can't access it from outside make_agent_program. The intent - which is explained in the docstring - is to make sure the 'program' function won't access the Agent instance - so it was obviously written for a Python version that predates lexical closures support (you can do some archeological research to find out when this support was added if you want !-). Now this implementation, whatever it was worth by the time this code was written (some 5 or more years ago AFAICT) would be considered a WTF with newer Python versions - where the obvious solution would be to define "program" as a staticmethod. HTH From istvan.albert at gmail.com Sat Dec 29 13:49:58 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Sat, 29 Dec 2007 10:49:58 -0800 (PST) Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> Message-ID: On Dec 29, 1:11 pm, "Martin v. L?wis" wrote: > Google for "Python mutable default arguments" and a mere 30 minutes later this thread is already one of the results that come up From montyphyton at gmail.com Mon Dec 24 10:22:02 2007 From: montyphyton at gmail.com (montyphyton at gmail.com) Date: Mon, 24 Dec 2007 07:22:02 -0800 (PST) Subject: list in a tuple Message-ID: Recently, I got into a debate on programming.reddit.com about what should happen in the following case: >>> a = ([1], 2) >>> a[0] += [3] Currently, Python raises an error *and* changes the first element of the tuple. Now, this seems like something one would want to change - why raise an error *and* execute the thing it was complaining about? The discussion seems to have no end, and that is why I'm posting here. I would like to know what is the opinion of the people on this group... Am I really mistaking for thinking that this is strange and unwanted behavior? Btw I understand *why* is this happening, I just think it should change... And here is the post that started this discussion: http://filoxus.blogspot.com/2007/12/python-3000-how-mutable-is-immutable.html#links Thanks for your replies From BjornSteinarFjeldPettersen at gmail.com Thu Dec 6 19:07:26 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Thu, 6 Dec 2007 16:07:26 -0800 (PST) Subject: Calculate an age References: <3cc59ef1-ecd4-4b7c-ac8b-9bb7f3f83aa3@n20g2000hsh.googlegroups.com> Message-ID: <8f10495a-a6de-4e4a-b2dd-fc71413c6ec3@d4g2000prg.googlegroups.com> On Dec 6, 11:19 pm, John Machin wrote: > On Dec 7, 8:34 am, Pierre Quentel wrote: > > > Hi all, > > > I have searched in the standard distribution if there was a function > > to return the difference between 2 dates expressed like an age : > > number of years, of months and days. The difference between datetime > > instances returns a timedelta object that gives a number of days, but > > not an age > > > So is there such a function somewhere ? If not, for what reason, since > > it's a rather usual task > > and a rather usually imprecisely specified task [what do you mean by > "number of months"?] with multiple interpretations/implementations/ > doctrines the publication of any one of which attracts a truckload of > rotten tomatoes and derision from adherents of other sects :-) It may be imprecisely specified, yet it's quite useful anyway. I've got an implementation at http://blog.tkbe.org/archive/python-how-old-are-you/ if anyone's interested.. -- bjorn From andre.roberge at gmail.com Wed Dec 26 22:36:29 2007 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Wed, 26 Dec 2007 19:36:29 -0800 (PST) Subject: Subject changed: Bug in combining htmlentitydefs.py and ElementTree? References: <803d10b9-01f0-4a1f-bc6a-6e12f17c308b@v32g2000hsa.googlegroups.com> <4772e404$0$15853$9b622d9e@news.freenet.de> <35818f3d-1998-4cea-8236-44fcebce71e9@x29g2000prg.googlegroups.com> <4772f76d$0$32111$9b622d9e@news.freenet.de> Message-ID: Sorry for the top posting - I found out that the problem I encountered was not something new in Python 3.0. Here's a test program: ============ import xml.etree.ElementTree ElementTree = xml.etree.ElementTree import htmlentitydefs class XmlParser(ElementTree.ElementTree): def __init__(self, file=None): ElementTree.ElementTree.__init__(self) parser = ElementTree.XMLTreeBuilder( target=ElementTree.TreeBuilder(ElementTree.Element)) parser.entity = htmlentitydefs.entitydefs self.parse(source=file, parser=parser) return f = open('test.html') tree = XmlParser(f) tree.write('test_out.html', encoding='utf-8') ====== This program should be run with the following test file (test.html): ===== test

Α

====== If run as such, it will print out the following: ------ test

&#913;

------- Notice how it is &#913; that appears instead of Α This is the behaviour with both Python3.0 and 2.5. (When I was running with Python 2.5, I was always preprocessing the files with BeautifulSoup, which removed many problems). If I use "my_htmlentitiesdef.py" described in a previous message, I do get an Alpha printed out (admittedly, not the character entity). I would prefer to find a way to process such files and get Α instead... (or even, to process files with hard-coded characters e.g. ? instead of é and have them processed properly...). unicode-challengedly-yrs, Andr? On Dec 26, 9:14 pm, "Andr?" wrote: > On Dec 26, 8:53 pm, "Martin v. L?wis" wrote: > > > > Without an additional parser, I was getting the following error > > > message: > > [...] > > > xml.parsers.expat.ExpatError: undefined entity ?: line 401, column 11 > > > To understand that problem better, it would have been helpful to see > > what line 401, column 11 of the input file actually says. AFAICT, > > it must have been something like "&?;" which would be really puzzling > > to have in an XML file (usually, people restrict themselves to ASCII > > for entity names). > > No, that one was é (testing with my own name that appeared in > a file). > > > > > > for entity in ent: > > > if entity not in parser.entity: > > > parser.entity[entity] = ent[entity] > > > This looks fine to me. > > > > The output was "wrong". For example, one of the test I used was to > > > process a copy of the main dict of htmlentitydefs.py inside an html page. A > > > few of the characters came ok, but I got things like: > > > > 'Α': 0x0391, # greek capital letter alpha, U+0391 > > > Why do you think this is wrong? > > Sorry, that was just cut-and-pasted from the browser (not the source); > in the source of the processed html page, it is > '&#913;': 0x0391, # greek capital letter alpha, U+0391 > > i.e. the "&" was transformed into "&" in a number of places (all > places above ascii 127 I believe). > > Here are a few more lines extracted from the html file that was > processed: > ============= > '?': 0x00c2, # latin capital letter A with circumflex, U+00C2 > ISOlat1 > '?': 0x00c0, # latin capital letter A with grave = latin capital > letter A grave, U+00C0 ISOlat1 > '&#913;': 0x0391, # greek capital letter alpha, U+0391 > '?': 0x00c5, # latin capital letter A with ring above = latin > capital letter A ring, U+00C5 ISOlat1 > '?': 0x00c3, # latin capital letter A with tilde, U+00C3 ISOlat1 > '?': 0x00c4, # latin capital letter A with diaeresis, U+00C4 > ISOlat1 > '&#914;': 0x0392, # greek capital letter beta, U+0392 > '?': 0x00c7, # latin capital letter C with cedilla, U+00C7 > ISOlat1 > '&#935;': 0x03a7, # greek capital letter chi, U+03A7 > '&#8225;': 0x2021, # double dagger, U+2021 ISOpub > '&#916;': 0x0394, # greek capital letter delta, U+0394 > ISOgrk3 > ============ > > > > > > When using my modified version, I got the following (which may not be > > > transmitted properly by email...) > > > '?': 0x0391, # greek capital letter alpha, U+0391 > > > > It does look like a Greek capital letter alpha here. > > > Sure, however, your first version ALSO has the Greek capital letter > > alpha there; it is just spelled as Α (which *is* a valid spelling > > for that latter in XML). > > Agreed that it would be... However that was not how it was > transformed, see above; sorry if I was not clear about what was > happening (I should not have cut-and-pasted from the browser window). > > > > > > I hope the above is of some help. > > > Thanks; I now think that htmlentitydefs is just as fine as it always > > was - I don't see any problem here. > > You may well be right in that the problem may lie elsewhere. But as > making the change I mentioned "fixed" the problem at my, I figured > this was where the problem was located - and thought I should at least > report it here. > > Regards, > Andr? > > > Regards, > > Martin From lists at cheimes.de Sun Dec 9 17:34:09 2007 From: lists at cheimes.de (Christian Heimes) Date: Sun, 09 Dec 2007 23:34:09 +0100 Subject: Is a "real" C-Python possible? In-Reply-To: <7tOdnRb-5fMW_MHanZ2dnUVZ_tmhnZ2d@comcast.com> References: <7tOdnRb-5fMW_MHanZ2dnUVZ_tmhnZ2d@comcast.com> Message-ID: <475C6D61.9020105@cheimes.de> Jack wrote: > I guess this is subjective :) - that's what I felt in my experience > with web applications developed in Python and PHP. I wasn't able to > find a direct comparison online. Please compare the number of serious bugs and vulnerabilities in PHP and Python. > I understand. Python modules implemented in Python - this is how > Python gets its really rich library. Correct Python code is much easier to write and multiple times easier to get right than C code. Everybody with a few months of Python experience can contribute to the core but it requires multiple years of C and Python experience to contribute to the C implementation. > I think most Java-Python benchmarks you can find online will indicate > that Java is a 3-10 times faster. A few here: > http://mail.python.org/pipermail/python-list/2002-January/125789.html > http://blog.snaplogic.org/?p=55 There are lies, damn lies and benchmarks. :) Pure Python code is not going to beat Java code until the Python core gets a JIT compiler. If you want fair results you have to either disable the JIT in Java or use Psyco for Python. Otherwise you are comparing the quality of one language implementation to the quality of a JIT compiler. > Here's an article that shows the new version of Ruby is > faster than Python in some aspects (they are catching up :) > http://antoniocangiano.com/2007/11/28/holy-shmoly-ruby-19-smokes-python-away/ The Ruby developers are allowed to be proud. They were able to optimize some aspects of the implementation to get one algorithm about 14 times faster. That's good work. But why was it so slow in the first place? Nevertheless it is just one algorithm that beats Python in an area that is well known to be slow. Python's numbers are several factors slower than C code because the overhead of the dynamic language throws lots of data out of the cache line. If you need fast and highly optimized int and floating point operations you can rewrite the algorithm in C and create a Python interface for it. From andreas.tawn at ubisoft.com Wed Dec 5 11:37:44 2007 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Wed, 5 Dec 2007 17:37:44 +0100 Subject: Timeout test hangs IDLE In-Reply-To: <8AEDA5E3386EA742B8C24C95FF0C758002769405@PDC-MAIL3.ubisoft.org> References: <31ac8ae6-b2fb-4a8c-87ca-bf839d901312@e10g2000prf.googlegroups.com> <8AEDA5E3386EA742B8C24C95FF0C758002769405@PDC-MAIL3.ubisoft.org> Message-ID: <8AEDA5E3386EA742B8C24C95FF0C758002769406@PDC-MAIL3.ubisoft.org> > > On Dec 5, 6:00 am, "Andreas Tawn" wrote: > > > I'm trying to integrate the timeout function from > > herehttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/47 > > 3878into a > > > long running automation script and the following code > > causes IDLE after > > > 20 or 30 iterations in countTest. > > > > > > This is in 2.5, XP and there's no traceback. > > > > > > Could someone point me at the user error? > > > > > > Thanks in advance. > > > > > > def countTest(): > > > for i in xrange(10000000): > > > print i > > > return True > > > > > > def timeout(func, args=(), kwargs={}, timeout_duration=1, > > default=None): > > > import threading > > > class InterruptableThread(threading.Thread): > > > def __init__(self): > > > threading.Thread.__init__(self) > > > self.result = None > > > > > > def run(self): > > > try: > > > self.result = func(*args, **kwargs) > > > except: > > > self.result = default > > > > > > it = InterruptableThread() > > > it.start() > > > it.join(timeout_duration) > > > if it.isAlive(): > > > return default > > > else: > > > return it.result > > > > > > def runTest(): > > > timeout(countTest, timeout_duration=5) > > > > > > if __name__ == "__main__": > > > runTest() > > > > I'm confused. What does it cause IDLE to do? I tried running the > > script and it ran fine. I killed it 17346 since I have no > intention of > > letting it tie up my work for your extraordinary large iteration > > number. > > > > I'm using Python 2.4 on Windows XP. > > > > Mike > > Sorry, I need a better proof-reader. > > When I run that code, the output gets to ~26 and then IDLE (or the > shell, I'm not sure which) hangs and there's zero CPU activity in the > pythonw.exe process. Also, I should say that the the idea is that the huge iteration should timeout after 5 seconds. I only gave it a 10000000 range because I didn't know how fast it would get through the loop. Perhaps you stopped it before the timeout triggered? Cheers, Drea From shaik_saleem at hotmail.com Fri Dec 21 14:45:22 2007 From: shaik_saleem at hotmail.com (shaik_saleem at hotmail.com) Date: Fri, 21 Dec 2007 11:45:22 -0800 (PST) Subject: How to draw IE browser content in a window created with PythonWin Message-ID: <34eb84d5-d8e1-48a0-86e8-bdddbaed90d2@e25g2000prg.googlegroups.com> I'm pretty new to Python and I've been searching all over the place to find a solution for this. I have a html page with some javascript in it and I need to load this page in my own window (which I will create using PythonWin). The reason for this is to have capability to control the window properties and at the same time have access to click on the "submit" buttons in the webpage So basically, I will open a wepage as shown below - import win32com.client import win32api import win32gui ie = win32com.client.Dispatch( "InternetExplorer.Application" ) ie.Visible = 1 ie.Navigate("http://www.microsoft.com/") And then I need to display it in a window that I will create as shown below - hwnd = CreateWindowEx(...) I will be so grateful if anyone can please give me some pointers on how to go about this. Thank you for reading From esj at harvee.org Sat Dec 15 18:01:26 2007 From: esj at harvee.org (Eric S. Johansson) Date: Sat, 15 Dec 2007 18:01:26 -0500 Subject: Is Python really a scripting language? In-Reply-To: <476433c5$0$36399$742ec2ed@news.sonic.net> References: <009101c83c55$4ee07a00$6501a8c0@aristotle> <2bc2ab76-da7b-43ec-969d-33f77b174a56@e6g2000prf.googlegroups.com> <13m12513p8pfqb4@corp.supernews.com> <4760fea4$0$31443$426a74cc@news.free.fr> <13m4eefgi618319@corp.supernews.com> <4762CAEE.20005@animats.com> <476433c5$0$36399$742ec2ed@news.sonic.net> Message-ID: <47645CC6.2060804@harvee.org> John Nagle wrote: > Eric S. Johansson wrote: >> John Nagle wrote: >>> Yes. One of the basic design flaws of UNIX was that interprocess >>> communication was originally almost nonexistent, and it's still not >>> all that >>> great. It's easy to run other programs, and easy to send command line >>> parameters, but all you get back is a status code, plus console-type >>> output. >>> >>> The UNIX world might have been quite different if, when you ran a >>> subprocess, at the end you got return values for the command line >>> parameters (argv/argc) and the environment back. Then programs >>> would behave more like big subroutines. >> not if you use pickle. > > That assumes both programs were designed to intercommunicate that way. > Most UNIX applications aren't. There's no accepted standard on how > UNIX programs should intercommunicate, other than the 1970s technology > of piping human-readable strings around. Yes, there are marshalling > systems, of which Python's "Pickle" is one. But there's no standard > interprocess call system. And Pickle is only a marshalling system, > not a full IPC system. There's no resource location system. ("Where's > the browser process?" "Where's the database back-end?") I apologize if this gets you a bit cranky but I think you're conflating a few interprocess communications issues. I know I didn't fully articulate what I had been doing and I apologize. As your description above shows, there are multiple types of interprocess communications. My example shows how it's possible to make two cooperatively designed programs act as if they are communicating via a remote procedure call across a parent-child process boundary. Yes, other marshaling systems may be useful across multiple language environments. I wasn't concerned about that. I had to get a job done so I used pickle. when it comes right down to it, IPC systems are hard to do right. http://birrell.org/andrew/papers/ImplementingRPC.pdf is a pretty good reference for how to do it for our PCs. Also, the definition of right, depends on the communications medium used. For example, if the application is using pipes with sub processes, what I wrote is a workable implementation especially if you need to deal with privilege escalation. If you're talking over sockets or some equivalent communications channel, then yes, you need some form of resource location as well as handling methods exposure and resolution on both server and client side. But even if you have all of these items, you're still not out of the woods. There's a fundamental issue of reliability in the face of this complexity. I've written some code with psycho and, this is not meant as a slam against psycho, but the resource location subsystem was causing more problems than I care to deal with so I eliminated it from my project by hard coding certain essential bits of information. > > Both Gnome and OpenOffice use CORBA. But they use incompatible versions, > and you have to have a "CORBA ORB" running for that to work. There's > OpenRPC, which isn't used much any more. There's "System V IPC", which > isn't used much. There are XML-based systems. There's REST, JSON, and > similar approaches. None of these approaches ever got the kind of > widespread use that OLE did in the Microsoft world. All of these examples are great examples of overly complex IPC mechanisms. while the complexity may be necessary if you are going to handle 99% of all cases, the complexity makes it more difficult to document functionality in a comprehensible way. complexity reduces take up because it's too much work to figure out and use especially if it's a one-shot job. I believe it's fairly clear that a very simple IPC mechanism could handle a significant majority of project needs while making IPC functionality accessible to more developers. XML RPC almost achieves that except for its functional call orientation. But, I'm not a waste any more breath on "what ifs" because there's way too much technological alpha male behavior to ever build a simple common infrastructure component for IPC (or almost any other widely usable components for that matter). ---eric -- Speech-recognition in use. It makes mistakes, I correct some. From gagsl-py2 at yahoo.com.ar Sun Dec 30 02:57:43 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Dec 2007 23:57:43 -0800 (PST) Subject: do i need to create new rgbimage class References: <73ec5c59-0855-4b2b-8518-0b9f91abc42c@s8g2000prg.googlegroups.com> Message-ID: On 29 dic, 12:42, jimgarde... at gmail.com wrote: > am a beginner in python and PIL ?.I need to read an RGB 8 bit image > (am using jpeg )and pack the rgb color values into a double value so i > can store the image as a list of pixelvalues.From my application i > should be able to call rgbimage1.getpixellist() to retrieve the double > values of an image. (May I ask why an accessor like getpixellist() instead of simply rgbimage1.pixellist?) > Do i need to create a new class for this?I made something like > > class myrgbimage: > ? ? ? def ?__init__(self,filename): > > ? ? ? def _readimage(self): > ? ? ? ? ? im=Image.open(filename) > ? ? ? ? ? self._readImage(filename) > ? ? ? ? ? self._wd,self._ht=im.size > ? ? ? ? ? for y in range(self._ht): > ? ? ? ? ? ? ? ?for x in range(self._wd): > ? ? ? ? ? ? ? ? ? ? ?r,g,b=im.getpixel((x,y)) > ? ? ? ? ? ? ? ? ? ? ?pval=self.rgbTodoubleval((r,g,b)) > ? ? ? ? ? ? ? ? ? ? ?self._pixellist.append(pval) The PIL docs at [1] say that using getpixel is very slow, and suggest to use getdata instead. And you want a flat representation anyway, just like getdata. So replace the for loops above with: rgbTodoubleval = self.rgbTodoubleval self._pixellist = [rgbTodoubleval(pix) for pix in im.getdata()] I've not tested it, but should be faster. > def rgbTodoubleval(self,(r,g,b)): > alpha=255 > pixelvalue=(alpha<<24)|(r<<16 )|( g<<8) | b > return pixelvalue I don't get the name - why "rgb to double"? This does not return a "double", but a long integer, even if you intended to return a 32 bit integer. This version returns an integer: from struct import pack, unpack def rgbTodoubleval((r,g,b)): alpha=255 return unpack("l", pack("BBBB", b, g, r, alfa))[0] It *may*, or not, be what you want... -- Gabriel Genellina From adonisv at REMOVETHISearthlink.net Sun Dec 2 12:39:03 2007 From: adonisv at REMOVETHISearthlink.net (Adonis Vargas) Date: Sun, 02 Dec 2007 12:39:03 -0500 Subject: How can i find a file size on the web ? In-Reply-To: <093310bd-2129-4468-9275-3042b0b6da50@b40g2000prf.googlegroups.com> References: <093310bd-2129-4468-9275-3042b0b6da50@b40g2000prf.googlegroups.com> Message-ID: <13l5rdpsfnp209d@corp.supernews.com> Abandoned wrote: > Hi.. > Can i find a file size witdhout download? > For example: www.roche.com/rochea_z_sp.pdf > How can i find its size with python ? > I'm sorry for my bad english. Typically you would just do an HTTP HEAD request in order to get information about the file without downloading it, but I tested the given site and it does not seem to support the HEAD request. Instead I used the GET request and read the headers in which contains information regarding the file as well, but opted no to read the data to avoid downloading it. import httplib connection = httplib.HTTPConnection("www.roche.com") connection.request("GET", "/rochea_z_sp.pdf") response = connection.getresponse() print response.status, response.reason print "File sie: %s" % response.getheader('content-length') Also you can do: import urllib response = urllib.urlopen("http://www.roche.com/rochea_z_sp.pdf") print response.info() Hope this helps. Adonis Vargas From arkanes at gmail.com Fri Dec 14 13:34:33 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 14 Dec 2007 12:34:33 -0600 Subject: state machine and a global variable In-Reply-To: <51719149-ab7f-45f4-9824-d3786ee49e24@e25g2000prg.googlegroups.com> References: <51719149-ab7f-45f4-9824-d3786ee49e24@e25g2000prg.googlegroups.com> Message-ID: <4866bea60712141034o7b73b2f9p43ca6324a5c31c51@mail.gmail.com> On Dec 14, 2007 10:52 AM, wrote: > Dear list, > I'm writing very simple state machine library, like this: > > > > _state = None > > def set_state(state): > global _state > _state = state > > def get_state(): > print _surface > > > > but I hate to use global variable. So, please, is there a better way > of doing this? All I want is that a user has to type as little as > possible, like: > Yes, don't do it. > from state_machine import * > set_state(3) > get_state() > This isn't a state machine, it's just state > I.e., nothing like: > import state_machine > my_machine = state_machine.new_machine() > my_machine.set_state(3) > my_machine.get_state() > Stop being afraid of objects, especially if your fear is caused by straw-man C style APIs. from state_machine import State state = State() print state.current_state state.do_something('sadfsafsad') #does something based on the current state print state.current_state From supercooper at gmail.com Fri Dec 7 10:06:57 2007 From: supercooper at gmail.com (supercooper) Date: Fri, 7 Dec 2007 07:06:57 -0800 (PST) Subject: Converting Excel time-format (hours since 1.1.1901) References: <6c5cc79e-a121-45c5-9a97-b8564ca9f3bf@l16g2000hsf.googlegroups.com> Message-ID: <387dbfe1-a75b-4360-83cb-0fa500f51ba2@o42g2000hsc.googlegroups.com> On Dec 7, 8:15 am, Dirk Hagemann wrote: > On 7 Dez., 14:34, supercooper wrote: > > > > > On Dec 7, 7:20 am, Dirk Hagemann wrote: > > > > Hello, > > > > From a zone-file of a Microsoft Active Directory integrated DNS server > > > I get the date/time of the dynamic update entries in a format, which > > > is as far as I know the hours since january 1st 1901. > > > For Example: the number 3566839 is 27.11.07 7:00. To calculate this in > > > Excel I use this: > > > ="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0) (put > > > 3566839 in field A1 and switch the format of the result-field to the > > > corresponding date-time format). > > > > You might guess what I need now: I want to calculate this somehow in > > > python. > > > > Sorry, but I couldn't find anything in the module time or something > > > else to get this calculated. > > > > Does anyone know how to convert this time in python to something > > > usable or how to convert this formula in python? > > > > Thanks a lot and regards > > > Dirk > > > I think you want the xldate_as_tuple function in the xlrd module: > > >http://www.lexicon.net/sjmachin/xlrd.htm > > > It works like a champ for me: > > > >>> import xlrd > > >>> xlrd.xldate.xldate_as_tuple(38980,0) > > > (2006, 9, 20, 0, 0, 0) > > > chad! > > Thanks so far, that comes close to a solution I think, BUT when I > enter 3566985 instead of 38980 I get the following error: > Traceback (most recent call last): > File "test.py", line 20, in > print xlrd.xldate.xldate_as_tuple(3566985,0) > File "C:\Python25\lib\site-packages\xlrd\xldate.py", line 75, in > xldate_as_tuple > raise XLDateTooLarge(xldate) > xlrd.xldate.XLDateTooLarge: 3566985 > > Do I have to use another function of this module? My number is 2 > digits shorter than yours. What is 38980 representing? > > Dirk Excel stores dates as floating point numbers; the number of days (or fraction thereof) since 12/31/1899. So 38980.0 is midnight 9/20/2006. You think your numbers represent the number of hours since 1/1/1901? 3,566,985 hrs/24 hrs in a day = ~148,618 days 148,618 days/365 days in a year = ~407 years Am I doing the math wrong? From timr at probo.com Thu Dec 20 01:51:16 2007 From: timr at probo.com (Tim Roberts) Date: Thu, 20 Dec 2007 06:51:16 GMT Subject: Does fileinput.input() read STDIN all at once? References: <940l35-7lu.ln1@news.ducksburg.com> Message-ID: Adam Funk wrote: > >I'm using this sort of standard thing: > > for line in fileinput.input(): > do_stuff(line) > >and wondering whether it reads until it hits an EOF and then passes >lines (one at a time) into the variable line. This appears to be the >behaviour when it's reading STDIN interactively (i.e. from the >keyboard). > >As a test, I tried this: > > for line in fileinput.input(): > print '**', line > >and found that it would print nothing until I hit Ctl-D, then print >all the lines, then wait for another Ctl-D, and so on (until I pressed >Ctl-D twice in succession to end the loop). Note that you are doing a lot more than just reading from a file here. This is calling a function in a module. Fortunately, you have the source to look at. As I read the fileinput.py module, this will eventually call FileInput.next(), which eventually calls FileInput.readline(), which eventually calls stdin.readlines(_bufsize). The default buffer size is 8,192 bytes. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From dahlbokum at intes.de Mon Dec 17 08:50:55 2007 From: dahlbokum at intes.de (Markus Dahlbokum) Date: Mon, 17 Dec 2007 14:50:55 +0100 Subject: Static linking of python and pyqt Message-ID: <200712171450.55840.dahlbokum@intes.de> Hello, I'm trying to link python statically with qt and pyqt. I've tried this in several ways but never succeeded. At the moment the final make runs without errors but I get import errors when accessing pyqt. How can I solve this problem? Markus # installing zipimport hook import zipimport # builtin # installed zipimport hook # /opt/python-2.4.4/lib/python2.4/site.pyc matches /opt/python-2.4.4/lib/python2.4/site.py import site # precompiled from /opt/python-2.4.4/lib/python2.4/site.pyc # /opt/python-2.4.4/lib/python2.4/os.pyc matches /opt/python-2.4.4/lib/python2.4/os.py import os # precompiled from /opt/python-2.4.4/lib/python2.4/os.pyc import posix # builtin # /opt/python-2.4.4/lib/python2.4/posixpath.pyc matches /opt/python-2.4.4/lib/python2.4/posixpath.py import posixpath # precompiled from /opt/python-2.4.4/lib/python2.4/posixpath.pyc # /opt/python-2.4.4/lib/python2.4/stat.pyc matches /opt/python-2.4.4/lib/python2.4/stat.py import stat # precompiled from /opt/python-2.4.4/lib/python2.4/stat.pyc # /opt/python-2.4.4/lib/python2.4/UserDict.pyc matches /opt/python-2.4.4/lib/python2.4/UserDict.py import UserDict # precompiled from /opt/python-2.4.4/lib/python2.4/UserDict.pyc # /opt/python-2.4.4/lib/python2.4/copy_reg.pyc matches /opt/python-2.4.4/lib/python2.4/copy_reg.py import copy_reg # precompiled from /opt/python-2.4.4/lib/python2.4/copy_reg.pyc # /opt/python-2.4.4/lib/python2.4/types.pyc matches /opt/python-2.4.4/lib/python2.4/types.py import types # precompiled from /opt/python-2.4.4/lib/python2.4/types.pyc # /opt/python-2.4.4/lib/python2.4/warnings.pyc matches /opt/python-2.4.4/lib/python2.4/warnings.py import warnings # precompiled from /opt/python-2.4.4/lib/python2.4/warnings.pyc # /opt/python-2.4.4/lib/python2.4/linecache.pyc matches /opt/python-2.4.4/lib/python2.4/linecache.py import linecache # precompiled from /opt/python-2.4.4/lib/python2.4/linecache.pyc import encodings # directory /opt/python-2.4.4/lib/python2.4/encodings # /opt/python-2.4.4/lib/python2.4/encodings/__init__.pyc matches /opt/python-2.4.4/lib/python2.4/encodings/__init__.py import encodings # precompiled from /opt/python-2.4.4/lib/python2.4/encodings/__init__.pyc # /opt/python-2.4.4/lib/python2.4/codecs.pyc matches /opt/python-2.4.4/lib/python2.4/codecs.py import codecs # precompiled from /opt/python-2.4.4/lib/python2.4/codecs.pyc import _codecs # builtin # /opt/python-2.4.4/lib/python2.4/encodings/aliases.pyc matches /opt/python-2.4.4/lib/python2.4/encodings/aliases.py import encodings.aliases # precompiled from /opt/python-2.4.4/lib/python2.4/encodings/aliases.pyc # /opt/python-2.4.4/lib/python2.4/encodings/utf_8.pyc matches /opt/python-2.4.4/lib/python2.4/encodings/utf_8.py import encodings.utf_8 # precompiled from /opt/python-2.4.4/lib/python2.4/encodings/utf_8.pyc Python 2.4.4 (#1, Dec 7 2007, 11:16:51) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import QtCore import QtCore # builtin import sip # builtin Traceback (most recent call last): File "", line 1, in ? SystemError: _PyImport_FixupExtension: module QtCore not loaded >>> import sys >>> print sys.builtin_module_names ('QtCore', 'QtGui', '__builtin__', '__main__', '_codecs', '_sre', '_symtable', 'errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'pwd', 'signal', 'sip', 'sys', 'thread', 'time', 'xxsubtype', 'zipimport') >>> # clear __builtin__._ # clear sys.path # clear sys.argv # clear sys.ps1 # clear sys.ps2 # clear sys.exitfunc # clear sys.exc_type # clear sys.exc_value # clear sys.exc_traceback # clear sys.last_type # clear sys.last_value # clear sys.last_traceback # clear sys.path_hooks # clear sys.path_importer_cache # clear sys.meta_path # restore sys.stdin # restore sys.stdout # restore sys.stderr # cleanup __main__ # cleanup[1] site # cleanup[1] encodings # cleanup[1] _codecs # cleanup[1] zipimport # cleanup[1] PyQt4.QtCore # cleanup[1] warnings # cleanup[1] encodings.utf_8 # cleanup[1] codecs # cleanup[1] types # cleanup[1] signal # cleanup[1] linecache # cleanup[1] posix # cleanup[1] encodings.aliases # cleanup[1] exceptions # cleanup[2] copy_reg # cleanup[2] sip # cleanup[2] posixpath # cleanup[2] os.path # cleanup[2] stat # cleanup[2] UserDict # cleanup[2] os # cleanup sys # cleanup __builtin__ # cleanup ints: 7 unfreed ints in 1 out of 3 blocks # cleanup floats From skawanagi at gmail.com Mon Dec 10 19:54:08 2007 From: skawanagi at gmail.com (mosi) Date: Mon, 10 Dec 2007 16:54:08 -0800 (PST) Subject: Any way to program custom syntax to python prompt? >> I want to edit matrices. Message-ID: <639ad9a8-83ac-41b3-abf2-0759e70eb839@r60g2000hsc.googlegroups.com> Python matrices are usually defined with numpy scipy array or similar. e.g. >>> matrix1 = [[1, 2], [3, 4], [5, 6]] I would like to have easier way of defining matrices, for example: >>> matrix = [1, 2; 3, 4; 5, 6] >>> matrix = [ 1, 2; 3, 4; 5, 6;] Any ideas how could this be done? The ";" sign is reserved, the "[ ]" is used for lists. Also, how to program custom operations for this new "class?" matrix ??? For example: >>> matrix + 2 [ 3, 4; 5, 6; 7, 8;] Possibly with operator overloading? I appreciate all your comments, directions, pointers. mosi From jo at durchholz.org Sat Dec 29 04:30:32 2007 From: jo at durchholz.org (Joachim Durchholz) Date: Sat, 29 Dec 2007 10:30:32 +0100 Subject: Choosing a new language In-Reply-To: References: <20071228162351.f29a3ce4.coolzone@it.dk> <477561af$0$36390$742ec2ed@news.sonic.net> Message-ID: George Neuner schrieb: > I know not everyone > works in RT, but I can't possibly be alone in developing applications > that are hard to restart effectively. Indeed. An additional case is interactive applications where setting up the situation to be tested requires several time-consuming steps. Regards, Jo From ilias at lazaridis.com Sat Dec 22 10:46:06 2007 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sat, 22 Dec 2007 07:46:06 -0800 (PST) Subject: Detecting memory leaks on apache, mod_python References: <6f624cbd-294b-4a45-bf23-4219d8d6245e@x69g2000hsx.googlegroups.com> <2e1f149b-adc4-4e63-9161-c3de1bcbae77@j20g2000hsi.googlegroups.com> <5t1sv1F1b421hU1@mid.uni-berlin.de> <13mp5uvs8psio75@corp.supernews.com> Message-ID: On 22 ???, 09:09, Fredrik Lundh wrote: [...] > For Python, standard process monitoring tools (combined with a basic > understanding of how dynamic memory allocation works on modern > platforms) are usually sufficient to get a good view of an application's > memory usage patterns. [...] which "standard process monitoring tools" are those? Aren't there any python specific tools (e.g. which list the python modules which use the memory)? . http://case.lazaridis.com/wiki/PythonAudit From MonkeeSage at gmail.com Fri Dec 7 03:37:11 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: Fri, 7 Dec 2007 00:37:11 -0800 (PST) Subject: __iadd__ useless in sub-classed int References: <5b43ef4e-e8a7-4477-8f34-d337cdeaf8ab@e1g2000hsh.googlegroups.com> <5rqvttF15q694U1@mid.uni-berlin.de> <5f791364-eb19-44e1-87bf-12e65cded930@d27g2000prf.googlegroups.com> <9005dbaa-b6ac-415c-bed1-8a55f68e5d09@n20g2000hsh.googlegroups.com> Message-ID: On Dec 7, 12:45 am, "Gabriel Genellina" wrote: > En Fri, 07 Dec 2007 03:01:28 -0300, MonkeeSage > escribi?: > > > I've wondered about this myself. Seems to me, to prevent clobbering > > subclasses, __iadd__ (and all of the integer and float and whatever) > > methods that return new instances, should work like this (obviously I > > mean in the C backend, this is just to show the behavior): > > > def __iadd__(self, other): > > return self.__class__(self + other) > > This would slow down *all* of Python, and is only useful for those who > actually inherit from some builtin class (not so common) > > -- > Gabriel Genellina I understand why it doesn't. It just *seems* like it should work that way when you first run into it (and has bitten me a couple times before). But then, I'm not Dutch. :) Regard, Jordan From timr at probo.com Sat Dec 1 19:59:14 2007 From: timr at probo.com (Tim Roberts) Date: Sun, 02 Dec 2007 00:59:14 GMT Subject: python newbie - question about lexical scoping References: Message-ID: <3n04l31j75i7ntsuql0ckru7iajfv3m8kr@4ax.com> Matt Barnicle wrote: >hi everyone.. i've been chugging along learning python for a few months >now and getting answers to all needed questions on my own, but this one >i can't figure out nor can i find information on the internet about it, >possibly because i don't understand the right words to type into google.. > >i have a very common scenario and need to know the python way to do it. >take this example loop: > >comments = [] >for row in rows: > comment = models.comment() > comment.author = row[1] > comment.text = row[0] > comments.append(comment) > >the problem is that when i go to retrieve the comments later, they are >all the same object! i assume this is due to there being no lexical >scoping? so what is the solution to this? Is that REALLY what the code looks like? Or does it actually look like this: comments = [] comment = models.comment() for row in rows: comment.author = row[1] comment.text = row[0] comments.append(comment) That construct would produce exactly the result you describe. You would also get the result you describe if models.comment() were a normal function that returns a single object, instead of a class name, as I have assumed. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From scripteaze at gmail.com Wed Dec 19 18:18:00 2007 From: scripteaze at gmail.com (scripteaze) Date: Wed, 19 Dec 2007 15:18:00 -0800 (PST) Subject: sending a rip1 request via python References: <1603d479-76eb-4f76-8d5b-1dbd5ce79ddb@e4g2000hsg.googlegroups.com> <90c1519b-00a1-4165-ba8a-d8645d09e7e5@e23g2000prf.googlegroups.com> Message-ID: <882edb1c-bd71-4480-a995-b81da5202039@s12g2000prg.googlegroups.com> On Dec 19, 5:14 pm, scripteaze wrote: > On Dec 19, 10:34 am, Dirk Loss wrote: > > > > > scripteaze wrote: > > > I need to be able to send a rip1 request to my rip1 enabled device., > > > so i need python to send : > > > 01 01 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 > > > 10 > > > Use Scapy: > > > from scapy import * > > myrip = RIP()/RIPEntry(metric=16) > > ans, unans = sr(IP(dst="192.168.1.1")/UDP(sport=520)/myrip) > > >http://www.secdev.org/projects/scapy/ > > > Regards > > Dirk > > Well, i use scapy quite often, however, this needs to be very portable > from one box to another with out the installation of extra I was not finished, lol, for some reason my keyboard went haywire and did its own thing. Anywho, scapy is out of the question. any code examples? and also, whats the alternative. thanks in advance From rodmena.com at gmail.com Fri Dec 14 08:33:21 2007 From: rodmena.com at gmail.com (farsheed) Date: Fri, 14 Dec 2007 05:33:21 -0800 (PST) Subject: Better way to searching. References: <4f5b3c60-e2c7-4365-81c2-99959b62b6c9@b1g2000pra.googlegroups.com> Message-ID: <950efa91-27cf-43ca-9f9b-bc5d2a8a5010@s8g2000prg.googlegroups.com> thanks, I'll try it. From temp2 at cfl.rr.com Sun Dec 16 15:32:36 2007 From: temp2 at cfl.rr.com (temp2 at cfl.rr.com) Date: Sun, 16 Dec 2007 12:32:36 -0800 (PST) Subject: Terminate capability .... Message-ID: <029f6a2f-0ee4-4eca-a3b4-f4c3067c3b74@d21g2000prf.googlegroups.com> Hello, I'm new to Python. I have a small task to do. I need to be able to find a running app (preferrably by name) and kill it. This is for the XP environment. What is best way to do this? Thanks, From ianare at gmail.com Fri Dec 21 15:48:23 2007 From: ianare at gmail.com (=?ISO-8859-1?B?aWFuYXLp?=) Date: Fri, 21 Dec 2007 12:48:23 -0800 (PST) Subject: mac dashboad References: Message-ID: On Dec 21, 12:37 pm, Carl K wrote: > How do I hang an app off the mac dashboard? > > The goal is a python version of Weatherbug. > > something like: > read xml data from a URL, > display some numbers, > mouse over shows more details > > Carl K What is the dashboard - is it anything like the taskbar in windows/ Gnome? If it is, take a look at this: http://www.wxwidgets.org/manuals/2.6.3/wx_wxtaskbaricon.html From python.list at tim.thechases.com Sat Dec 1 07:33:54 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 01 Dec 2007 06:33:54 -0600 Subject: "Python" is not a good name, should rename to "Athon" In-Reply-To: <78bdd499-a263-4c68-8e43-e3e59b111c7e@a39g2000pre.googlegroups.com> References: <78bdd499-a263-4c68-8e43-e3e59b111c7e@a39g2000pre.googlegroups.com> Message-ID: <475154B2.90300@tim.thechases.com> > I agree that Python is not a good name for a programming language, but > I'm afraid we're stuck with it. Well, the language was going to be called "One of the cross beams has gone out askew on the treadle" but that was a little unwieldy and hard to understand when mumbled in a hury. Searching for the runtime "ootcbhgoaott" returns zero hits on Google. That would have guaranteed that the only hits that came back related to the language. However typing things like sh$ ootcbhgoaott myprog.ootcbhgoaott became too cumbersome. So they decided on Python instead. Besides...nobody expected a kind of Spanish Inquisition... Just-making-stuff-up'ly yers, -tkc From sharun.mg at gmail.com Wed Dec 19 07:59:16 2007 From: sharun.mg at gmail.com (Sharun) Date: Wed, 19 Dec 2007 04:59:16 -0800 (PST) Subject: Need help with a regular expression References: <77d0fa90-580c-4429-9fb9-5c1fcd634328@t1g2000pra.googlegroups.com> Message-ID: <04379109-0629-47e2-bbca-1b0561600117@d21g2000prf.googlegroups.com> Thanks Marek! From python.list at tim.thechases.com Mon Dec 10 06:26:42 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 10 Dec 2007 05:26:42 -0600 Subject: Best way to protect my new commercial software. In-Reply-To: <9771eb4a-fae5-472d-9cba-9a09ae077e3d@x69g2000hsx.googlegroups.com> References: <8c9a903b-7f57-4a90-883a-5bb1f06fedf6@e6g2000prf.googlegroups.com> <46303db5-7cd0-4424-9834-3458c4061229@w56g2000hsf.googlegroups.com> <9e1711a2-688b-4643-a276-659163e867f1@d61g2000hsa.googlegroups.com> <9771eb4a-fae5-472d-9cba-9a09ae077e3d@x69g2000hsx.googlegroups.com> Message-ID: <475D2272.5090104@tim.thechases.com> > So you say there is not any trusted way? You cannot distribute any program with the expectation that it cannot be reverse engineered. Despite what various protection companies would have folks believe. At some point, the user's CPU has to execute the code, and at that point, it can be intercepted, unwound, and intercepted. The *only* way to prevent people from reverse engineering your code (until quantum computing becomes a household standard) is to never give your code to them. Keep it on your servers and only allow users to access your service, not your code. Or, you could just trust your customers to adhere to your licensing terms (with this little thing called "the law" to back you up, as long as your licensing terms are legal). Then just distribute your software and spend your energies making a better product rather than chasing a quixotic dream of protection. Customers prefer not to be treated as criminals. -tkc From xkenneth at gmail.com Fri Dec 28 17:51:04 2007 From: xkenneth at gmail.com (xkenneth) Date: Fri, 28 Dec 2007 14:51:04 -0800 (PST) Subject: Tab indentions on different platforms? Message-ID: <14a26d3f-94de-4887-b3f4-d837a2723f35@21g2000hsj.googlegroups.com> All, I seem to be having problems with running my python code, written on a Mac, on Linux and Windows boxes. It seems like the problem has to do with tab indention, particularly I've noticed that my code will completely ignore try statements. Has anyone had a similar problem? Regards, Ken From nyamatongwe+thunder at gmail.com Wed Dec 12 16:26:39 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Wed, 12 Dec 2007 21:26:39 GMT Subject: After running for four days, Python program stalled In-Reply-To: <4760371e$0$36373$742ec2ed@news.sonic.net> References: <4760371e$0$36373$742ec2ed@news.sonic.net> Message-ID: John Nagle: > Had a Python program stall, using no time, after running OK for four days. > Python 2.4, Windows. Here's the location in Python where it's stalled. > Any idea what it's waiting for? > 77FA144B int 3 # STALLED HERE Its a breakpoint instruction and its likely you are running under a debugger that is failing to respond. You don't often see a bare 'int 3' in real code unmassaged by a debugger unless the developer wants an explicit break to debugger. Neil From rodmena.com at gmail.com Sat Dec 1 06:05:16 2007 From: rodmena.com at gmail.com (farsheed) Date: Sat, 1 Dec 2007 03:05:16 -0800 (PST) Subject: "Show this file in explorer" References: <8bca2fe0-c81f-4f93-8325-e0e99636762a@p69g2000hsa.googlegroups.com> Message-ID: <8ec38759-2a7a-4864-a9e8-542200585e49@l16g2000hsf.googlegroups.com> That was great. Thanks so sooooooooooooooooooooooooooooooooo much. can you tell me where can I find that kind of trips? Thanks Again. From gagsl-py2 at yahoo.com.ar Thu Dec 27 03:05:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Dec 2007 05:05:19 -0300 Subject: Happy Christmas Pythoneers References: <49cb0a4e-9256-44ee-9164-424b029a8f9c@y5g2000hsf.googlegroups.com> <8b4f001d-33d3-47d5-b523-f619f82769e8@f3g2000hsg.googlegroups.com> Message-ID: En Thu, 27 Dec 2007 02:32:54 -0300, mensanator at aol.com escribi?: > On Dec 26, 9:43?pm, Steven D'Aprano > wrote: >> watch_fireworks() >> try: >> ? ? champagne >> except NameError: >> ? ? champagne = any_fizzy_alcoholic_drink_will_do() >> champagne.drink() >> shout("Happy New Years!!!") >> for person in adults_nearby: >> ? ? if (person.is_appropriate_sex and person.is_pretty): > > Hey, my version of the person module doesn't have > an is_appropriate_sex attribute, but an > is_opposite_sex attribute instead. Is this a new version? The default is_appropriate_sex implementation just happens to call is_opposite_sex, but this is an implementation detail and you should not rely on that, even more so if you didn't create that particular person instance. -- Gabriel Genellina From bj_666 at gmx.net Sun Dec 9 03:49:57 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Dec 2007 08:49:57 GMT Subject: dictionary of dictionaries References: <8bbf5f9a-e4ed-412c-bff8-45a316478a24@b1g2000pra.googlegroups.com> Message-ID: <5s1ohlF16tekoU3@mid.uni-berlin.de> On Sun, 09 Dec 2007 00:35:18 -0800, kettle wrote: > Hi, > I'm wondering what the best practice is for creating an extensible > dictionary-of-dictionaries in python? > > In perl I would just do something like: > > my %hash_of_hashes; > for(my $i=0;$i<10;$i++){ > for(my $j=0;$j<10;$j++){ > ${$hash_of_hashes{$i}}{$j} = int(rand(10)); > } > } > > but it seems to be more hassle to replicate this in python. I've > found a couple of references around the web but they seem cumbersome. > I'd like something compact. Use `collections.defaultdict`: from collections import defaultdict from random import randint data = defaultdict(dict) for i in xrange(11): for j in xrange(11): data[i][j] = randint(0, 10) If the keys `i` and `j` are not "independent" you might use a "flat" dictionary with a tuple of both as keys: data = dict(((i, j), randint(0, 10)) for i in xrange(11) for j in xrange(11)) And just for completeness: The given data in the example can be stored in a list of lists of course: data = [[randint(0, 10) for dummy in xrange(11)] for dummy in xrange(11)] Ciao, Marc 'BlackJack' Rintsch From pavlovevidence at gmail.com Sat Dec 15 09:39:52 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 15 Dec 2007 06:39:52 -0800 (PST) Subject: container.___le___ can use only <=? References: <92ddc6c2-e24d-4c10-9bfe-0a5b6d37099f@o42g2000hsc.googlegroups.com> <56b659be-4f37-4abf-9944-b9529c0a950a@w40g2000hsb.googlegroups.com> Message-ID: <35e45707-c095-4db1-b78f-7338b4efe1e9@w56g2000hsf.googlegroups.com> On Dec 15, 9:05 am, ceru... at tds.net wrote: > On Dec 15, 8:33 am, Carl Banks wrote: > > > > > On Dec 14, 4:15 pm, Neil Cerutti wrote: > > > > When implementing the rich comparison operators for some sort of > > > container, it's tempting to save code by doing something like: > > > > class LarchTree: > > > ... > > > def __gt__(self, other): > > > # A lot of code to traverse the tree > > > def __le__(self): > > > return not self > other > > > > However, if I'm thinking correctly, this is a bad idea. The > > > reasoning being that > and <= are not required to be each others > > > opposite for arbitrary value types, and may not even both be > > > supplied by the contained objects. > > > And yet, by the same reasoning, using > and <= for list and tuple is > > also a "bad idea". > > My reasoning is (I hope) that the container ought to support every > comparison operation supported by the contained objects. This can be > ensured by being careful in the implementation. I see what you're asking now. Yep, probably a bad idea to use that shortcut. Carl Banks From benoit.barberousse at gmail.com Thu Dec 20 06:35:23 2007 From: benoit.barberousse at gmail.com (Benoit) Date: Thu, 20 Dec 2007 03:35:23 -0800 (PST) Subject: Is there *any* real documentation to PyWin32? Message-ID: I understand that the Win32 has been said to be itself poorly documented, so perhaps that the documentation that comes with the modules is of similar quality is no coincidence. Maybe I'm still too young in my programming to grasp the good of that documentation, but for myself, it tells me next to nothing. Could anyone point me to anything which may exist that does a better job of explaining the extensions' use? I tried to take a look @ Microsoft's documentation, but it was confusing. From david.van.mosselbeen__NO-SPAM__ at telenet.be Mon Dec 31 01:57:47 2007 From: david.van.mosselbeen__NO-SPAM__ at telenet.be (David Van Mosselbeen) Date: Mon, 31 Dec 2007 06:57:47 GMT Subject: Python for web... References: <983c7459-7388-41ca-a192-b39805ea0b69@s8g2000prg.googlegroups.com> Message-ID: on Tue, 25 Dec 2007 20:42:03 -0800 (PST), thushianthan15 at gmail.com wrote: > > Hi everyone, > > I have to develop a web based enterprise application for my final year > project. Since i am interested in open source, i searched the net. > Almost 90% of them were PHP and MySQL. Cant we use python for that ? I > tried several sites, but there is not enough tutorial for beginners > [mod_python, PSP etc]. I couldnt find any detailed book, not even a > single book :( All the python books are covering only CGI part) > > Any suggestions? Any recommended book? > > Execuse my English. > > Thushanthan. You can also take a look to `webpy` and `cherrypy`. These where not yet mentioned. -- David Van Mosselbeen http://dvm.zapto.org:8080/ From jigisbert.etra-id at grupoetra.com Thu Dec 13 01:32:19 2007 From: jigisbert.etra-id at grupoetra.com (Jose Ignacio Gisbert) Date: Thu, 13 Dec 2007 07:32:19 +0100 Subject: *SPAM*: 04.0/4.0 - Re: how to maximize a Tkinter Window in python TK??? In-Reply-To: References: <3f227a13-ae24-4f17-9a0b-2c7f01ccec05@c4g2000hsg.googlegroups.com> Message-ID: <000f01c83d51$e9d7d2e0$2000a8c0@depid.local> If you want to start with your main window maximized, you can do: root = Tk() root.state("zoomed") Regards, Naxo -----Mensaje original----- De: python-list-bounces+jigisbert.etra-id=grupoetra.com at python.org [mailto:python-list-bounces+jigisbert.etra-id=grupoetra.com at python.org] En nombre de Matimus Enviado el: jueves, 13 de diciembre de 2007 2:18 Para: python-list at python.org Asunto: *SPAM*: 04.0/4.0 - Re: how to maximize a Tkinter Window in python TK??? On Dec 12, 3:11 pm, "d4v.j... at googlemail.com" wrote: > hello @ all, > > subj? example: import Tkinter as tk rt = tk.Tk() rt.state("zoomed") rt.overrideredirect(True) can = tk.Canvas(rt, bg="black",borderwidth=0,highlightthickness=0) can.pack(expand=True, fill=tk.BOTH) def draw_rect(e): can.create_rectangle(e.x,e.y,e.x+100,e.y+100, fill='white', outline='white') can.bind("",draw_rect) rt.bind("",lambda e:rt.destroy()) rt.mainloop() -Matt -- http://mail.python.org/mailman/listinfo/python-list From i.pantusa at gmail.com Fri Dec 14 15:42:46 2007 From: i.pantusa at gmail.com (i.pantusa at gmail.com) Date: Fri, 14 Dec 2007 12:42:46 -0800 (PST) Subject: Loops and things References: Message-ID: <8238ee91-cc67-497a-bf51-951729809fce@i29g2000prf.googlegroups.com> On Dec 14, 5:01 pm, Neil Cerutti wrote: > On 2007-12-14, rocco.ro... at gmail.com wrote: > > > > > I was wondering how and if it's possible to write a loop in python > > which updates two or more variables at a time. For instance, something > > like this in C: > > > for (i = 0, j = 10; i < 10 && j < 20; i++, j++) { > > printf("i = %d, j = %d\n", i, j); > > } > > > So that I would get: > > > i = 0, j = 0 > > i = 1, j = 1 > > i = 2, j = 2 > > ... > > ... > > ... > > i = 9, j = 19 > > > Can this be done in Python? > > Yes, assuming you meant to say: > > i = 0, j = 10 > i = 0, j = 11 > ... > i = 9, j = 19 > > import sys > from itertools import izip > > for i, j in izip(xrange(10), xrange(10, 20)): > sys.stdout.write("i = %d, j = %d\n", (i, j)) > > -- > Neil Cerutti > To succeed in the world it is not enough to be stupid, you must also be well- > mannered. --Voltaire Yeah, that's what I meant ... ooops :) Thanks a lot to everyone for the useful info. In the meantime I had found out about zip and that way of doing it. But I really appreciated all the different alternative solutions that were illustrated, especially the more "functional" ones with map ... very cool, I'm also a big Lisp fan, and I really dig those. From t.rectenwald at gmail.com Wed Dec 26 11:51:14 2007 From: t.rectenwald at gmail.com (t_rectenwald) Date: Wed, 26 Dec 2007 08:51:14 -0800 (PST) Subject: Writing Oracle Output to a File References: <9ea3f90b-23e1-46c2-beb9-2b7cd8cf83cc@s48g2000hss.googlegroups.com> Message-ID: On Dec 26, 10:36?am, t_rectenwald wrote: > Hello, > > I attempting to execute an Oracle query, and write the results to a > file in CSV format. ?To do so, I've done the following: > > import cx_Oracle > db = cx_Oracle.connect('user/pass at DBSID') > cursor = db.cursor() > cursor.arraysize = 500 > cursor.execute(sql) > result = cursor.fetchall() > > The above works great. ?I'm able to connect to the database and print > out the results as a list of tuples. ?Here is where I get lost. ?How > do I work with a "list of tuples?" ?My understanding is that a "list" > is basically an array (I don't come from a Python background). ?Tuples > are a "collection of objects." ?So, if I do... > > print result[0] > > I get the first row of the query, which would make sense. ?The problem > is that I cannot seem to write tuples to a file. ?I then do this... > > csvFile = open("output.csv", "w") > csvFile = write(result[0]) > csvFile.close > > This generates an exception: > > TypeError: argument 1 must be string or read-only character buffer, > not tuple > > So, I'm a bit confused as to the best way to do this. ?I guess I could > try to convert the tuples into strings, but am not sure if that is the > proper way to go. ?Any help would be appreciated. ?I've also seen a > csv module out there, but am not sure if that is needed in this > situation. > > Best Regards, > Tom Hello, I was able to figure this out by using join to convert the tuples into strings, and then have those write to the filehandle: csvFile = open("output.csv", "w") for row in cursor.fetchall(): csvFile.write(','.join(row) + "\n") csvFile.close Regards, Tom From piet at cs.uu.nl Thu Dec 6 10:12:20 2007 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 06 Dec 2007 16:12:20 +0100 Subject: "Python" is not a good name, should rename to "Athon" References: <78bdd499-a263-4c68-8e43-e3e59b111c7e@a39g2000pre.googlegroups.com> Message-ID: >>>>> "Adrian Cherry" (AC) wrote: >AC> Piet van Oostrum wrote in >AC> news:m28x49qads.fsf at cochabamba.cs.uu.nl: >>>>>>>> "Adrian Cherry" (AC) wrote: >>> >AC> For that matter C# is no better, I thought that # was >>>> pronounced AC> hash, I still refer to C# as C-hash. >>> >>> Are you musically illiterate? >AC> Yup! The limits of my musically ability is >AC> Spam, spam, spam, spam. >AC> Lovely spam! Wonderful spaaam! >AC> Lovely spam! Wonderful spam. >AC> Spa-a-a-a-a-a-a-am! Spa-a-a-a-a-a-a-am! >AC> Is that a problem? It's still a hash sign to me. No problem, but if you know music notation, C# will ring a bell. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From bdesth.quelquechose at free.quelquepart.fr Tue Dec 11 16:04:01 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 11 Dec 2007 22:04:01 +0100 Subject: Is anyone happy with csv module? In-Reply-To: <15ab759b-0aec-45dd-88b9-c446c2b7d299@e10g2000prf.googlegroups.com> References: <15ab759b-0aec-45dd-88b9-c446c2b7d299@e10g2000prf.googlegroups.com> Message-ID: <475efb4f$0$18754$426a74cc@news.free.fr> massimo s. a ?crit : > Hi, > > I'm struggling to use the python in-built csv module, and I must say > I'm less than satisfied. Apart from being rather poorly documented, I > find it especially cumbersome to use, and also rather limited. What I > dislike more is that it seems working by *rows* instead than by > *columns*. Indeed. > So I have some questions: > 1) Is there a good tutorial, example collection etc. on the csv module > that I'm missing? Not AFAIK > 2) Is there an alternative csv read/write module? Not AFAIK > 3) In case anyone else is as unhappy as me, and no tutorial etc. > enlighten us, and no alternative is present, anyone is interested in > an alternative csv module? I'd like to write one if it is the case. As far as I'm concerned, and having spent some time trying to write a CSV module (before I noticed the existing one - duh...), I'm fully satisfied with the existing one. But if you feel like doing better and contributing it, by all means do it. From pofuk at email.t-com.hr Fri Dec 14 17:20:42 2007 From: pofuk at email.t-com.hr (SMALLp) Date: Fri, 14 Dec 2007 23:20:42 +0100 Subject: Python import search path! In-Reply-To: <6f899751-2117-4a5e-b6fd-70ea02dd6da4@s8g2000prg.googlegroups.com> References: <6f899751-2117-4a5e-b6fd-70ea02dd6da4@s8g2000prg.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Dec 14, 3:44 pm, SMALLp wrote: >> Hy! >> I'm new in Linux, and i feel little less newer in python. >> >> I need advice and help. I'm making an application witch purpose is >> irrelevant. It has a lot of code for now and I've only made interface. >> So I've tried to split code into separate files and in windows as I >> remember worked file when i wrote eg. import myFile but now in Ubuntu >> it says Module not found. (I'm using Ubuntu and I've installed python >> 2.5 and wxPython 2.8.4, and I'm using GedIt as my favorite text editor). >> The question is how to make this work (files are in the same folder) >> > > Not sure what is going on here from this description. You may need to > use the sys module and add the path to your module temporarily. > > import sys > sys.path.append("//path/to/myFile") > > I managed to make simple thing complicated. So what i was trying to do is to write part of my program in a separate file and than use "import myFile as my" to use classes written in that file. Thanks for the answer Mike! From nospam at nospam.com Wed Dec 26 17:04:33 2007 From: nospam at nospam.com (Gilles Ganault) Date: Wed, 26 Dec 2007 23:04:33 +0100 Subject: [newbie] Read file, and append? References: <2ig1n31tjm7hpj7k7mgg6stu51rdkq81ov@4ax.com> <13n2td29ahlcp3f@corp.supernews.com> Message-ID: <1qj5n31h7nb4frm7bh1tn9pish3minhfao@4ax.com> On Tue, 25 Dec 2007 13:27:09 -0800, Dennis Lee Bieber wrote: >Ignoring the question of the proper I/O mode, I believe the I/O >system MAY require one to perform a seek() when switching from read to >write and vice versa... I thought about this, but I don't understand why I would need to do this: myfile=open('test.txt','r+') content = myfile.read() myfile.seek() myfile.write('added this') myfile.close Is there really no way to read from a file and append data to it while keeping the file open? Also, I noticed a problem with the code given by Garry: When opening a file in binary mode, the EOF character is 0A, while Windows apps expect 0D0A. VisualBasic was not happy :-) From aaragao at gmail.com Tue Dec 11 17:02:11 2007 From: aaragao at gmail.com (aaragao at gmail.com) Date: Tue, 11 Dec 2007 14:02:11 -0800 (PST) Subject: Tuples !?!? References: <475ef5c7$0$25948$426a34cc@news.free.fr> Message-ID: <013f3fa0-fb00-4ab2-95d9-ce034714dfb0@i29g2000prf.googlegroups.com> Ok. This is small code. The problem is '2' != 2 there is a way of converting 'some number' in number ? Thanks. # -*- coding: cp1252 -*- import random import csv import struct import array # resultados para colocar nos campos def gera_string(res): # acampo3 acampo1=((0,5,'muito reduzidos'),(6,20,'reduzidos'), (21,32,'satisfat?rios'),(33,40,'bons'),(41,45,'excelentes')) campo1='' for a in acampo1: print res[1] if (res[1]>=a[0] and res[1]<=a[1]): campo1=a[2] return campo1 # processar res=['a','2'] print gera_string(res) quit() On 11 Dez, 20:40, Bruno Desthuilliers wrote: > aara... at gmail.com a ?crit : > > > Hi, > > > Is the tuple comparison brooked in python ?!?!? > > Given the size and average level of the user base, I think this would > have been noticed. > > > > > Try this > > If you hope anyone to try anything, please post the *minimal* working > code showing the problem. And while your at it, also explain the > expected result. > > > and you will see funny things: > > Sorry but the only thing I see so far is that your code needs refactoring. From sjmachin at lexicon.net Thu Dec 13 05:40:49 2007 From: sjmachin at lexicon.net (John Machin) Date: Thu, 13 Dec 2007 02:40:49 -0800 (PST) Subject: MySQLdb extracting to a list References: <6b8888e2-ee92-4122-929a-4b2034ab297a@e10g2000prf.googlegroups.com> Message-ID: On Dec 13, 9:03 pm, dave.... at googlemail.com wrote: > Hi all, > > I've been searching the docs like mad and I'm a little new to python > so apologies if this is a basic question. > > I would like to extract the results of the following query into a list > - SELECT columnname FROM tablename. I use the following code. > > # Create a connection object and create a cursor > db = MySQLdb.Connect( cursor = db.cursor() > # Make SQL string and execute it > sql = "SELECT columnname FROM tablename" > cursor.execute(sql) > # Fetch all results from the cursor into a sequence and close the > connection > results = cursor.fetchall() > db.close() > print results > > The output from the above gives the following: > > (('string1',), ('string2',), ('string3',)) > > When I'm expecting > ('string1', 'string2', 'string3') > > I could pass this through some string manipulation but I'd guess I'm > doing something wrong. Please could someone point me in the right > direction. > Your SQL query has returned 3 rows. Each row contains only 1 column. Each row is returned as a tuple of 1 element. The whole result is a tuple of 3 rows. You don't need string manipulation, you need tuple manipulation. Better example: select name, hat_size from friends; results in: (('Tom', 6), ('Dick', 7), ('Harry', 8)) so: >>> result = (('Tom', 6), ('Dick', 7), ('Harry', 8)) >>> [row[0] for row in result] ['Tom', 'Dick', 'Harry'] >>> for n, h in result: ... print 'Name: %s; hat size: %d' % (n, h) ... Name: Tom; hat size: 6 Name: Dick; hat size: 7 Name: Harry; hat size: 8 >>> result[2][1] 8 >>> HTH, John From raj.amal at gmail.com Wed Dec 19 08:35:20 2007 From: raj.amal at gmail.com (Amal) Date: Wed, 19 Dec 2007 19:05:20 +0530 Subject: HTML unit . Message-ID: <3bfbb0bb0712190535h22fc0ebke38c9ff33ed44a4a@mail.gmail.com> Is there something like HTML unit for python. I don't want to use jython and use the existing Java based HTML unit. Amal. -------------- next part -------------- An HTML attachment was scrubbed... URL: From russblau at hotmail.com Sat Dec 15 11:23:15 2007 From: russblau at hotmail.com (Russell Blau) Date: Sat, 15 Dec 2007 11:23:15 -0500 Subject: Tkinter weirdness on Windows In-Reply-To: References: Message-ID: I have some Tkinter programs that I run on two different machines. On Machine W, which runs Python 2.5.1 on Windows XP, these programs run just fine. On Machine H, which runs Python 2.5.1 on Windows XP, however, the same programs crash regularly. The crashes are not Python exceptions, but rather are reported by Windows as errors in pythonw.exe. (Of course, the error messages themselves contain absolutely no useful information.) This happens whether I run them from the command prompt or from IDLE (although IDLE itself never crashes). Further, the crashes occur at unpredictable times; sometimes the program will crash almost immediately upon startup, while at other times it will run for a while and then crash. A couple of other points that may or may not have something to do with it. (1) Both programs use the threading module to launch new threads from the GUI. (2) Machine H, but not Machine W, also has Python 2.2 installed on it. I do recall seeing a message at some point that suggested that conflicts in the MS VC++ runtime DLLs might cause this sort of problem, but I haven't been able to find that information through a search, so I'm not sure which particular DLLs to look for. Any help in tracking down the source of this problem would be appreciated. Russ _________________________________________________________________ Share life as it happens with the new Windows Live. http://www.windowslive.com/share.html?ocid=TXT_TAGHM_Wave2_sharelife_122007 -------------- next part -------------- An HTML attachment was scrubbed... URL: From george.sakkis at gmail.com Mon Dec 24 15:26:48 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 24 Dec 2007 12:26:48 -0800 (PST) Subject: 5 queens References: <9639f80c-5722-40c6-bd7b-b727d0a7804e@n20g2000hsh.googlegroups.com> <13mrp429n5oai2a@corp.supernews.com> <13mrpe0cccvrle3@corp.supernews.com> <13msjn5erd72n2a@corp.supernews.com> Message-ID: On Dec 23, 7:04 am, Steven D'Aprano wrote: > def combinations(seq, n): > if n == 0: > yield [] > else: > for i in xrange(len(seq)): > for cc in combinations(seq[i+1:], n-1): > yield [seq[i]]+cc > > >>> for c in combinations(range(4), 3): > > ... print c > ... > [0, 1, 2] > [0, 1, 3] > [0, 2, 3] > [1, 2, 3] Or if you only need to iterate over each combination once instead of keeping around more than one of them, below is a more efficient version that reuses the same list for all combinations. Also it doesn't require the input sequence to implement slicing so it can be used e.g. with xrange: def itercombos(seq, n): def ifill(combo, i, start, end=len(seq), seq=seq, n=n): if i == n: yield combo else: i1 = i+1 for j in xrange(start,end): combo[i] = seq[j] for combo in ifill(combo, i1, j+1): yield combo for combo in ifill(n*[None],0,0): yield combo >>> for c in itercombos(xrange(4), 3): print c [0, 1, 2] [0, 1, 3] [0, 2, 3] [1, 2, 3] >>> for c in combinations(xrange(4), 3): print c Traceback (most recent call last): File "combs.py", line 54, in for c in combinations(xrange(4), 3): print c File "combs.py", line 12, in combinations for cc in combinations(seq[i+1:], n-1): TypeError: sequence index must be integer, not 'slice' George From mensanator at aol.com Fri Dec 14 15:09:33 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Fri, 14 Dec 2007 12:09:33 -0800 (PST) Subject: Is Python really a scripting language? References: <009101c83c55$4ee07a00$6501a8c0@aristotle> Message-ID: <8ce054b2-9d24-4fdc-90cb-11d64bc2c17a@d4g2000prg.googlegroups.com> On Dec 11, 10:34 pm, "Terry Reedy" wrote: > "Ron Provost" wrote in message > > news:009101c83c55$4ee07a00$6501a8c0 at aristotle... > But here's my problem, most of my coworkers, when they see my apps and > learn that they are written in Python ask questions like, "Why would you > write that in a scripting language?" Whenever I hear a comment like that I > can feel myself boiling inside. > =================== > > I don't blame you. Python is an full-fledged algorithm/programming > language that was designed to *also* be used a scripting language. When you buy a new car, which is more important, the styling or what's under the hood? Take, for example, Microsoft's slick new language F#. F# (pronounced F Sharp) is a multi-paradigm programming language, targeting the .NET Framework, that encompasses functional programming as well as imperative object-oriented programming disciplines. It is a variant of ML and is largely compatible with the OCaml implementation. Sounds pretty sexy, eh? And programs compile to .exe files, none of that byte-code interpretation nonsense. But you would never buy a car without taking a test drive, right? So we can fire up the F# Interactive (Console) and put it in gear. > #time;; --> Timing now on > open Math;; Time 0.046875 > let mutable Z = 0I;; val mutable Z : bigint Time 0.156250 > Z <- Z + (BigInt.pow 3I 123295I) * (BigInt.pow 2I 0I);; val it : unit = () Time 0.515625 > About a half second to compute a number with 58827 decimal digits. OTOH, that was only the first of 123296 terms. The time to compute the full sequence is 0.515625*123296 seconds or 17.65 hours. If it takes that long for a compiled .exe to run, just imagine how long a lowly, byte-code interpreted language would take! But wait... ...we don't have to imagine, we can take the Python out for a test drive also. >>> import collatz_functions >>> import time >>> sv = collatz_functions.build_sv(19,19,1000000,1541095) >>> def Big_Z(sv): Z = 0 e2 = 0 e3 = len(sv) - 1 t0 = time.time() for v in sv: Z += 3**e3 * 2**e2 e3 -= 1 e2 += v t1 = time.time() print (t1-t0)/60,'minutes' >>> Big_Z(sv) 25.6775999983 minutes Hold on... That's for the whole sequence, not a single term! 25.67 MINUTES compared to 17.65 HOURS! So, sure, some languages compile to .exe programs. In the trade, we call that "polishing a turd". From arkanes at gmail.com Mon Dec 10 13:23:48 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 10 Dec 2007 12:23:48 -0600 Subject: Best way to protect my new commercial software. In-Reply-To: References: <8c9a903b-7f57-4a90-883a-5bb1f06fedf6@e6g2000prf.googlegroups.com> <46303db5-7cd0-4424-9834-3458c4061229@w56g2000hsf.googlegroups.com> <9e1711a2-688b-4643-a276-659163e867f1@d61g2000hsa.googlegroups.com> <9771eb4a-fae5-472d-9cba-9a09ae077e3d@x69g2000hsx.googlegroups.com> Message-ID: <4866bea60712101023lb286ec9q900ba00a5e8570f5@mail.gmail.com> On Dec 10, 2007 5:56 AM, Carl Banks wrote: > On Dec 10, 6:26 am, Tim Chase wrote: > > > So you say there is not any trusted way? > > > > You cannot distribute any program with the expectation that it > > cannot be reverse engineered. > [snip] > > > >From the OP's post, it seemed likely to me that the OP was asked by a > misguided management to make sure it was "reverse-engineer-proof". So > any attempt to convince the OP may be aimed at the wrong person. > > Misguided as they are, sometimes you have to placate these people. > So, are there any ways to make it "harder" to reverse engineer a > program? > > Just telling them you did is at least as effective as anything else. Anyone who knows enough to know that you're lying knows why it's impossible. From arkanes at gmail.com Fri Dec 21 17:06:39 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 21 Dec 2007 16:06:39 -0600 Subject: mac dashboad In-Reply-To: <4aWdnRg9NK_KsvHanZ2dnUVZ_rfinZ2d@comcast.com> References: <4aWdnRg9NK_KsvHanZ2dnUVZ_rfinZ2d@comcast.com> Message-ID: <4866bea60712211406i46cec0b0m81899a5a734d2f4f@mail.gmail.com> On Dec 21, 2007 3:25 PM, Carl K wrote: > ianar? wrote: > > On Dec 21, 12:37 pm, Carl K wrote: > >> How do I hang an app off the mac dashboard? > >> > >> The goal is a python version of Weatherbug. > >> > >> something like: > >> read xml data from a URL, > >> display some numbers, > >> mouse over shows more details > >> > >> Carl K > > > > What is the dashboard - is it anything like the taskbar in windows/ > > Gnome? If it is, take a look at this: > > > > http://www.wxwidgets.org/manuals/2.6.3/wx_wxtaskbaricon.html > > Yes. But I don't want to rely on wx - trying to use just native mac python > (whatever they ship with) > Dashboard widgets are written using HTML and Javascript. They are rendered by a WebKit instance which, as far as I know, has no mechanism for Python scripting. Unless it does, you can't write a widget in Python, and even so you wouldn't use wx (or any other GUI toolkit) to do so - your display medium is HTML and the Canvas object. There's lots of articles on developer.apple.com about writing Dashboard widgets. From pict100 at gmail.com Thu Dec 13 07:35:58 2007 From: pict100 at gmail.com (DarkBlue) Date: Thu, 13 Dec 2007 04:35:58 -0800 (PST) Subject: kniterbasdb and datetime References: Message-ID: <17e6d6f4-7d8e-46c4-95ef-0afd19741b37@i12g2000prf.googlegroups.com> On Dec 13, 7:45 pm, Laszlo Nagy wrote: > Hi All, > > I connected to a FireBird 1.5 database this way: > > import kinterbasdb > kinterbasdb.init(type_conv=200) # Seehttp://kinterbasdb.sourceforge.net/dist_docs/usage.html#faq_fep_is_mx... > > Then I try to update the database: > > sql = "UPDATE TABLE1 SET DATEFIELD=? where ID = ?" > params=[datetime.date(2007,11,01),2341] > cursor.execute(sql,params) > > I get this error: > > kinterbasdb.ProgrammingError: (-413, 'isc_dsql_execute: \n conversion > error from string "2007-11-01"') > > What is wrong here? > > Thanks, > > Laszlo Kinterbasdb probably expects the format looking like month/day/year rather than year-month-day I have an old pythoncard app where there was the same issue when picking a date using the wx.calendar widget, Rearranging the format solved the problem. here is the relevant code snippet ,maybe it gives you the idea: def on_doCalDate_command(self,event): # this the way to get a wx.calendar date into a # format suitable for kinterbasdb D=[] MYDATE=str(self.components.Calendar1.date) SPLITDATE=MYDATE.split('-') for data in SPLITDATE: D.append(data) YR=D[0] MO=D[1] DY=D[2] JOBDATE=MO+"/"+DY+"/"+YR DB From fredrik at pythonware.com Thu Dec 27 10:21:48 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 27 Dec 2007 16:21:48 +0100 Subject: Bug in htmlentitydefs.py with Python 3.0? In-Reply-To: <4773B1AA.8060902@v.loewis.de> References: <803d10b9-01f0-4a1f-bc6a-6e12f17c308b@v32g2000hsa.googlegroups.com> <4772e404$0$15853$9b622d9e@news.freenet.de> <4773B1AA.8060902@v.loewis.de> Message-ID: Martin v. L?wis wrote: >> entity_map = htmlentitydefs.entitydefs.copy() >> for name, entity in entity_map.items(): >> if len(entity) != 1: >> entity_map[name] = unichr(int(entity[2:-1])) >> >> (entitydefs is pretty unusable as it is, but it was added to Python >> before Python got Unicode strings, and changing it would break ancient >> code...) > > I would not write it this way, but as > > for name,codepoint in htmlentitydefs.name2codepoint: > entity_map[name] = unichr(codepoint) has dictionary iteration changed in 3.0? if not, your code doesn't quite work. and even if you fix that, it doesn't work for all Python versions that ET works for... From gagsl-py2 at yahoo.com.ar Mon Dec 3 19:02:27 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Dec 2007 21:02:27 -0300 Subject: Delete a instance passed by reference into a method References: <855405.74475.qm@web90502.mail.mud.yahoo.com> Message-ID: En Mon, 03 Dec 2007 19:53:20 -0300, sccs cscs escribi?: > I am very surprising by the Python interpreter behavior : see code > I initialize a 'A' and a 'B', and i give a B instance reference to the > instance A in 'm1' method. I can modify (IN/OUT mode) the 'i' > attribute ( aB.i = 10 ) , BUT I CANNOT DELETE "aB" into the fonction > m1 ! the code " del aB " or " aB= None" has no effect. 'aB' still > exists when m1() is finsihed! WHY ? How can i do that? First, read this > class A(object): > def __init__(self): > pass > def m1 (self, aB ): > aB.i = 10 > del aB > print "no more B" > class B(object): > def __init__(self,i): > self.i = i > def __del__(self): > print "delete B" > > aA = A () > aB = B ( i = 6) > > unA.m1 (aB ) > print str( aB .i ) #---> Display 10, aB is not destroy ! The "del" statement does NOT delete the object, it only removes the name from the current namespace (and doing so, it decrements the object's reference count by one). If that was the last reference to the object, it becomes a candidate for being garbage collected later. __del__ is not used too much. If you want to ensure resource deallocation, use either a try/finally block or a with statement: f = open('filename'): try for line in f: do_something_with(line) finally f.close() Another alternative, Python 2.5 and up: from __future__ import with_statement with open('filename') as f: for line in f: do_something_with(line) # there is an implicit f.close() here If you want to use __del__ for another purpose, please describe your use case (what you want to achieve, not how you think you should implement it). -- Gabriel Genellina From python at rcn.com Sat Dec 29 15:12:30 2007 From: python at rcn.com (Raymond Hettinger) Date: Sat, 29 Dec 2007 12:12:30 -0800 (PST) Subject: getting n items at a time from a generator References: <5657aa68-cbc4-4285-86e8-91ddd317260d@q77g2000hsh.googlegroups.com> <05e5f3ef-9930-4ad5-af88-2f08594568aa@j20g2000hsi.googlegroups.com> Message-ID: <02406011-8f48-4a70-aa1b-5e9bd0ffb075@e23g2000prf.googlegroups.com> > > Also consider this solution from O'Reilly's Python Cookbook (2nd Ed.) p705 > > > ? ? def chop(iterable, length=2): > > ? ? ? ? return izip(*(iter(iterable),) * length) > > However, chop ignores the remainder of the data in the example. There is a recipe in the itertools docs which handles the odd-length data at the end: def grouper(n, iterable, padvalue=None): "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')" return izip(*[chain(iterable, repeat(padvalue, n-1))]*n) Raymond From mark.english at rbccm.com Tue Dec 4 05:36:30 2007 From: mark.english at rbccm.com (MarkE) Date: Tue, 4 Dec 2007 02:36:30 -0800 (PST) Subject: "Python" is not a good name, should rename to "Athon" References: <47546949$0$31456$426a74cc@news.free.fr> Message-ID: <18d696f0-130e-4b8e-8b8c-dce5af401e44@x69g2000hsx.googlegroups.com> Ithon From jstroud at mbi.ucla.edu Thu Dec 20 17:29:35 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 20 Dec 2007 14:29:35 -0800 Subject: Why does __builtins__ mean different things... Message-ID: Hello all, Say I have the following module # amodule.py print __builtins__ # end of module Then I have the following little helper script: # helper.py import amodule # end of helper script Now, I do this at the command line: python amodule.py And I get the following output: Which is good. Now, I do this: python helper.py and I get the following output: {'IndexError': , 'all;: ... [etc] I.e.: __builtins__ is a dict when referenced in an imported module, but in *the exact same code*, when executed as a script, it becomes a module! Is this a bug? In other words, what is the good of this? For the purposes of argument, the bad of this is the behavior above. I'm guessing its a bug. James From stargaming at gmail.com Mon Dec 10 14:11:00 2007 From: stargaming at gmail.com (Stargaming) Date: 10 Dec 2007 19:11:00 GMT Subject: Job Offer: Python Ninja or Pirate! References: Message-ID: <475d8f43$0$31216$9b622d9e@news.freenet.de> On Mon, 10 Dec 2007 16:10:16 +0200, Nikos Vergas wrote: [snip] >> Problem: In the dynamic language of your choice, write a short program >> that will: >> 1. define a list of the following user ids 42346, 77290, 729 (you can >> hardcode these, but it should >> still work with more or less ids) >> 2. retrieve an xml document related to each user at this url "http:// >> api.etsy.com/feeds/xml_user_details.php?id=" >> 3. retrieve the data contained in the city element from each xml >> document >> 4. keep a running total of how many users are found in each city 5. >> display the total count of users living in each city [snip] > > i wanted to make it a one liner, but i had to import modules :( > > import sys, xml, urllib > > dummy = [sys.stdout.write(city + ': ' + str(num) + '\n') for city, num > in set([[(a, o.count(a)) for a in p] for o, p in [2*tuple([[city for > city in > ((xml.dom.minidom.parseString(urllib.urlopen('http://api.etsy.com/feeds/ xml_user_details.php?id=' > + str(id)).read()).getElementsByTagName('city')[0].childNodes + [(lambda > t: (setattr(t, 'data', 'no city'), > t))(xml.dom.minidom.Text())[1]])[0].data.lower().replace(' ', ' ') for > id in [71234, 71234, 71234, 71234, 71234, 71234, 42792])]])]][0])] I suggest `__import__` in such cases. Even though I do not qualify for the job, I came up with this () code (modified list values for demonstration, mixed together from previous post and original task): print '\n'.join('%s: %d'%(x,len(list(y))) for x,y in __import__ ('itertools').groupby(sorted(__import__('xml').dom.minidom.parse (__import__('urllib').urlopen('http://api.etsy.com/feeds/ xml_user_details.php?id=%d'%i)).getElementsByTagName('city') [0].lastChild.data.title() for i in (71234, 729, 42346, 77290, 729, 729)))) I still find this rather readable, though, and there is no bad side- effect magic! :-) Output should be: | Chicago: 3 | Fort Lauderdale: 1 | Jersey City And South Florida: 1 | New York: 1 Cheers, From a24061 at ducksburg.com Tue Dec 11 15:04:23 2007 From: a24061 at ducksburg.com (Adam Funk) Date: Tue, 11 Dec 2007 20:04:23 +0000 Subject: Is a "real" C-Python possible? References: Message-ID: <737335-d7j.ln1@news.ducksburg.com> On 2007-12-10, sturlamolden wrote: > We have seen several examples that 'dynamic' and 'interpreted' > languages can be quite efficient: There is an implementation of Common > Lisp - CMUCL - that can compete with Fortran in efficiency for > numerical computing. There are also versions of Lisp than can compete > with the latest versions of JIT-compiled Java, e.g. SBCL and Allegro. > As it happens, SBCL and CMUCL is mostly implemented in Lisp. The issue > of speed for a language like Python has a lot to do with the quality > of the implementation. What really makes CMUCL shine is the compiler > that emits efficient native code on the fly. If it is possible to make > a very fast Lisp, it should be possible to make a very fast Python as > well. I remember people complaining 10 years ago that 'Lisp is so > slow'. A huge effort has been put into making Lisp efficient enough > for AI. I hope Python some day will gain a little from that effort as > well. I've been told that Torbj?rn Lager's implementation of the Brill tagger in Prolog is remarkably fast, but that it uses some counter-intuitive arrangements of the predicate and argument structures in order to take advantage of the way Prolog databases are indexed. From gherron at islandtraining.com Fri Dec 14 10:48:30 2007 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 14 Dec 2007 07:48:30 -0800 Subject: simple string formatting question In-Reply-To: References: Message-ID: <4762A5CE.7080709@islandtraining.com> Neal Becker wrote: > I have a list of strings (sys.argv actually). I want to print them as a > space-delimited string (actually, the same way they went into the command > line, so I can cut and paste) > > So if I run my program like: > ./my_prog a b c d > > I want it to print: > > './my_prog' 'a' 'b' 'c' 'd' > > Just print sys.argv will almost work, but it's comma-delimited. > > There must be some clever way to do this. Any ideas? > > Use repr to get the quotes around each output arg, and use join on a space to the the space delimited string. >>> theList = ['./whatever', 'a', 'b', 'c'] >>> print ' '.join([repr(i) for i in theList]) './whatever' 'a' 'b' 'c' Gary Herron From scardig at gmail.com Mon Dec 10 03:20:12 2007 From: scardig at gmail.com (scardig at gmail.com) Date: Mon, 10 Dec 2007 00:20:12 -0800 (PST) Subject: My very first python web app (no framework) References: Message-ID: <8dc8e1c6-7847-419d-b7ea-0e49994506ae@d21g2000prf.googlegroups.com> On 9 Dic, 15:43, scar... at gmail.com wrote: > This is my first Python web pseudo-app: "you give me some data, I give > you func(data)". I'm on a shared host with mod_fastcgi so I installed > a virtual python environment + flup (no middleware now, just wsgi > server). > > ========= dispatch.fcgi ================= > from fcgi import WSGIServer > import sys, cgi, cgitb,os > import myfunctions > > def myapp(environ, start_response): > start_response('200 OK', [('Content-Type', 'text/html')]) > write = [] > write.append (myfunctions.func1(par1,par2)) > write.append (myfunctions.func2(par1,par2)) > # [...] > write.append (myfunctions.funcn(par1,par2)) > return [write] > > if __name__=="__main__": > WSGIServer(myapp).run() > ==================================== > > ====== myfunctions.py ================== > def func1(a,b): > return a > def func2(a,b): > return b > ==================================== > > Is it the right way to go? Is it safe in a web production > environment ? Is it thread-friendly (since flup is threaded) ? > > tnx Any hint ? From lists at cheimes.de Sun Dec 9 09:21:15 2007 From: lists at cheimes.de (Christian Heimes) Date: Sun, 09 Dec 2007 15:21:15 +0100 Subject: python from any command line? In-Reply-To: References: Message-ID: <475BF9DB.8030205@cheimes.de> waltbrad wrote: > Is there a way to set this so I can also invoke it from any command > line prompt? You can follow Adonis' advice but I'm going a different path on my computer because I've multiple versions of Python installed on my box. I usually put a simple batch file in c:\Windows, e.g. python25.bat @C:\Python25\python.exe %* I can start Python 2.5 with python25 from every directory. Christian From emin.shopper at gmail.com Thu Dec 27 08:52:23 2007 From: emin.shopper at gmail.com (Emin.shopper Martinian.shopper) Date: Thu, 27 Dec 2007 08:52:23 -0500 Subject: parallel processing in standard library Message-ID: <32e43bb70712270552n76d460e8y9d1d2acaa73f829e@mail.gmail.com> Dear Experts, Is there any hope of a parallel processing toolkit being incorporated into the python standard library? I've seen a wide variety of toolkits each with various features and limitations. Unfortunately, each has its own API. For coarse-grained parallelism, I suspect I'd be pretty happy with many of the existing toolkits, but if I'm going to pick one API to learn and program to, I'd rather pick one that I'm confident is going to be supported for a while. So is there any hope of adoption of a parallel processing system into the python standard library? If not, is there any hope of something like the db-api for coarse grained parallelism (i.e, a common API that different toolkits can support)? Thanks, -Emin -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sat Dec 1 21:46:59 2007 From: http (Paul Rubin) Date: 01 Dec 2007 18:46:59 -0800 Subject: [OT] minimalist web server References: Message-ID: <7xy7cdke3g.fsf@ruckus.brouhaha.com> "Daniel Fetchinson" writes: > I'm looking for the most minimalist web server ever that does nothing > else than return a fixed static page for every request. Regardless of > what the request is, it just needs to be an HTTP request to port 80, > the web server should return always the same html document. What would > be the best choice for this? The goal is of course to minimize system > resources in terms of memory, cpu, etc, etc. If you're running linux, maybe you want tux. publicfile isn't exactly what you describe, but its description might be of some interest: http://cr.yp.to/publicfile.html From eric.promislow at gmail.com Wed Dec 12 20:34:02 2007 From: eric.promislow at gmail.com (Eric Promislow) Date: Wed, 12 Dec 2007 17:34:02 -0800 (PST) Subject: Vista + Rails 2.0 upgrade => subprocess hangs Message-ID: <13f1941e-7a7d-4be4-92cf-fcec53874b73@d4g2000prg.googlegroups.com> Here's a small Python program I use to grab the output from rake: ===== from subprocess import Popen, PIPE p = Popen(args='c:\\ruby\\bin\\ruby.exe c:\\ruby\\bin\\rake -T', cwd=u'c:\\Users\\ericp\\testing\\file07', shell=True, stdin=None, stderr=PIPE, stdout=PIPE, creationflags=0x8000000 ); p.wait() data = p.stdout.read() print data ===== This is on Windows Vista. With Rails 1.2.6 there was no problem. After upgrading to Rails 2.0.1, the program now hangs at the call to the wait() command. If I manually kill the ruby.exe process, I get some of the expected output, but not all of it. I can run the above command from the command-line with no problem. The rake code that Ruby loads did change moving from 1.2.6 to 2.0.1, but subprocess should run the command to completion. I'm not sure what happens yet on XP, or other platforms. I'd like to get this working on Vista, though. Any ideas. Thanks, Eric From arcphi at gmail.com Sat Dec 22 17:39:15 2007 From: arcphi at gmail.com (Jervis Liang) Date: Sat, 22 Dec 2007 14:39:15 -0800 (PST) Subject: 5 queens References: <9639f80c-5722-40c6-bd7b-b727d0a7804e@n20g2000hsh.googlegroups.com> Message-ID: On Dec 22, 2:36 pm, cf29 wrote: > The goal is to control all the chess board with five queens that do > not attack each other. I found "manually" many solutions to this > problem (184 until now) How did you find 184 solutions? Wolfram says there are 91 distinct solutions for 5-queens on an 8x8 board with no two queens attacking each other. http://mathworld.wolfram.com/QueensProblem.html From ilias at lazaridis.com Mon Dec 17 22:52:07 2007 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Mon, 17 Dec 2007 19:52:07 -0800 (PST) Subject: WikiInclude on 0.11 - Noah Kantrowitz blocks bug-fix References: <804f9639-6715-47d6-927d-797bfda0a9b8@s8g2000prg.googlegroups.com> Message-ID: <78f21c31-0f30-42f8-bd9a-637ca8e2f0eb@i72g2000hsd.googlegroups.com> On Dec 18, 4:23 am, Ilias Lazaridis wrote: > Essence: > > * Deletion of valid defect reports on trac community resources UPDATE: Instead of fixing the "WikiInclude" in the repo (or at least leave the ticket open, thus a developer can do it), Mr. Noah Kantrowitz goes his very special way (hint: his nick "coderanger") to suggest to use the "IncludeMacro": "This plugin uses the older style trac_plugin.txt file. If you need something more 0.11 compatible, try the IncludeMacro." http://trac-hacks.org/ticket/2294#comment:1 This is of course completely nonsense. I don't want to use the complex and buggy "IncludeMacro". The "WikiInclude" can be corrected with just one line. But ok, let's take a at Mr. Noah Kantrowitz creation, the "IncludeMacro". Does it work with 0.11? He does not know, thus he asks: "What about the current version doesn't work in 0.11?" http://trac-hacks.org/ticket/2310#comment:3 who received this question? A user, which has provided a 0.11 implementation of the plugin: " * summary changed from [patch] 0.11 patch to 0.11 version of IncludeMacro. Well, there's certainly no need to get snippy over semantics ;) There wasn't a version of IncludeMacro for 0.11, so I created one in the hopes that other Trac admins might find it useful -- humblest apologies for erroneously referring to my submission as a "patch". Having said that, if you feel so inclined as to review my version, then that would be superb, as I'm sure potential future users would feel much better if my contribution had your blessing and/or fixes. " http://trac-hacks.org/ticket/2310#comment:2 Other tickets remain completely unprocessed, although they give an answer to his question "does it work on 0.11": "The macros.py of Includewikimacro contain : macro = WikiProcessor? (self.env, 'Include') for the rendering of the wiki page. Whereas now with the version 0.11, the function WikiProcessor?() nead a formatter as first argument and not anymore an environment." 08/27/07 05:13:21 changed by sibok at tis***.fr http://trac-hacks.org/ticket/1973 Mr. Noah Kantrowitz does not care about the trac users, otherwise he would update the svn of the WikiInclude macro and the documentation to inform users, instead of violently closing a valid ticket as an invalid one. A few more wild-west CODERANGERS like Noah Kantrowitz can ruine the already very slow progress of the trac-project completely. User comments and user feedback is critical for any open-source project. Engouraging contributions, instead of surpressing them is essential. Trac-Users, please do not accept such a surpressive behaviour - it costs your time. (btw: I am a 0.11dev user, see http://dev.lazaridis.com/base/wiki) . > The "WikiInclude" plugin is not recognised on trac 0.11, thus I took a > look an made a small addition to the setup.py (the entry_point). > > Other users have the same problem, thus I filed a ticket in the "trac- > hacks" community resource. > > Mr. Noah Kantrowitz closed the ticket as "invalid". My comments within > this ticket are deleted, directly in the database, which is the same > as censorship. I've copied the email-notification from my comment > below. [1] > > Please realize: > > * this is a real-live defect, which remains unprocessed, thus more > users run into this trouble. > * My attemps to inform users in the user-threads do not show up in > all threads (moderation on trac-users!!!) > * The "IncludeMacro" is not compatible to the "WikiInclude" macro > * My comments were deleted in a non-trackable way > * Users of the WikiInclude plugin are not informed in any way > > You are may wondering why the trac project fails to produce a stable > 1.0 version since years. The answer is here: > > http://case.lazaridis.com/wiki/TracAudit > > - > > [1] > > #2294: Plugin is not detectd on trac 0.11 (even the 0.11 specific one) > -------------------------------- > +------------------------------------------- > Reporter: il... at lazaridis.com | Owner: yu-ji > Type: defect | Status: reopened > Priority: normal | Component: WikiIncludePlugin > Severity: critical | Resolution: > Keywords: | Release: 0.11 > -------------------------------- > +------------------------------------------- > Changes (by il... at lazaridis.com): > > * status: closed => reopened > * resolution: invalid => > * summary: Missing "entry_point" within setup.py => Plugin is not > detectd on trac 0.11 (even the 0.11 specific > one) > > Comment: > > (Mr. Kantrowitz. This is defenitely a defect, which occoured for > several > users. The provided information helps any user which hits on this > ticket > via a search. I ask you once more to stop with the deletions on this > '''community''' resource). > > The resolution "invalid" is incorrect. > > The problem exists for me '''and other''' users, see e.g.: > > * [http://groups.google.com/group/trac-users/browse_frm/thread/ > de454e7dcf9f0438/d9806ad4a31a14a7 thread 1] > * [http://groups.google.com/group/trac-users/browse_frm/thread/ > 2ccf4b2855a6f242?q=WikiInclude& thread 2] > > I've solved it whilst simply adding the entry point to the setup.py. > > It is ok to point to the more flexible and maintained "IncludeMacro", > but > other people possibly just want to continue to use the simpler > "WikiInclude" one. > > I suggest the maintainer of "WikiInclude" (or another developer) > corrects > the setup.py in the repo, and additionally one should place a note in > the > "WikiInclude" documentation, that there's a more flexible > "IncludeMacro" > available. From ironfroggy at socialserve.com Tue Dec 11 21:03:36 2007 From: ironfroggy at socialserve.com (Calvin Spealman) Date: Tue, 11 Dec 2007 21:03:36 -0500 Subject: replacing built-in exception types In-Reply-To: <475EF868.5090806@pdi.dreamworks.com> References: <475EF868.5090806@pdi.dreamworks.com> Message-ID: <140AE310-26CD-4340-ADC7-994A48B495FF@socialserve.com> Why would you do this? How to do it, if its even possible, is far less important than if you should even attempt it in the first place. On Dec 11, 2007, at 3:51 PM, Nishkar Grover wrote: > > I'm trying to replace a built-in exception type and here's a > simplified > example of what I was hoping to do... > >>>> >>>> import exceptions, __builtin__ >>>> >>>> zeroDivisionError = exceptions.ZeroDivisionError >>>> >>>> class Foo(zeroDivisionError): > ... bar = 'bar' > ... >>>> >>>> exceptions.ZeroDivisionError = Foo >>>> ZeroDivisionError = Foo >>>> __builtin__.ZeroDivisionError = Foo >>>> >>>> try: > ... raise ZeroDivisionError > ... except ZeroDivisionError, e: > ... print e.bar > ... > bar >>>> >>>> try: > ... 1/0 > ... except ZeroDivisionError, e: > ... print e.bar > ... > Traceback (most recent call last): > File "", line 2, in ? > ZeroDivisionError: integer division or modulo by zero >>>> > > Notice that I get my customized exception type when I explicitly raise > ZeroDivisionError but not when that is implicitly raised by 1/0. It > seems like I have to replace that exception type at some lower level, > but I'm not sure how/where. Does anyone know of a way to do this? > > - Nishkar > > -- > http://mail.python.org/mailman/listinfo/python-list From rodmena.com at gmail.com Mon Dec 10 02:15:17 2007 From: rodmena.com at gmail.com (farsheed) Date: Sun, 9 Dec 2007 23:15:17 -0800 (PST) Subject: Best way to protect my new commercial software. Message-ID: <8c9a903b-7f57-4a90-883a-5bb1f06fedf6@e6g2000prf.googlegroups.com> I wrote a software and I want to protect it so can not be cracked easily. I wrote it in python and compile it using py2exe. what is the best way in your opinion? From steve at REMOVE-THIS-cybersource.com.au Fri Dec 7 16:41:54 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Dec 2007 21:41:54 -0000 Subject: Dictionary instantiation? References: <06ba5d69-0623-4133-a8cd-89c2b48efbf5@v4g2000hsf.googlegroups.com> <475926c8$0$23994$426a34cc@news.free.fr> Message-ID: <13ljfh2hgatj5ab@corp.supernews.com> On Fri, 07 Dec 2007 11:56:14 +0100, Bruno Desthuilliers wrote: > Also, modifying a sequence in place while iterating over it is a *very* > bad idea. That's somewhat of an exaggeration, surely. Some sorts of modifications are more error-prone than others, and deserves your warning e.g. inserting or deleting items (as the OP was doing). But modifying the items themselves isn't risky at all. E.g. instead of this: L = [] for x in xrange(1000000): L.append(result_of_some_calculation(x)) a perfectly reasonable optimization technique for large lists is: L = [None]*1000000 for i,x in enumerate(L): L[i] = result_of_some_calculation(x) The second avoids needing to re-size the list repeatedly, which is quite slow. -- Steven From ptmcg at austin.rr.com Tue Dec 11 09:23:43 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 11 Dec 2007 06:23:43 -0800 (PST) Subject: Counter-spam: Change the subject References: Message-ID: <1b648cf1-ee24-4132-9c15-b293d12907cf@i29g2000prf.googlegroups.com> On Dec 11, 5:59 am, dfg wrote: > Breakthrough - How To Turn Your Dull Website into Money Making Website I was surprised at how effectively the spam posting the other day, "Jesus in the Quran" was masked and defused by a reply titled "J in the Q". It seems this might be a simple tool for cleaning up some of the spam posting clutter, just by "changing the subject" (double entendre not intentional, it just happened). Instead of these breathless, shouting subjects full of '#' signs and capital letters, we just acronymify them to "H T T Y D W into M M W" by posting a reply and editing the subject. Could this work? It seems too simple. -- Paul From gardner at networknow.org Thu Dec 20 18:28:56 2007 From: gardner at networknow.org (Gardner Pomper) Date: Thu, 20 Dec 2007 18:28:56 -0500 Subject: How to spider through a secure site? Message-ID: <42d22dbf0712201528u5048bbbu9046a88ea300e6f1@mail.gmail.com> Hi, My daughter's school just put up an "Infinite Campus" website, which requires a login and does everything through https. I can find examples of how to spider a regular web site with python, but I can't figure out how to deal with the ssl certificate and how to supply name and password. I have tried google, but I must not know the right terms. There is a book, called Spidering Hacks, that seems to imply that perl's LWP module will allow it, but i don't know enough about perl to determine if there is a python equivalent. Thanks for any tips, - Gardner -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Sat Dec 15 03:10:42 2007 From: timr at probo.com (Tim Roberts) Date: Sat, 15 Dec 2007 08:10:42 GMT Subject: Changing argument value References: <927621cd-0640-477d-9400-c0f863c1bca3@e6g2000prf.googlegroups.com> <4761a9c4$0$28240$426a74cc@news.free.fr> <47629c70$0$4006$9b622d9e@news.freenet.de> Message-ID: Stargaming wrote: > >Even though you have the assignment operator *in both cases*, it does >**not** issue the same thing. > >As Bruno pointed out, in the first case ``y = [3,4]`` it is *rebinding* >the name `y`. There have been two good replies to this, but I would like to present the "mental model" I use to understand this. The term "rebinding" is not one that folks encounter very often, and so doesn't bring up an image. In Python, you have objects (which do not have names), and you have names. Names get "bound" to objects. For example: x = [1,2,3] This statement creates an anonymous object out in space. The object is a list, containing three numbers. It also creates a name "x" in a namespace, and binds it to that anonymous list. Now, let's say I do this: x = [1,2,6] This creates a NEW anonymous object out in space -- a list containing three numbers -- and binds the name "x" to it. For a short time, we now have TWO three-element lists in our object space. The old list ([1,2,3]) now has nothing bound to it, so it will eventually be cleaned up by the garbage collector. x is now bound to an entirely different object. But, if I did this INSTEAD of that: x[2] = 6 This does NOT create a new list. Instead, it changes one element in that first anonymous list object we created. x is still bound to that same list. So, consider your example: def fooA(y): y = [3,4] return y def fooB(y): y[0] = 3 y[1] = 4 return y x = [1,2] fooA(x) "x" is just a name in the global namespace. We don't really pass "x" to the function. Instead, we pass that anonymous list object with two-elements. As the function is called, that list gets bound to the name "y" inside fooA. This list now has TWO names bound to it, "x" in the global namespace, and "y" in the fooA function. When you execute y = [3,4] you are creating a brand-new list with two elements, and bunding that to the local name "y". The old list STILL EXISTS, and since it is still bound to the global "x", it won't be cleaned up. When the function returns, the name "y" goes away, so it gets unbound. Since you don't store the function result anywhere, the [3,4] list now has no names bound to it, and will get cleaned up. fooB(x) Like before, this is passing the two-element [1,2] list into fooB, where it gets bound to "y" inside fooB. Again, it has two names bound to it. Then, when you do y[0] = 3 you are changing an element in that list. Since that same list is bound to both the global "x" and the local "y", the effect of the changes WILL be seen when you exit from function. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From martin at v.loewis.de Sat Dec 8 10:25:44 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 08 Dec 2007 16:25:44 +0100 Subject: distutils & OS X universal binaries In-Reply-To: References: <475AA774.7020904@jessikat.plus.net> Message-ID: <475AB778.8050801@v.loewis.de> >> A user reports problems with one of our extensions when running the >> intel compiled extension on ppc and vice versa. He is building the >> extension as a universal binary. Although the intel compiled version >> runs fine it displays a known bug when run on a ppc. > > Have you reported the problem at http://bugs.python.org/? A minimal > example could help us to fix the problem. At first, I also thought that Robin suggested that there is a problem with Python. Upon re-reading, I now believe he rather sees the bug in the reportlabs code, and is asking for an approach to solve it there. Regards, Martin From sturlamolden at yahoo.no Tue Dec 11 17:16:59 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 11 Dec 2007 14:16:59 -0800 (PST) Subject: Is a "real" C-Python possible? References: <475EE42C.5060308@animats.com> Message-ID: <6c73d2e1-1afb-469b-9132-671e03ffe741@f3g2000hsg.googlegroups.com> On 11 Des, 20:25, John Nagle wrote: > Shed Skin effort. Its author writes "Am I the only one seeing the potential > of an implicitly statically typed Python-like-language that runs at > practically the same speed as C++?" Don't forget about Pyrex and PyPy's RPython. By the way, we don't need a hotspot JIT compiler. Lisp has a compiler invoked by the programmer. We could include optional static typing in Python, and have an optional static optimizing native compiler for selected portions of code. That would be easier to implement in the short run, with JIT-capabilities added later. Pyrex, ShedSkin or RPython are all good starting points. From rpmuller at gmail.com Sun Dec 9 09:20:58 2007 From: rpmuller at gmail.com (Rick Muller) Date: Sun, 9 Dec 2007 06:20:58 -0800 (PST) Subject: Advice for editing xml file using ElementTree and wxPython References: <7e0d9dbf-6de1-4c46-a8e9-0ade7531b0aa@e25g2000prg.googlegroups.com> <5fef1874-9589-4aed-8986-a5e3ba6eb04d@b40g2000prf.googlegroups.com> Message-ID: <9fad8c68-257b-4e41-8d00-c2dddcbd58c1@b40g2000prf.googlegroups.com> On Dec 8, 11:57 pm, Waldemar Osuch wrote: > On Dec 8, 8:35 pm, Rick Muller wrote: > > > > > I'm a computational chemist who frequently dabbles in Python. A > > collaborator sent me a huge XML file that at one point was evidently > > modified by a now defunct java application. A sample of this file > > looks something like: > > > > > Test > > > > File Name > > fileName > > Name of the input file > > water > > > > > > Number of Atoms > > natoms > > Number of atoms in the molecule > > 3 > > > > > > > > > > > Seems like this is something that's probably pretty common, modifying > > a data structure using a gui, so I'm hoping that someone has thought > > about this and has some good advice about best practices here. > > The trick is to keep a reference to the actual ElementTree objects > as you build your TreeCtrl. Ability to store arbitrary Python object > in the TreeCtrl Item makes it easy. In an event handler modify the > original element and you are done. Do not forget to save when > closing. > > If the XML file is very large you may have performance issues since > the whole parsed tree is kept in memory. Luckily the ElementTree > representation is lean. > > A sample below shows the approach. It is very basic but I hope it > conveys the idea. Please note that edits to the actual tags are > ignored. > > ------------------------------------------------------------------- > import wx > import xml.etree.cElementTree as ET > > class MainFrame(wx.Frame): > def __init__(self, fpath): > wx.Frame.__init__(self, None) > self.fpath = fpath > self.xml = ET.parse(fpath) > self.tree = wx.TreeCtrl(self, > style=wx.TR_HAS_BUTTONS|wx.TR_EDIT_LABELS) > root = self.fillmeup() > self.tree.Expand(root) > > self.Bind(wx.EVT_CLOSE, self.OnClose) > self.Bind(wx.EVT_TREE_END_LABEL_EDIT, self.OnEdit) > > def fillmeup(self): > xml = self.xml.getroot() > tree = self.tree > root = tree.AddRoot(xml.tag) > def add(parent, elem): > for e in elem: > item = tree.AppendItem(parent, e.tag, data=None) > text = e.text.strip() > if text: > val = tree.AppendItem(item, text) > tree.SetPyData(val, e) > add(item, e) > add(root, xml) > return root > > def OnEdit(self, evt): > elm = self.tree.GetPyData(evt.Item) > if elm is not None: > elm.text = evt.Label > > def OnClose(self, evt): > self.xml.write(self.fpath) > self.Destroy() > > if __name__=='__main__': > app = wx.App(False) > frame = MainFrame('sample.xml') > frame.Show() > app.MainLoop() This was exactly what I was looking for! Thanks very much. Rick From L33tminion at gmail.com Wed Dec 19 11:46:44 2007 From: L33tminion at gmail.com (Sam) Date: Wed, 19 Dec 2007 08:46:44 -0800 (PST) Subject: Allowing Arbitrary Indentation in Python References: <5169ce7e-a092-47fc-b121-cd86e4916aa5@p69g2000hsa.googlegroups.com> <003ad67e-7ac4-4558-9a70-497c704b21cd@e4g2000hsg.googlegroups.com> Message-ID: On Dec 19, 11:09 am, gDog wrote: > Hi, Sam- > > I'm not wanting to start a flame war, either, but may I ask why does > your friend want to do that? I'm always intrigued by the folks who > object to the indentation rules in Python, even though I've always > tried to keep consistent indentation in all the languages I've used > (and I've been at this since the 1980's). Even my Perl coding friends > tend to insist on indents being aligned. I'm just curious, that's > all. > > Thanks, > --greg His comments on the subject are in the LiveJournal comment I linked to in my original post. I think it's mostly an idiosyncratic thing; he's used to laying out GUI elements in a hierarchy using tabs (in some language that allows arbitrary tabs) and now that he's experimenting with the (new?) Python API for the same toolkit, he wishes he could use the same coding style. From dmitrey.kroshko at scipy.org Tue Dec 18 02:38:34 2007 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Mon, 17 Dec 2007 23:38:34 -0800 (PST) Subject: OpenOpt install References: <65e61980-a21b-4ba2-81f2-a2c23ccb43f2@1g2000hsl.googlegroups.com> <89ecef85-b670-40ab-bc8a-74271ff4cff0@y5g2000hsf.googlegroups.com> Message-ID: When earlier OpenOpt versions had been installed there were no compiled pyc-files (in destination directory). I called to mailing list but no obvious receipt had been achieved. Matthieu had done some changes but it yielded other mistakes (no some py-files detected or kind of), so I had removed those changes and write my own, for to have OO py-files being compiled when installed, because next time when they will be run user may not have root permissions, so he will recompile source files each time OO starts. On Dec 17, 10:27 pm, Robert Kern wrote: > dmitrey wrote: > > Use > > python setup.py install > > People should be able to run the distutils commands independently. > > What are you trying to achieve with this block of code that follows the setup() > call? > > new_name = 'tmp55' > os.rename('scikits', new_name) > newPath = [] > for directory in sys.path: > if not 'scikits' in directory: newPath.append(directory)# something > wrong with list.remove() > sys.path = newPath > import scikits > reload(scikits) > Path = scikits.__path__[0] > NewPath = os.path.join(Path, 'openopt') > rmtree(NewPath, True) # True means ignore errors > copytree(os.path.join(os.path.curdir, new_name, 'openopt'), NewPath) > NewPath = Path > compileall.compile_dir(NewPath) > > os.rename(new_name, 'scikits') > > This just looks like a really bad idea. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco From lists at cheimes.de Wed Dec 19 02:02:32 2007 From: lists at cheimes.de (Christian Heimes) Date: Wed, 19 Dec 2007 08:02:32 +0100 Subject: More than one interpreter per process? In-Reply-To: References: Message-ID: Roger Binns wrote: > sturlamolden wrote: >> If one can have more than one interpreter in a single process, > > You can. Have a look at mod_python and mod_wsgi which does exactly > this. But extension modules that use the simplified GIL api don't work > with them (well, if at all). No, you can't. Sub-interpreters share a single GIL and other state. Why don't you run multiple processes? It's on of the oldest and best working ways use the full potential of your system. Lot's of Unix servers like postfix, qmail, apache (with some workers) et al. use processes. Christian From MartinRinehart at gmail.com Sat Dec 8 13:17:23 2007 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Sat, 8 Dec 2007 10:17:23 -0800 (PST) Subject: Newbie edit/compile/run cycle question Message-ID: <1f995159-fc02-4cd1-aa99-7f8500eeaeec@b1g2000pra.googlegroups.com> I'm a java guy used to the effective edit/run cycle you get with a good IDE. Today I'm writing my first Python, but can't seem to find the way to use Python's inherent edit/run cycle. I edit my source, import it into Python, run it. Fine. Then I edit again, but the next import doesn't notice that a new compile is needed. I'm making a little progress (very little) by exiting/ reentering Python after each edit. Ugh. What don't I know that I should know to just edit/run, preferably at the tap of a function key? From devicerandom at gmail.com Tue Dec 11 18:35:11 2007 From: devicerandom at gmail.com (massimo s.) Date: Tue, 11 Dec 2007 15:35:11 -0800 (PST) Subject: Is anyone happy with csv module? References: <15ab759b-0aec-45dd-88b9-c446c2b7d299@e10g2000prf.googlegroups.com> <88102e1b-c54a-4216-a71e-017a0a243aeb@b40g2000prf.googlegroups.com> <516581dc-a2d7-452a-8988-89c381e086e8@r29g2000hsg.googlegroups.com> Message-ID: On 12 Dic, 00:08, "Gabriel Genellina" wrote: > Note that all the above (as any operation involving a whole *column*) > requires reading the whole file in memory. Working by rows, on the other > hand, only requires holding ONE row at a time. For big files this is > significant. > > An example of writing data given in columns: > > id = [1,2,3,4] > name = ['Moe','Larry','Curly','Shemp'] > hair = ['black','red',None,'black'] > writer = csv.writer(...) > writer.writerows(itertools.izip(id, name, hair)) > > I think your problem is not with the csv module, but lack of familiarity > with the Python language itself and how to use it efficiently. Maybe. As stated at the beginning, I am not a professional programmer. I am a scientist using Python at work. It's years I use it and I love it, but I surely miss many nuances. For example, I never ever looked into itertools. I am also not so familiar with iterators. Itertools seem fantastic, and I'll definitely look into them, however I can't but feel it's a bit strange that someone wanting a quick csv parsing/writing has to dig into those apparently unrelated stuff. > > (Btw: who is using csv to read >10**6 lines of data?) > > Me, and many others AFAIK. 1M lines is not so big, btw. It's clear that I am thinking to completely different usages for CSV than what most people in this thread. I use csv to export and import numerical data columns to and from spreadsheets. That's why I found 1M lines a lot. Didn't know csv had other uses, now I see more clearly why the module is as it is. Thanks for your tips, I've learned quite a lot. m. From hat at se-162.se.wtb.tue.nl Mon Dec 10 05:56:54 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Mon, 10 Dec 2007 11:56:54 +0100 Subject: My very first python web app (no framework) References: <8dc8e1c6-7847-419d-b7ea-0e49994506ae@d21g2000prf.googlegroups.com> Message-ID: On 2007-12-10, scardig at gmail.com wrote: > On 9 Dic, 15:43, scar... at gmail.com wrote: >> Is it the right way to go? Is it safe in a web production >> environment ? Is it thread-friendly (since flup is threaded) ? >> >> tnx > > Any hint ? If you as author are asking, my bet is on "no" for safety. Albert From jwwest at gmail.com Thu Dec 20 15:21:02 2007 From: jwwest at gmail.com (jwwest) Date: Thu, 20 Dec 2007 12:21:02 -0800 (PST) Subject: Regex Matching on Readline() References: <624c98d6-383e-4e19-af96-c6b2a0efa950@r60g2000hsc.googlegroups.com> Message-ID: <302d7567-1db7-4277-a45a-bd99ef4972fa@b1g2000pra.googlegroups.com> On Dec 20, 2:13 pm, John Machin wrote: > On Dec 21, 6:50 am, jwwest wrote: > > > > > Anyone have any trouble pattern matching on lines returned by > > readline? Here's an example: > > > string = "Accounting - General" > > pat = ".+\s-" > > > Should match on "Accounting -". However, if I read that string in from > > a file it will not match. In fact, I can't get anything to match > > except ".*". > > > I'm almost certain that it has something to do with the characters > > that python returns from readline(). If I have this in a file: > > > Accounting - General > > > And do a: > > > line = f.readline() > > print line > > > I get: > > > A c c o u n t i n g - G e n e r a l > > > Not sure why, I'm a nub at Python so any help is appreciated. They > > look like spaces to me, but aren't (I've tried matching on spacs too) > > > - james > > To find out what the pseudo-spaces are, do this: > > print repr(open("the_file", "rb").read()[:100]) > > and show us (copy/paste) what you get. > > Also, tell us what platform you are running Python on, and how the > file was created (by what software, on what platform). Here's my output: 'A\x00c\x00c\x00o\x00u\x00n\x00t\x00i\x00n\x00g\x00 \x00-\x00 \x00G \x00e\x00n\x00e\x00r\x00a\x00l\x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00' I'm running Python on Windows. The file was initially created as output from SQL Management Studio. I've re-saved it using TextPad which tells me it's Unicode and PC formatted. From Mark.McGirr at gov.bc.ca Thu Dec 20 11:22:17 2007 From: Mark.McGirr at gov.bc.ca (McGirr, Mark A ILMB:EX) Date: Thu, 20 Dec 2007 08:22:17 -0800 Subject: POpen - Wait For Process To Complete Message-ID: <440F5CA85C13D04DAD79C5274E75BC83A056BC@crowd.idir.bcgov> Rob. Did you ever figure this out. It's driving me crazy too. ________________________________________________ Mark McGirr Land Information Specialist Regional Client Services Division Integrated Land Management Bureau Ministry of Agriculture and Lands 201 - 172 North Second Avenue Williams Lake, BC V2G 1T4 phone 250-398-4719 fax 250-398-4836 mark.mcgirr at gov.bc.ca From gagsl-py2 at yahoo.com.ar Wed Dec 19 12:13:41 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Dec 2007 14:13:41 -0300 Subject: operator module isSequenceType with builtin set produces False References: <15e46d41-7534-4d9a-8939-bb3a8bf11ca0@e23g2000prf.googlegroups.com> Message-ID: En Wed, 19 Dec 2007 06:28:03 -0300, MarkE escribi?: >> Is there a short Pythonic way to determine whether an object is >> iterable (iteratable ??) that I haven't thought of (getattr(obj, >> '__iter__') ?). Would operator.isIterable() be at all a useful >> addition ? Yes, I think the only way is to try iter(obj) and see if it succeeds (that's basically the same as what you do with getattr, but actually creates the iterator and checks that it's of the right type). > And here I probably meant container (although the url says sequence > when the article meant container, bit like me): > http://docs.python.org/ref/sequence-types.html > "Containers usually are sequences (such as lists or tuples) or > mappings (like dictionaries), but can represent other containers as > well" > > So same question, but perhaps "isContainer()" rather than > "isIterable()" "container" is too generic. Perhaps you can look if it has a __len__ attribute. But anyone could implement a linked list (the common interfase don't fit well with those sequence/mapping methods) and would be hard to deduce whether it is a container or not without further knowledge about it. -- Gabriel Genellina From duncan.booth at invalid.invalid Fri Dec 7 06:59:40 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Dec 2007 11:59:40 GMT Subject: File to dict References: Message-ID: mrkafk at gmail.com wrote: > def lookupdmo(domain): > lines = open('/etc/virtual/domainowners','r').readlines() > lines = [ [y.lstrip().rstrip() for y in x.split(':')] for x in > lines] > lines = [ x for x in lines if len(x) == 2 ] > d = dict() > for line in lines: > d[line[0]]=line[1] > return d[domain] Just some minor points without changing the basis of what you have done here: Don't bother with 'readlines', file objects are directly iterable. Why are you calling both lstrip and rstrip? The strip method strips whitespace from both ends for you. It is usually a good idea with code like this to limit the split method to a single split in case there is more than one colon on the line: i.e. x.split(':',1) When you have a sequence whose elements are sequences with two elements (which is what you have here), you can construct a dict directly from the sequence. But why do you construct a dict from that input data simply to throw it away? If you only want 1 domain from the file just pick it out of the list. If you want to do multiple lookups build the dict once and keep it around. So something like the following (untested code): from __future__ import with_statement def loaddomainowners(domain): with open('/etc/virtual/domainowners','r') as infile: pairs = [ line.split(':',1) for line in infile if ':' in line ] pairs = [ (domain.strip(), owner.strip()) for (domain,owner) in pairs ] return dict(lines) DOMAINOWNERS = loaddomainowners() def lookupdmo(domain): return DOMAINOWNERS[domain] From paul.nospam at rudin.co.uk Thu Dec 13 10:50:00 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Thu, 13 Dec 2007 15:50:00 +0000 Subject: Is Python really a scripting language? References: <009101c83c55$4ee07a00$6501a8c0@aristotle> <2bc2ab76-da7b-43ec-969d-33f77b174a56@e6g2000prf.googlegroups.com> <13m12513p8pfqb4@corp.supernews.com> Message-ID: <87lk7y387r.fsf@rudin.co.uk> Neil Cerutti writes: > On 2007-12-13, Steven D'Aprano wrote: >> I have repeatedly argued in the past that we do ourselves a >> disservice by describing Python as an interpreted language. >> >> Python is compiled. It has a compiler. It even has a built-in >> function "compile". It's just not compiled to *machine code* -- >> but with even machine code often running on a virtual machine >> in the CPU(s), the distinction is far less important now than >> it was when Sun described Java as a compiled language despite >> the lack of JIT compilers. > > When folks say Python is an interpreted language I think they > mean it informally--they just mean you have to run an interpreter > to execute it. *How* it's translated is irrelevent to the > *informal* meaning. > > And I'd further argue that the informal meaning is the only one > that makes any sense. > Many people still talk about lisp as "interpreted" despite the fact that there have been compilers (that compile to machine code) for decades. I'm not sure it's really a property of a language, rather of an implementation. From mail at microcorp.co.za Wed Dec 5 02:54:47 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 5 Dec 2007 09:54:47 +0200 Subject: "Python" is not a good name, should rename to "Athon" References: <47502B0C.3040504@fmed.uba.ar><880dece00712010651j74c4c407ra5623fde62457d1@mail.gmail.com><5rl3mvF14sd6cU1@mid.uni-berlin.de><13lb4pbp7lufd63@corp.supernews.com> Message-ID: <017501c83714$e6434120$03000080@hendrik> "Gabriel Genellina" wrote: >En Tue, 04 Dec 2007 14:49:36 -0300, Dennis Lee Bieber > escribi?: >> How about the cognate: Kulkukan? >You meant Kukulkan. If you got it wrong from "Apocalypto" (Mel Gibson), >well, it's just one of many errors in the film... Either way its no good - sounds too much like Kalkul - Hendrik From dteslenko at gmail.com Thu Dec 20 13:35:55 2007 From: dteslenko at gmail.com (Dmitry Teslenko) Date: Thu, 20 Dec 2007 21:35:55 +0300 Subject: xml-filter with XMLFilterBase() and XMLGenerator() shuffles attributes Message-ID: <91325fec0712201035o4c7f719y73fe1c3353404f01@mail.gmail.com> Hello! I've made a trivial xml filter to modify some attributes on-the-fly: ... from __future__ import with_statement import os import sys from xml import sax from xml.sax import saxutils class ReIdFilter(saxutils.XMLFilterBase): def __init__(self, upstream, downstream): saxutils.XMLFilterBase.__init__(self, upstream) self.__downstream = downstream return def startElement(self, name, attrs): self.__downstream.startElement(name, attrs) return def startElementNS(self, name, qname, attrs): self.__downstream.startElementNS(name, qname, attrs) return def endElement(self, name): self.__downstream.endElement(name) return def endElementNS(self, name, qname): self.__downstream.endElementNS(name, qname) return def processingInstruction(self, target, body): self.__downstream.processingInstruction(target, body) return def comment(self, body): self.__downstream.comment(body) return def characters(self, text): self.__downstream.characters(text) return def ignorableWhitespace(self, ws): self.__downstream.ignorableWhitespace(ws) return ... with open(some_file_path, 'w') as f: parser = sax.make_parser() downstream_handler = saxutils.XMLGenerator(f, 'cp1251') filter_handler = ReIdFilter(parser, downstream_handler) filter_handler.parse(file_path) I want prevent it from shuffling attributes, i.e. preserve original file's attribute order. Is there any ContentHandler.features* responsible for that? From nickjbyrne at gmail.com Tue Dec 4 10:40:40 2007 From: nickjbyrne at gmail.com (Nick) Date: Tue, 4 Dec 2007 07:40:40 -0800 (PST) Subject: Escaping the semicolon? Message-ID: <7dd5d462-b8a3-4260-92b9-3c75cd75995f@x69g2000hsx.googlegroups.com> Hi all, Is this expected behavior? >>> s = '123;abc' >>> s.replace(';', '\;') '123\\;abc' I just wanted a single backslash. I can see why this probably happens but i wondered if it is definitely intentional. Thanks Nick From MartinRinehart at gmail.com Sat Dec 22 07:18:18 2007 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Sat, 22 Dec 2007 04:18:18 -0800 (PST) Subject: How to in Python References: <5b91c387-0a96-466c-a5c7-7d412a9c6796@b1g2000pra.googlegroups.com> <9ce37ee7-b6ad-4d7b-b3b6-b67b3f2f1a7b@e10g2000prf.googlegroups.com> <2be7103b-a119-4762-9d30-ace320b5d63a@j20g2000hsi.googlegroups.com> <9c5b6014-9b86-47dc-b5c3-28ffb5686141@e4g2000hsg.googlegroups.com> Message-ID: Chris Mellon wrote: > You don't seem to be implementing the > lexer in Python I am absolutely implementing my language in Python, a language I have now been writing for two entire weeks. This list has been more than helpful, tolerating numerous newbie questions. From gandalf at shopzeus.com Thu Dec 13 10:13:50 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 13 Dec 2007 16:13:50 +0100 Subject: kniterbasdb and datetime In-Reply-To: <47612A89.1090104@shopzeus.com> References: <17e6d6f4-7d8e-46c4-95ef-0afd19741b37@i12g2000prf.googlegroups.com> <47612A89.1090104@shopzeus.com> Message-ID: <47614C2E.3030707@shopzeus.com> >> Kinterbasdb probably expects the format looking like >> >> month/day/year >> >> rather than >> >> year-month-day >> All right, I tried the month/day/year version: print sql print params cur.execute(sql,params) Results in: Inserting new TTT codes...insert into ttt( ID, TTT, KIHIR ) VALUES ( GEN_ID(G_TTT,1), ?,?) [210227753, '11/1/2007'] Traceback (most recent call last): File "c:\Delphi5_Brinkman\Projects\TTTImport\tttupdate.py", line 131, in cur.execute(sql,params) kinterbasdb.ProgrammingError: (-413, 'isc_dsql_execute: \n conversion error from string "2007-11-01"') You see, I passed '11/1/2007' but the error says "2007-11-01". So what? I also tried this: Inserting new TTT codes...insert into ttt( ID, TTT, KIHIR ) VALUES ( GEN_ID(G_TTT,1), ?, cast( ? as date) ) [210227753, '11/1/2007'] Results in: Traceback (most recent call last): File "c:\Delphi5_Brinkman\Projects\TTTImport\tttupdate.py", line 131, in cur.execute(sql,params) kinterbasdb.ProgrammingError: (-804, 'isc_dsql_prepare: \n Dynamic SQL Error\n SQL error code = -804\n Data type unknown') Right now I cannot see any way to specify a date parameter and as time goes by, it is becoming a biger problem for me. :-( Please help. Laszlo From bdelmee at advalvas._REMOVEME_.be Wed Dec 26 09:46:43 2007 From: bdelmee at advalvas._REMOVEME_.be (=?ISO-8859-1?Q?Bernard_Delm=E9e?=) Date: Wed, 26 Dec 2007 15:46:43 +0100 Subject: missing pydoc gui In-Reply-To: <93d3dd33-e9ae-44ba-b74e-cb222378231c@21g2000hsj.googlegroups.com> References: <2d895dd7-6610-42e0-99fb-de4ab03fc528@l32g2000hse.googlegroups.com> <93d3dd33-e9ae-44ba-b74e-cb222378231c@21g2000hsj.googlegroups.com> Message-ID: FWIW I am using 2.4.4 under debian etch and 2.5.1 under windows XP, and pydoc seems to support the -[pgkw] flags under both versions. When trying -g under debian, I am getting a stack-trace and a message inviting me to install the python-tk package. Does "pydoc -g" provide any feedback on your installation? One nice alternative for python standard doc is the .CHM file provided at python.org. You can use the "xchm" viewer under linux. On 26/12/2007 14:56, JimG wrote: > > Thanks for the suggestion, however, that does not seem to be the > reason since I already have both tk and tkinter. I tried adding tk- > devel but that made no difference. From tlis01 at googlemail.com Fri Dec 14 04:53:07 2007 From: tlis01 at googlemail.com (Tlis) Date: Fri, 14 Dec 2007 01:53:07 -0800 (PST) Subject: reloading modules and isinstance() References: Message-ID: <56f5e3b6-e6f0-4d38-9c13-65304230f87d@t1g2000pra.googlegroups.com> Hi, I have found that it is possible to reassign the instance.__class__ reference to the same class (but after reloading) to make the isinstance() test work again! I know that it is a kind of hacking of the Python interpreter, but it works :-) From pesquisa485 at gmail.com Tue Dec 11 15:05:36 2007 From: pesquisa485 at gmail.com (pesquisa) Date: Tue, 11 Dec 2007 12:05:36 -0800 (PST) Subject: cadastros de e-mails por estados Message-ID: listas de email marketing livre de spam Maladireta e-mails para mala- direta. mala direta, emails segmentados, e-mail marketing. Visite agora: http://www.divulgaemails.com Listas de e-mails, lista de emails, compra de emails, maladireta, mala direta segmentada, , mala direta por e-mail. Mala Direta, Fazer Mala Direta, Cadastro de Mala Direta, Lista de Mala Direta, Endere?o para Mala Direta, Maladireta, Telemarketing, Enviar Mala Direta, Envio de Mala Direta. http://www.divulgaemails.com mala direta,modelo, gratis,e-mail para, por email, virtual, trabalho em casa,fazer, software, mail Visite agora: http://www.divulgaemails.com divulga email, mala direta, lista de emails, e-mails, email, lista de e-mails, lista de email, lista de e-mail, mailing list, emails, divulga??o por email, divulga??o, email para mala direta, divulga, email marketing, spam, fazer spam, divulgue, milh?es de emails, milh?es de email. Os melhores Modelos de Contratos e Cartas Comerciais. Como escrever uma proposta, ducumento ou carta comercial: Visite tamb?m: http://www.modelosdecartascomerciais.com cadastros de e-mails por estados From python.list at tim.thechases.com Mon Dec 31 12:39:01 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 31 Dec 2007 11:39:01 -0600 Subject: Newbie: Why doesn't this work In-Reply-To: <207173e6-dff0-481a-a2ef-6d3cfa719460@e10g2000prf.googlegroups.com> References: <207173e6-dff0-481a-a2ef-6d3cfa719460@e10g2000prf.googlegroups.com> Message-ID: <47792935.5060907@tim.thechases.com> A couple items of note: > class Person: This should be "class Person(object)" to take advantage of some of the features that new-style classes offer...particularly in this case. > def __init__(self, fName="", lName=""): > self.__fName = fName > self.__lName = lName > > def __getattr__(self, attr): > if attr == "name": > return self.__fName + " " + self.__lName > > def __setattr__(self, attr, value): > # this assumes that value is a tuple of first and last name > if attr == "name": > self.__fName, self.__lName = value if the attr isn't "name", no default behavior gets called here. The common way, with new-style classes is to add else: parent(Person, self).__setattr__(attr, value) Do be aware that this has some odd behaviors when what you put in and what you get out are different types: >>> p1.name = ("Joe", "Smith") >>> p2.name = p1.name Traceback (most recent call last): File "x.py", line 22, in ? p2.name = P.name File "x.py", line 13, in __setattr__ self.__fName, self.__lName = value ValueError: too many values to unpack (slightly munged traceback as it actually came from the test input file rather than the interactive prompt) -tim From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Dec 2 05:10:49 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 02 Dec 2007 11:10:49 +0100 Subject: "Python" is not a good name, should rename to "Athon" References: <78bdd499-a263-4c68-8e43-e3e59b111c7e@a39g2000pre.googlegroups.com> <5rcq90F13re18U1@mid.individual.net> <2bd39781-94e2-4d3d-b185-47a247d3acc2@d27g2000prf.googlegroups.com> <20a6e1c5-a865-45f4-b511-59ebd734ac74@e10g2000prf.googlegroups.com> <5ree76F14bp82U2@mid.individual.net> <0a48e277-9c49-4d8b-9469-6c96c6557858@s19g2000prg.googlegroups.com> Message-ID: <5rfel9F1480rvU1@mid.individual.net> Russ P. wrote: > Python is an "acceptable" name, but Newton1 (or Newton3) would be > a great name. Nah, I like Monty and Snakes. Newton already has his name as unit for kg*m/s^2. :) Regards, Bj?rn -- BOFH excuse #74: You're out of memory From deets at nospam.web.de Mon Dec 24 09:52:16 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 24 Dec 2007 15:52:16 +0100 Subject: Releasing malloc'd memory using ctypes? In-Reply-To: References: Message-ID: <5t9vdcF1ca377U1@mid.uni-berlin.de> skip at pobox.com schrieb: > I am starting to experiment with ctypes. I have a function which returns a > pointer to a struct allocated in heap memory. There is a corresponding free > function for that sort of struct, e.g.: > > from ctypes import * > > cdll.LoadLibrary("libthing.so") > c_thing = CDLL("libthing.so") > > class THING(Structure): > _fields_ = [("name", c_char_p), > ("value", c_int)] > > get_thing = c_thing.get_thing > get_thing.restype = POINTER(THING) > free_thing = c_thing.free_thing > > So I call get_thing() and get back this ctypes wrapper for a pointer to a > thing. I can extract the name and value elements from the thing instance > just fine: > > thing_p = get_thing() > thing = thing_p.contents > print thing.name, "=", thing.value > > Now I need to call free_thing. What do I pass it? thing_p? Some attribute > of thing_p? Something else altogether? The ctypes module docs seem to be > strangely silent on the question of freeing heap memory which you've > received from the underlying library's functions. You simply declare free by loading libc (I'm a unix-guy, Windows will have an equivalent) as library and then declaring it. And of course it gets a void-pointer, so you have to cast you pointer to void* - as you'd have in C (or get a warning). Diez From arkanes at gmail.com Wed Dec 5 16:39:37 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 5 Dec 2007 15:39:37 -0600 Subject: Converting LF/FF delimited logs to XML w/ Python? In-Reply-To: References: Message-ID: <4866bea60712051339i2a15a284i8bd238e79d84956b@mail.gmail.com> On Dec 5, 2007 3:19 PM, Kadin2048 wrote: > This is a very noob-ish question so I apologize in advance, but I'm > hoping to get some input and advice before I get too over my head. > > I'm trying to convert some log files from a formfeed- and > linefeed-delimited form into XML. I'd been thinking of using Python to > do this, but I'll be honest and say that I'm very inexperienced with > Python, so before I dive in I wanted to see whether some more > experienced minds thought I was choosing the right tool. > > Basically, what I want to do is convert from instant messaging logs > produced by CenterIM, which look like this (Where "^L" represents ASCII > 12, the formfeed character): > > ^L > IN > MSG > 1190126325 > 1190126325 > hi > ^L > OUT > MSG > 1190126383 > 1190126383 > hello > > To an XML-based format* like this: > > > hi > hello > > > Obviously there's information in the bottom example not present in the > top (account names, protocol), but I'll grab those from the file name or > prompt the user. > > Given that I'd be learning as I go along, is Python a good tool for > doing this? (Am I totally insane to be trying this as a beginner?) And > if so, where should I start? I'd like to avoid massive > wheel-reinvention if at all possible. > > I'm not afraid to RTFM but there's a lot of information around on Python > and I'm not sure what's most relevant. Suggestions on what to read, > books to buy, etc., are all welcomed. > This is a pretty simple problem and is well suited for a beginner project. The file() builtin will get you the data in your log file. Using the split() method of the string object, you can break your logfile into chunks. There are a number of XML libraries in the standard lib, but xml.etree is my preferred one. It is documented in the stdlib docs, and on the effbot site. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Dec 19 07:58:50 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 19 Dec 2007 13:58:50 +0100 Subject: import X between submodules in a package In-Reply-To: References: <4768da12$0$10771$426a74cc@news.free.fr> Message-ID: <47691552$0$12400$426a34cc@news.free.fr> Donn Ingle a ?crit : >> would be a VeryBadThing(tm). > :) > >> Having explicits imports in each module is good wrt/ readability. > Okay, I can accept that. I worry that it's opening the module file over and > over again Hopefully not ! "import" is not "include". > - or does it open it once and kind of re-point to it when it > hits a second import of the same thing? You guess. When fisrt imported, the module's source is executed, a module object is created and stored in sys.modules, and the needed names are inserted into the importing module's namespace. Next times the module is "served" directly from sys.modules. > >> package, you can of course factor them out in a distinct submodule and >> just do a 'from myimports import *' at the top of the others submodules... > Good point. Note that while it's perfectly legal, that's a pattern I'd try to avoid unless I have a very good reason to use it. From rpdooling at gmail.com Mon Dec 3 09:53:23 2007 From: rpdooling at gmail.com (Rick Dooling) Date: Mon, 3 Dec 2007 06:53:23 -0800 (PST) Subject: python 2.5 - f=open('a_file.txt','w') gives [Errno 2] References: <56e9075a-b3aa-4e8e-b5b7-5a58f0305945@s36g2000prg.googlegroups.com> Message-ID: <190d6986-2f37-4432-bb2e-d6b1dac4e891@d21g2000prf.googlegroups.com> On Dec 3, 7:47 am, dirkheld wrote: > IOError: [Errno 2] No such file or directory: 'a_file.txt' I sometimes see that error on Linux when trying to run a script with DOS line endings. Is it an imported file? I don't know Macs, but start by making sure both your script and the file have Mac line endings? rick From sjmachin at lexicon.net Sun Dec 30 17:32:30 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 30 Dec 2007 14:32:30 -0800 (PST) Subject: Sub-classing unicode: getting the unicode value References: <87fxxkugrd.fsf@physik.rwth-aachen.de> <87bq87vqkj.fsf@physik.rwth-aachen.de> Message-ID: On Dec 31, 8:08 am, Torsten Bronger wrote: > Hall?chen! > > Gabriel Genellina writes: > > On 30 dic, 17:25, Torsten Bronger > > wrote: > > >> I sub-classed unicode in an own class called "Excerpt", and now I > >> try to implement a __unicode__ method. In this method, I want to > >> get the actual value of the instance, i.e. the unicode string: > > > The "actual value of the instance", given that it inherits from > > unicode, is... self. > > But then it is not unicode but Excerpt which I don't want. The idea > is to buffer the unicode representation in order to gain efficiency. > Otherwise, a lot of unicode conversion would take place. > I'm confused: you are subclassing unicode, and want to use several unicode methods, but the object's value appears to be an 8-bit string!?!? Care to divulge the code for your __init__ method? From martin at v.loewis.de Thu Dec 27 09:47:37 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 27 Dec 2007 15:47:37 +0100 Subject: Python DLL in Windows Folder In-Reply-To: References: <533b7d320712231027h26623fffi3b471b6c85873a64@mail.gmail.com> <4866bea60712241007r1db5de8w75abab3c8a2e024e@mail.gmail.com> <0f90f7bc-2faa-4a21-99c3-28ad2e074e89@a35g2000prf.googlegroups.com> <533b7d320712250143te07c86ch4b47e79c3a55d331@mail.gmail.com> Message-ID: <4773BB09.8030905@v.loewis.de> >> Instead of being upset about cutting your word (which was not my >> intention, sorry about that), it would be nice if you could make a >> statement concerning the problem I mentioned: Having an object being >> created by one MSVC runtime, msvcr80.dll and passing it to another >> one, msvcr71.dll. > > The C runtime doesn't create objects. Depends on your definition of "object". fopen will create objects, and passing those to a different CRT will cause crashes. Regards, Martin From Lie.1296 at gmail.com Sat Dec 15 17:38:17 2007 From: Lie.1296 at gmail.com (Lie) Date: Sat, 15 Dec 2007 14:38:17 -0800 (PST) Subject: About Rational Number (PEP 239/PEP 240) References: <5cded538-8c2c-4929-a3aa-ebe30eb1cc3d@e23g2000prf.googlegroups.com> <975f4667-2bf9-4d4b-a1de-95390154c8d1@t1g2000pra.googlegroups.com> Message-ID: On Dec 16, 4:55 am, "Fredrik Johansson" wrote: > On Dec 15, 2007 10:05 PM, Lie wrote: > > > Random ramble past here: > > Actually, my vision would be not only fractions, but also rooted > > number (square root, cube root, etc), it could be possible to > > implement a type where a number consist of a rooted number times a > > multiplier plus a variable [a + b * root(c, d)]. But I guess this > > would be extremely complex and it requires nesting, probably very slow > > if implementation isn't good. The advantage of using such is much > > faster operations, as long as str() is not called. This actually > > reflects my way of doing paper math, I save the lossy operations > > (float division, root, trigonometric function) until the very end of > > calculation (I'm not fundamentalist though, so compromise sometimes is > > done here and there). > > You're looking for a computer algebra system. Try sympy:http://code.google.com/p/sympy/ > > Fredrik Yeah, that's why I consider them too complex for being included as a core of a general programming language like Python. Nevertheless, fraction datatype _IS_ elementary enough to be included as core language feature. From pavlovevidence at gmail.com Fri Dec 28 15:06:33 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 28 Dec 2007 12:06:33 -0800 (PST) Subject: os.system question References: Message-ID: <967fbefd-dcde-49da-846c-932e24d9e0ac@e6g2000prf.googlegroups.com> On Dec 28, 1:52 pm, stanleyxu wrote: > Hi All, > > I am porting Perl script to Python script. Everything works fines until > calling os.system(). > > In my script, a number of DOS-commands will be executed. > for new_folder, old_folder in folder_array: > os.system('MD "' + new_folder + '"'); > os.system('XCOPY "' + old_folder + '" "' + new_folder + '"'); > > In Perl, all outputs will be printed in console directly. > But in Python, outputs will be printed in separated cmd-windows. > > Is it possible to prevent so many cmd-windows to be opened and let all > output be printed direct in Python shell? Consider using the subprocess module instead. It has more options available than os.system, including I/O redirection, which seems to be what you need. In IDLE, you'll have to capture the output of the programs and print it yourself, since you can't (AFAIK) run a DOS shell in an IDLE window. Untested: import subprocess output = subprocess.Popen('MD "' + new_folder + '"', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] print output Carl Banks From Russ.Paielli at gmail.com Fri Dec 21 18:52:58 2007 From: Russ.Paielli at gmail.com (Russ P.) Date: Fri, 21 Dec 2007 15:52:58 -0800 (PST) Subject: exception message output problem References: <482a0572-8dbe-42b6-9058-118ee0d28254@d4g2000prg.googlegroups.com> Message-ID: <4e293e6a-3374-4a25-b37c-a760387b8c0c@s19g2000prg.googlegroups.com> On Dec 21, 2:58 pm, Lie wrote: > Change the exception into this: > class InconsistentUnits(Exception): > def __init__(self, args=""): self.args = (args,) > # Python have an odd (read: broken) singleton implementation > # single member tuple must have a comma behind it Hey, that worked. Thanks. Actually, the parens aren't needed, so this works too: def __init__(self, args=""): self.args = args, The trailing comma wasn't necessary a while back (pre 2.5?), so something in Python must have changed. I'd say that it looks a bit cleaner without the trailing comma, so maybe whatever changed should get changed back. From rodmena.com at gmail.com Sat Dec 1 03:30:19 2007 From: rodmena.com at gmail.com (farsheed) Date: Sat, 1 Dec 2007 00:30:19 -0800 (PST) Subject: "Show this file in explorer" Message-ID: <8bca2fe0-c81f-4f93-8325-e0e99636762a@p69g2000hsa.googlegroups.com> I have a big problem. I have a list of files that my script find and list them in a little gui. I need this function: when i d-click on each item, I want explorer opens and selects that item inside windows explorer. like that beautiful buttom in iTunes. Thanks in advane. Farshid Ashouri. From arnodel at googlemail.com Mon Dec 24 11:08:09 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 24 Dec 2007 08:08:09 -0800 (PST) Subject: list in a tuple References: Message-ID: <885d00ad-c6ec-484a-830d-bd64cb118127@l32g2000hse.googlegroups.com> On Dec 24, 3:22?pm, montyphy... at gmail.com wrote: > Recently, I got into a debate on programming.reddit.com about > what should happen in the following case: > > >>> a = ([1], 2) > >>> a[0] += [3] > > Currently, Python raises an error *and* changes the first element of > the tuple. Now, this seems like something one would want to > change - why raise an error *and* execute the thing it > was complaining about? The discussion seems to have no end, and > that is why I'm posting here. I would like to know what is the opinion > of the people on this group... Am I really mistaking for thinking that > this is strange and unwanted behavior? Btw I understand *why* is this > happening, I just think it should change... > And here is the post that started this discussion:http://filoxus.blogspot.com/2007/12/python-3000-how-mutable-is-immuta... > > Thanks for your replies For the sake of clarity, say you have typed: >>> L = [1] >>> a = (L, 2) >>> a[0] += [3] Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment >>> a ([1, 3], 2) I think that this is what happens when a[0] += [3] is executed: 1. list.__iadd__(L, [3]) is called, modifying L in place and returning L. 2. tuple.__setitem__(a, L) is tried, raising the TypeError. Notice that this problem doesn't arise when replacing lists with tuples: >>> a = ( (1,), 2) >>> a[0] += (3, ) Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment >>> a ((1,), 2) This is because tuple object don't have an __iadd__ method so a new object tuple.__add__((1,),(3,)) is created and returned. AFAICS, the only way to avoid the error message would be to check if the new object is the same as the old one before raising the TypeError: class mytuple(tuple): "It's ok to do t[i] = obj as long as t[i] was already obj" def __setitem__(self, i, val): if self[i] is not val: raise TypeError("'mytuple' object is immutable") So: >>> a = mytuple(([1], 2)) >>> a[0] += [3] # This now works >>> a[1] += 4 # This won't work as ints are immutable Traceback (most recent call last): File "", line 1, in File "tuple.py", line 4, in __setitem__ raise TypeError("'mytuple' object is immutable") TypeError: 'mytuple' object is immutable >>> a ([1, 3], 2) It wouldn't slow anything down I suppose, just make some currently failing code succeed. -- Arnaud From bj_666 at gmx.net Fri Dec 28 21:37:26 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 29 Dec 2007 02:37:26 GMT Subject: Strange Behavior: csv module & IDLE References: <3f24f105-ea2c-4f8f-aaf5-08340b4e7ca3@y5g2000hsf.googlegroups.com> Message-ID: <5tlq76F1cvq5uU2@mid.uni-berlin.de> On Fri, 28 Dec 2007 18:12:58 -0800, t_rectenwald wrote: > Within the program, the snippet where I use the csv module is below: > > ============================== > csvfile = open('foo.csv', 'w') > writer = csv.writer(csvfile) > > for row in rows: > writer.writerow(row[0:3]) > > csvfile.close > ============================== > > The rows object is returned from a database query and is a list of > tuples. Now here is the strange thing. If I run this program > directly from the command line, i.e., > > D:\test> D:\python25\python foo.py > > It runs fine, foo.csv is created and all is well. However, when I run > it through the IDLE shell as described above, the foo.csv file is > created but remains empty at 0 bytes. When I try to delete the file, > Windows says it is in use. The only way I can break out of this is by > restarting the IDLE shell. In other words, it appears that the shell > is hanging. > > This will run through Task Scheduler, so shouldn't be a problem, but > I'm worried that I'm coding this wrong for it to be acting this way > under IDLE. Any help or explanation would be appreciated. You are not closing the file so the buffered data is not written to disk. To call a function you need the parenthesis, otherwise you are just referencing it without any effect. Ciao, Marc 'BlackJack' Rintsch From murderbystealth at gmail.com Sat Dec 29 10:54:09 2007 From: murderbystealth at gmail.com (=?ISO-8859-1?Q?Michael_Bernhard_Arp_S=F8rensen?=) Date: Sat, 29 Dec 2007 16:54:09 +0100 Subject: Howto on callbacks, queues and good design patterns Message-ID: <47766da0$0$2085$edfadb0f@dtext02.news.tele.dk> Hi there. As a newbie, I need to learn about callbacks and queues(syntax and examples) working together. At work we talk a lot about design patterns. Does any of you know a good site about that or any good books from Amazon? I started using python at work in the summer 2007. I think I know the stuff, but I need to expand my understanding of the more complex programming techniques. Thanks in advance. /Karneevor From andymac at bullseye.apana.org.au Sat Dec 22 19:31:20 2007 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 23 Dec 2007 10:31:20 +1000 Subject: Pure Python GUI lib? In-Reply-To: <6a4f17690712220531y1e86021bt6ed1042e73596b2e@mail.gmail.com> References: <6a4f17690712220531y1e86021bt6ed1042e73596b2e@mail.gmail.com> Message-ID: <476DAC58.9010301@bullseye.andymac.org> oyster wrote: > For the word "Pure", I mean it is not a C/C++/Z++.. extension, so that > we can use it under pythons of different version. Is it possible? > I don't like to update the module for different python and the module > > Currently, I am writing the interface to > iup(http://www.tecgraf.puc-rio.br/iup) via ctypes, but find 2 too > strange things which have let me feel blue for some days, and I don't > know whether it can be successful or not. Can anyone give me some > lights? Thank you. :) Venster is a Windows API GUI wrapper on top of ctypes. Fairly low level, but quite viable. I have an application at work using an old version (0.21) on an old version of ctypes (0.6.3) that works fine, though it doesn't do MDI. Sadly Venster appears not to have recently been maintained in line with changes in ctypes, but the code (available from SourceForge) could still prove a useful reference. Cheers, Andrew. -- ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From rodperson at verizon.net Tue Dec 4 19:07:09 2007 From: rodperson at verizon.net (Rod Person) Date: Tue, 04 Dec 2007 19:07:09 -0500 Subject: Python Class Best Practice In-Reply-To: <4755E7F6.7030008@islandtraining.com> References: <20071204181804.70edef0a@atomizer.opensourcebeef.net> <4755E7F6.7030008@islandtraining.com> Message-ID: <20071204190709.556694a9@atomizer.opensourcebeef.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Tue, 04 Dec 2007 15:51:18 -0800 Gary Herron wrote: > Rod Person wrote: > > > > 1: > > class Foo(object): > > member1='' > > member2=0 > > > > def __init__(self,member1='',member2=0): > > self.member1 = member1 > > self.member2 = member2 > > > > 2: > > class Foo(object): > > def __init__(self,member1='',member2=0): > > self.member1 = member1 > > self.member2 = member2 > > > > > Both examples will store values for member1 and member2 in every > instance. Any code that accesses self.member1 (or 2) will get the > value stored in the instance. > > Example 1 which also creates two *class* members of the same name > won't affect the conclusion of the previous paragraph. The two > values in the class will be shadowed by each instances members of the > same name. > > But now I need to ask, what did you expect to happen here? Well I guess I should say that I'm coming to Python from Delphi, so I am used to creating classes like in #1, but I'm used to having to declare a scope for each member. Not having a scope declaration is really throwing me some. > > * If you thought those two extra assignments in example 1 effected > the execution or storage in the __init__ (or any other method), you > were mistaken. > Yes, this is what I thought. I thought that declaring member1='' would just assign the a default value on creation of the class (as in Delphi). I probably shouldn't have give the parameters in the __init__ a default value in example 1. > Gary Herron Thanks. - -- Rod http://roddierod.homeunix.net:8080 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (FreeBSD) iD8DBQFHVeuucZAIaGStcnARAgEKAJ4/bJW9GSNTsmSgyOTokbCkEQFO7ACdErME 50Mgzge48M2z+nymifkByqo= =e3gV -----END PGP SIGNATURE----- From fetchinson at googlemail.com Wed Dec 5 00:46:04 2007 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Tue, 4 Dec 2007 21:46:04 -0800 Subject: Python surpasses Perl in TIOBE index In-Reply-To: <5rm9b3F15l05pU1@mid.individual.net> References: <7e117be5-4308-43ae-a34b-cd9cb72f15b6@b40g2000prf.googlegroups.com> <75e8931d-87fa-45a3-8638-c5c8508d77e2@s12g2000prg.googlegroups.com> <87fxyifnpp.fsf@rudin.co.uk> <5rm9b3F15l05pU1@mid.individual.net> Message-ID: > > Well we Python folks are spoiled but for most people C++ counts as a > > high level language > > Well, some parts are high-level, but it's full of very > deep elevator shafts for you to accidentally fall > into... > > A truly high-level language also *doesn't* have low > level parts (or at least doesn't expose them unless > you explicitly ask it to). Anyone has an idea what the huge peak around the middle of 2004 can be attributed to? http://www.tiobe.com/tiobe_index/Python.html From exarkun at divmod.com Tue Dec 11 14:43:52 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 11 Dec 2007 14:43:52 -0500 Subject: DNS servers in Python - which ones are a good base for work? In-Reply-To: <475ee012$0$36349$742ec2ed@news.sonic.net> Message-ID: <20071211194352.8162.1753846892.divmod.quotient.44693@ohm> On Tue, 11 Dec 2007 11:10:52 -0800, John Nagle wrote: > I need to do a non-standard DNS server in Python. This >is for a spam blacklist type DNS server, not for IP lookup. >"dnspython" seems to be client side only. Oak DNS is >deprecated. Suggestions? > There's Twisted Names. I wrote a custom DNS server with it just last week. The documentation is a bit sparse, but it's not particularly complicated. Jean-Paul From fivfm at lycos.com Mon Dec 31 07:07:43 2007 From: fivfm at lycos.com (fivfm at lycos.com) Date: 31 Dec 2007 12:07:43 GMT Subject: M.I 5-Perse cution ` 22,5 44 + 837 = 23 ,381 Message-ID: MI5. Persecution Update: Friday 7 April, 2000 22,544 +. 837 = 23,381 Last weekend I delivered another 837 faxes to politicians and the. media on the subject. of the security service conspiracy which has destroyed my life.. This brings the total in the last three years to at least 23,381. These totals do not include. partially delivered faxes. Some. of the recipients of these faxes must know that what I say is true; and I hope to motivate those people to acknowledge the reality. of the. harassment which has followed me for ten years. It takes much time to transmit these. articles, but as OCG MD Simpson-Wells said to me in 1992, you have to be a good. communicator if you are to succeeed. Harassment in. February 2000 Following a quiet. period of almost five months, the persecution resumed with a vengeance in. late January/February 2000. At this time I was at home in Clapham, London and was. a relatively easy target for the persecutors. They have my house bugged, for audio. and I believe video in some. rooms as well; so they can find out easily where I will be going on a particular day, and place people in. that location to mouth words of abuse at me. (I know the last sentence. sounds like classic paranoia, but it happens to. be true, and some of the people reading this know it to be true.) On Friday 11 February 2000 I went shopping in Croydon, to buy a. watch at H. Samuels jewellers in the Whitgift Centre. While I was. there two youths came into the shop, one of them quietly uttered an obscenity at me,. and they immediately walked out.. They showed no interest in the shop. That Sunday I met with a friend in Clapham, who started needling. me about "do you know anything about the CIA. and FBI?". Rather unsubtle, and worrying considering Ive known this guy for. 20 years. From the words and demeanour. of this "friend" and others in February, I saw that the persecutors have again been trying. to separate from me what remains of my social. life. Incidents in. my Road in February MI5 very. rarely place people in my home road to harass me, but such was their persecutory fervour in February that they did so on three. separate occasions. On the first such occasion,. I was met my two youths who, grinning, said a deeply offensive sexual obscenity. at me - at which I coughed at them, so. they called me a "wanker". This incident is safely recorded on minidisc-walkman, but because of the. offensive nature of their abuse the recording will. not be made public. Another. incident very early in the morning of Sunday 20/Feb/2000 occurred outside my home, following an evening in Croydon with. some schoolfriends.. Again there were two youths - for some reason the persecutors always. travel in twos or threes, very rarely is there just one of them - perhaps they need. a group to bolster their courage, perhaps just one of them wouldnt have the guts to say something unpleasant. One. of the youths said quietly, and bitterly, "shitty, very. shitty". Anyway, in March there were no further incidents near my house. in in my road, and. our neighbours are very well disposed towards us, so let us hope that the current quiet. continues. 13814 -- Posted via NewsDemon.com - Premium Uncensored Newsgroup Service ------->>>>>>http://www.NewsDem From andrea.baron at tin.it Tue Dec 4 05:33:03 2007 From: andrea.baron at tin.it (beronz) Date: Tue, 4 Dec 2007 02:33:03 -0800 (PST) Subject: make money with bux!! Message-ID: http://bux.to/?r=beronz use this link to register What is Bux.to? Bux.to is a new innovative, international and FREE English based service that allows advertisers to reach thousands of potential customers by displaying their ad on our, "Surf Ads" page. How does it work? You view websites in 30 second sessions via the "Surf Ads" page. Once the 30 seconds is up, you'll either get a green tick sign or a red 'X'. The green tick sign means you've earned $0.01 and as premium member $0.0125 for the visit and the 'X' means you have not earned money for the visit. You'll get red X's when you have more than one website from the "Surf Ads" page open. When this happens, you get no credit. How do I get paid? If you have at least $10.00 accumulated, you can click on your account balance within your stats area and it will submit your request. Currently, we only make payments via PayPal. We will soon be using other methods of payment. join bux! From chris.gonnerman at newcenturycomputers.net Tue Dec 4 23:39:38 2007 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Tue, 04 Dec 2007 22:39:38 -0600 Subject: Why Python 3? Message-ID: <47562B8A.3040506@newcenturycomputers.net> I spent some time today reading about Python 3, and specifically the differences between Python 3 and Python 2, and I was left with a question... why? Why bother to change to Python 3, when the CPython implementation is slower, and probably will be for a while? When I learned Python, 1.5 was the current version. Each new version from 2.0 on brought goodies to the table... I think I have made use of about half of the "advancements" that have come along since. But I was swayed into taking Python seriously by Eric Raymond's article in Linux Journal, where he talked about how much easier it was to read his old code in Python than in Perl, and how the whole white space thing wasn't so bad. I discovered I agreed with him. Python has been my favorite language ever since. But... almost all of my old 1.5 code ported painlessly to 2.x. No need for a "1.5to2" script, whereas I see that there is a "2to3" script for converting modules. Python 1.5 and 2.x are "executable pseudocode," something that can be easily read by anyone with a modicum of programming knowledge. In fact, the things I rarely or never use in Python tend to be those things I find hardest to read (like list comprehensions). Few of the changes along the way have required me to change how I *write* code; probably the worst was the integer division change, which I disagreed with, but I went along with the community. I don't see myself using Python 3 for a long time. Probably as long as I can hold out. Where are my goodies? What is my payoff for learning how to write code the new way? I can't see it. Many things seem a lot less obvious... like, what was wrong with .keys() returning a list? Now it returns some strange object type. I don't think I can surely be the only one. Certainly, I'm nobody important; it's not as if my opinion has any real bearing on the situation. I suspect that many Python coders will stay with 2.x; after all, this is Open Source... there is no Micro$oft forcing us to upgrade to get more licenses. If enough people stay with 2.x... will the project fork? Will there be enough of "us" to maintain Python 2 indefinitely? Will module maintainers have to choose which version of Python to support? It's already a pain for me to keep the GDmodule up with the current Python release... and it's a pretty small module. I just don't see the point. I feel like we already have all we need in Python 2. I feel like the language is becoming less and less "friendly" and "readable" as it evolves. Just my two cents, I guess. -- Chris Gonnerman From grante at visi.com Wed Dec 19 11:17:04 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 19 Dec 2007 16:17:04 -0000 Subject: How to generate pdf file from an html page?? References: <13md67emkcesh11@corp.supernews.com> <038bbf25-3345-4224-b506-54f9fb4b6545@d27g2000prf.googlegroups.com> <13mieavg35e92@corp.supernews.com> Message-ID: <13mih00shme5ee1@corp.supernews.com> On 2007-12-19, Terry Jones wrote: >>>>>> "Grant" == Grant Edwards writes: >Grant> On 2007-12-19, abhishek wrote: >>>> > Hi everyone, I am trying to generate a PDF printable format file from >>>> > an html page. Is there a way to do this using python. If yes then >>>> > which library and functions are required and if no then reasons why it >>>> > cant be done. >>>> >>>> Here's one way: >>>> >>>> ------------------------------html2pdf.py----------------------------------------- >>>> #!/usr/bin/python >>>> import os,sys >>>> >>>> inputFilename,outputFilename = sys.argv[1:3] >>>> >>>> os.system("w3m -dump %s | a2ps -B --borders=no | ps2pdf - %s" % (inputFilename,outputFilename)) > > Note that this is highly insecure. outputFilename could be passed e.g., as > > /tmp/file.pdf; rm -fr /home/abhishek Here's a half-assed solution: inputFilename = inputFilename.replace("'","") outputFilename = outputFilename.replace("'","") os.system("w3m -dump '%s' | a2ps -B --borders=no | ps2pdf - '%s'" % (inputFilename,outputFilename)) As somebody else suggested, building the pipeline "by hand" using the subprocess module is the most bullet-proof method. -- Grant Edwards grante Yow! I brought my BOWLING at BALL -- and some DRUGS!! visi.com From gagsl-py2 at yahoo.com.ar Tue Dec 18 08:05:43 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Dec 2007 05:05:43 -0800 (PST) Subject: checking a string against multiple patterns References: Message-ID: <2b178dc3-771b-471a-8b9b-5642763d5397@i12g2000prf.googlegroups.com> On 18 dic, 09:41, tomasz wrote: > Hi, > > here is a piece of pseudo-code (taken from Ruby) that illustrates the > problem I'd like to solve in Python: > > str = 'abc' > if str =~ /(b)/ # Check if str matches a pattern > str = $` + $1 # Perform some action > elsif str =~ /(a)/ # Check another pattern > str = $1 + $' # Perform some other action > elsif str =~ /(c)/ > str = $1 > end > > The task is to check a string against a number of different patterns > (containing groupings). > For each pattern, different actions need to be taken. > > In Python, a single match of this kind can be done as follows: > > str = 'abc' > match = re.search( '(b)' , str ) > if match: str = str[0:m.start()] + m.group(1) # I'm not sure if > this way of accessing 'pre-match' > # is > optimal, but let's ignore it now > > The problem is that you you can't extend this example to multiple > matches with 'elif' > because the match must be performed separately from the conditional. > > This obviously won't work in Python: > > if match=re.search( pattern1 , str ): > ... > elif match=re.search( pattern2 , str ): > ... > > So the only way seems to be: > > match = re.search( pattern1 , str ): > if match: > .... > else: > match = re.search( pattern2 , str ): > if match: > .... > else: > match = re.search( pattern3 , str ): > if match: > .... > > and we end up having a very nasty, multiply-nested code. Define a small function with each test+action, and iterate over them until a match is found: def check1(input): match = re.search(pattern1, input) if match: return input[:match.end(1)] def check2(input): match = re.search(pattern2, input) if match: return ... def check3(input): match = ... if match: return ... for check in check1, check2, check3: result = check(input) if result is not None: break else: # no match found -- Gabriel Genellina From jjl at pobox.com Mon Dec 3 17:23:55 2007 From: jjl at pobox.com (John J. Lee) Date: Mon, 03 Dec 2007 22:23:55 GMT Subject: issue with cookielib.LWPCookieJar References: <468c2718-0e62-41b2-bf09-cd67f5978594@e25g2000prg.googlegroups.com> Message-ID: <87lk8bl8n8.fsf@pobox.com> JD Smith writes: > Greetings: > > My cookiejar contains the cookie that I need however when I do > cj.save(file) it does not actually save out to the cookies.lwj Does > anyone have any clue what would keep this from saving? It CREATED my > cookies.lwj file so I know it's not permissions. You want a true ignore_discard argument to .save() and .load() (or .revert()). John From mail at microcorp.co.za Sun Dec 9 01:53:31 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 9 Dec 2007 08:53:31 +0200 Subject: how to convert 3 byte to float References: <475a7336$0$13116$9b4e6d93@newsspool2.arcor-online.net><5rvc6hF17032iU1@mid.individual.net><475a8591$0$17533$9b4e6d93@newsspool4.arcor-online.net> <1F3FD2D2-EE5A-4AAA-9DB9-A8D2BB129DE5@comhem.se> Message-ID: <009801c83a30$36b916c0$03000080@hendrik> "Tommy Nordgren" wrote: > > On 8 dec 2007, at 12.52, Mario M. Mueller wrote: > > > Bjoern Schliessmann wrote: > > > > [...] > >> BTW, who in his mind designs three byte floats? Memory isn't that > >> expensive anymore. Even C bool is four bytes long. > > > > It's output of a digitizer (but not that old). I was also wondering > > about > > the reason for this limitation (maybe the design is ~20 years old). > > > > Mario > > -- > One thing to consider: It is possible that one of the bytes > contributes bits > to BOTH the mantissa and the exponent ; Do you know the relative > accurazy of the digitizer? What is it digitising - if its an Analogue to Digital converter, then the 24 bits may not be floats at all, but simple integer counts. Is there no Fine Manual documenting the output format? - Hendrik From DelDotDr at gmail.com Mon Dec 3 05:36:44 2007 From: DelDotDr at gmail.com (DelDotDr at gmail.com) Date: Mon, 3 Dec 2007 02:36:44 -0800 (PST) Subject: Any idea how to open Matlab and run M-files by using Python? References: <1ccff7ae-df36-4bf5-8f70-bcf81ded014d@t47g2000hsc.googlegroups.com> Message-ID: Hello, One solution I can think of would be to write an interface to the Matlab command prompt using pexpect, the python implementation of expect. Expect allows you to spawn and interact with other process. There is already a cool implementation of exactly this in Sage, an open source computer algebra system written in python. If you want to see something work immediately, try installing sage (sage.math.washington.edu/sage). I did some experimenting (in a linux environment) and it works quite nicely. Here is an example: I wrote a simple matlab function myAdd saved as myAdd.m function thesum = myAdd(a, b) thesum = a+b; I put the file in my Matlab search path. In sage, I did this: sage: a = matlab('myAdd(2,2)') sage: a 4 This would require you to run your python scripts using Sage instead of just python. You can import the sage library into python, but it's kind of non- trivial. At the very least, you can study sage's matlab interface, which is written in python. It is very easy to spawn process and give commands with pexpect, but not as fun to get results because it involves parsing to get the output. Good luck, -Dorian On Dec 2, 8:02 pm, itcecsa wrote: > Hi, > > I am implementing a small Python project, what I am going to do is to > open Matlab and run some M-files, and get some output from Matlab > command prompt. > > I have no idea how to open Matlab from Python! > > Any suggestions would be appriciated! From Mberyl1 at aol.com Sat Dec 1 15:43:39 2007 From: Mberyl1 at aol.com (Mberyl1 at aol.com) Date: Sat, 1 Dec 2007 15:43:39 EST Subject: LIVE TEEN CAM in my ROOM! Message-ID: -------------- next part -------------- An HTML attachment was scrubbed... URL: From damonjulian at yahoo.com Sun Dec 23 12:52:21 2007 From: damonjulian at yahoo.com (damonjulian at yahoo.com) Date: Sun, 23 Dec 2007 09:52:21 -0800 (PST) Subject: why does a disabled button respond to clicks Message-ID: <9168ecd1-1100-47db-83b7-6e3f04a44cd3@d21g2000prf.googlegroups.com> hi ,i created 3 buttons such that if button1 is clicked it will disable button2 ,and clicking button3 will restore state of button2 to normal, to my dismay i find that button2 still responds to clicks even if it is greyed out here is the code..am i doing something wrong? is there a way to truly disable the button? class MyApp: def __init__(self,parent): self.mainframe=Frame(parent) self.mainframe.pack() #self.canvorig=Canvas(self.mainframe,width=100,height=200) #self.canvorig.pack() self.button1=Button(self.mainframe,bg="green") self.button1.configure(text="1") self.button1.pack(side=LEFT) self.button1.bind("",self.buttonClick1) self.button2=Button(self.mainframe,bg="yellow") self.button2.configure(text="2") self.button2.pack(side=LEFT) self.button2.bind("",self.buttonClick2) self.button3=Button(self.mainframe,bg="red") self.button3.configure(text="3") self.button3.pack(side=RIGHT) self.button3.bind("",self.buttonClick3) def buttonClick1(self,event): print "ok clicked" self.button2.configure(state="disabled") self.button2.update_idletasks() def buttonClick2(self,event): print "2 clicked" def buttonClick3(self,event): print "3 clicked" self.button2.configure(state="normal") self.button2.update_idletasks() root = Tk() myapp = MyApp(root) root.mainloop() From te509 at york.ac.uk Sat Dec 15 09:33:04 2007 From: te509 at york.ac.uk (te509 at york.ac.uk) Date: 15 Dec 2007 14:33:04 +0000 Subject: Convert a sequence of bits to a bit-string Message-ID: Hi guys, does anybody know how to convert a long sequence of bits to a bit-string? I want to avoid this: >>> bit=0011010000000000000111111111111111000000000000000001111111010111111111111001 >>> str(bit) '949456129574336313917039111707606368434510426593532217946399871489' I would appreciate a prompt reply because I have a python assessment to submit. Thanks, Thomas From tim.leslie at gmail.com Wed Dec 5 06:35:41 2007 From: tim.leslie at gmail.com (Tim Leslie) Date: Wed, 5 Dec 2007 22:35:41 +1100 Subject: Why did no one tell me about import antigravity? In-Reply-To: References: <52f0eca3-e807-4890-b21d-460e0453c0e2@e4g2000hsg.googlegroups.com> Message-ID: On 5 Dec 2007 10:08:48 GMT, Adrian Cherry wrote: > Ant wrote in news:52f0eca3-e807-4890-b21d- > 460e0453c0e2 at e4g2000hsg.googlegroups.com: > > > Python on xkcd: > > > > http://xkcd.com/353/ > > > > Another good comic from xkcd, I'm surprised by the muted response > on here. Don't forget to check out the alt. text on the comic > > Alt text: "I wrote 20 short programs in Python yesterday. It was > wonderful. Perl, I'm leaving you." > +1 QOTW Tim > > Regards > > Adrian > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From bignose+hates-spam at benfinney.id.au Tue Dec 11 05:24:04 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 11 Dec 2007 21:24:04 +1100 Subject: Securely distributing python source code as an application? References: <7489fd22-e2dd-44b8-a35b-e2858fa36d32@b1g2000pra.googlegroups.com> Message-ID: <87lk815y2j.fsf@benfinney.id.au> xkenneth writes: > I'll shortly be distributing a number of python applications that > use proprietary. That's unfortunate. Hopefully it's not too late to avoid restricting yourself and your users in this way. > The software is part of a much larger system and it will need to be > distributed securely. How can i achieve this? That depends partly on what "distributed securely" means for you. Can you elaborate? In particular, what threat model are you seeking security from? -- \ "If I ever get real rich, I hope I'm not real mean to poor | `\ people, like I am now." -- Jack Handey | _o__) | Ben Finney From MartinRinehart at gmail.com Fri Dec 21 14:02:17 2007 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Fri, 21 Dec 2007 11:02:17 -0800 (PST) Subject: How to in Python References: <5b91c387-0a96-466c-a5c7-7d412a9c6796@b1g2000pra.googlegroups.com> <9ce37ee7-b6ad-4d7b-b3b6-b67b3f2f1a7b@e10g2000prf.googlegroups.com> <2be7103b-a119-4762-9d30-ace320b5d63a@j20g2000hsi.googlegroups.com> Message-ID: <9c5b6014-9b86-47dc-b5c3-28ffb5686141@e4g2000hsg.googlegroups.com> Chris Mellon wrote: > Is there some reason that you think Python is incapable of > implementing lexers that do this, just because Python lexer accepts > it? Absolutely not. My opinion is that it's a bug. A very, very minor bug, but still six-legged. > Note that if you're using your lexer to mark up or pretty print or > whatever Python source, it's wrong - 0x is (rightly or not) a valid > Python literal. My lexer is for my language, Decaf, which, in this particular, is the same as Python. Here's what I find at at python.org/ref: (2.4.4). hexinteger ::= "0" ("x" | "X") hexdigit+ Implementation differs from specification. In this case, I think the spec is more sensible. From charl.loubser at gmail.com Thu Dec 13 02:16:01 2007 From: charl.loubser at gmail.com (Merrigan) Date: Wed, 12 Dec 2007 23:16:01 -0800 (PST) Subject: E-Mail Parsing Message-ID: <53d05498-d057-4e8f-90c8-48bb1cdf233f@t1g2000pra.googlegroups.com> Hi There, I am writing a script to administer my E-Mail Server. The One thing I'm currently struggling with is kind of Parsing the E-Mail adress that I supply to the script. I need to get the username (The part BEFORE the @ sign) out of the address so that I can use it elsewhere. The problem I have with this is that both the domain, and the username are variable lenghts and that I have no idea how to split the two parts. Is there any way that I can do this? Thank ye very much. -- Merrigan From slimaak at gmail.com Sat Dec 1 12:04:33 2007 From: slimaak at gmail.com (slomo) Date: Sat, 1 Dec 2007 09:04:33 -0800 (PST) Subject: How to read strings cantaining escape character from a file and use it as escape sequences? References: <98aefc9f-cfed-43ef-b67a-1b94ed1c3fcc@s12g2000prg.googlegroups.com> Message-ID: <752b4684-56ef-41d4-ba07-ed11b5d1f913@s36g2000prg.googlegroups.com> WOW! Great! Thanks, Duncan. On 12?2?, ??12?33?, Duncan Booth wrote: > slomo wrote: > >>>> print line > > \u0050\u0079\u0074\u0068\u006f\u006e > > > But I want to get a string: > > > "\u0050\u0079\u0074\u0068\u006f\u006e" > > > How do you make it? > > line.decode('unicode-escape') From martin at v.loewis.de Wed Dec 12 19:43:22 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 13 Dec 2007 01:43:22 +0100 Subject: Help needed with python unicode cgi-bin script In-Reply-To: <6dK7j.8027$581.1065@trnddc04> References: <475cefe8$0$31165$9b622d9e@news.freenet.de> <8tj7j.5048$bW.4346@trnddc07> <24f3c1af-bf57-4b94-8d02-d7e956764f90@s8g2000prg.googlegroups.com> <0f09d97f-d742-4a3e-a459-91e730748d7e@b1g2000pra.googlegroups.com> <_vE7j.5156$bW.2309@trnddc07> <475f1dc4$0$19340$9b622d9e@news.freenet.de> <6dK7j.8027$581.1065@trnddc04> Message-ID: <4760802b$0$31162$9b622d9e@news.freenet.de> > It looks like your suggestions to change charset were incorrect. My example > works equally well with charset=utf8 as it does with charset=windows-1252. It rather looks like that you didn't follow the suggestions carefully. In my very first message, I wrote # Sending "Content-type: text/html" is not enough. The web browser needs # to know what the encoding is. So you should send # # Content-type: text/html; charset="your-encoding-here" As Duncan Booth explains, this is what you should have done instead - if you do that, you can also leave the AddDefaultCharset declaration. Regards, Martin From hniksic at xemacs.org Mon Dec 3 10:36:18 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 03 Dec 2007 16:36:18 +0100 Subject: Overriding member methods in __init__ References: <47540d0f$0$12505$426a74cc@news.free.fr> Message-ID: <87ir3fx025.fsf@mulj.homelinux.net> c james writes: >> class YesNo(object): >> def __init__(self, which): >> self.which = which >> >> def __call__(self, val): >> return (self.no, self.yes)[self.which](val) >> >> def yes(self, val): >> print 'Yes', val >> >> def no(self, val): >> print 'No', val > > Thanks, I was trying to eliminate another level of indirection with a > test at each invocation of __call__ Allowing instance lookup of __call__ would slow down normal uses of the internal __call__ mechanism. Since it used for all function and method calls, it needs to remain extremely fast. If you're really worried about performance, you can define YesNo.__new__ to return either a Yes instance or a No instance, depending on the value: class YesNo(object): def __new__(cls, which): if which: return object.__new__(Yes) else: return object.__new__(No) def yes(self, val): print 'Yes', val def no(self, val): print 'No', val class Yes(YesNo): def __call__(self, val): self.yes(val) # no check at every call class No(YesNo): def __call__(self, val): self.no(val) # likewise >>> x = YesNo(True) >>> x <__main__.Yes object at 0xb7d0ee8c> >>> x('foo') Yes foo >>> y = YesNo(False) >>> y <__main__.No object at 0xb7d0eeec> >>> y('foo') No foo >>> isinstance(x, YesNo) True >>> isinstance(y, YesNo) True From andre.roberge at gmail.com Mon Dec 17 19:25:53 2007 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 17 Dec 2007 16:25:53 -0800 (PST) Subject: very puzzling doctest behaviour Message-ID: <9b580ef0-ee64-4b40-b419-6cddfd29888f@x69g2000hsx.googlegroups.com> Hi everyone, I've run into a very puzzling doctest behaviour - I'm trying to narrow down the case of it but I'm dealing with multiple files being imported for one of the case and I have not, so far, created a simple example. However, just in case someone had run into something similar, I thought I would ask. I am using the doctest.testfile() interface to load up tests that resides in a text file. Here's a description of the puzzling feature. ==== file 1: all tests pass ==== title >>> print "<" < >>> import module_a >>> print "<" < ======================== So far, nothing surprising... ==== file 2: we have a failure ==== title >>> print "<" < >>> import module_a >>> print "<" < + 400 lines of text and further tests ======================== The second expected "<" fails; instead, we get "<" ==== file 3: all tests pass ==== title >>> print "<" < >>> import module_a >>> print "<" < + 400 lines of text and further tests ======================== Upon further inspection, I find in module_a that, if I comment out a line like import module_b then, tests in file 2 pass again. So, I figure the problem is in module_b. I then did ==== file 4: one failure ==== title >>> print "<" < >>> import module_b >>> print "<" < + 400 lines of text and further tests ======================== Again, this can be "fixed" by changing the expected output of the second test ==== file 5: no failure ==== title >>> print "<" < >>> import module_b >>> print "<" < + 400 lines of text and further tests ======================== As mentioned, I have not succeeded in narrowing it down further. However, has anyone observed such a behaviour of doctests before? Andr? From jyoung79 at kc.rr.com Sun Dec 9 17:25:00 2007 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Sun, 9 Dec 2007 16:25:00 -0600 Subject: changing fonts? Message-ID: <14036725.144641197239100487.JavaMail.root@hrndva-web02-z01> Hi Doug, > I'm not *that* familiar with the Terminal program on OS/X, but regardless > perhaps I can point out a possibly useful path to explore... Wow!! Thanks for all this info!! This is some good stuff!!! :-) Well, I got to experimenting with a lot of different stuff, as well as doing a lot of research on the net, and I think I've found what I was looking for. It's not perfect, but I'm thrilled I was able to do this! I never could find anything on changing the actual font (or character set) on-line, and looking through the man pages I couldn't figure out if it was possible there either, although I'm still new to this stuff so a lot of it could just be my ignorance. I took Greg's idea and found this web-site: http://www.unicode.org/charts/PDF/U0370.pdf which gave me all the unicode characters for the Greek font. I wrote a simple Python script to test this (only on Mac OS X 10.5 at the moment): ---------- import os os.system("clear") print '\033[36m', u'\u03B1\u03C1\u03C4\u03BF\u03C2', '\033[37m', 'This is the Greek word for "Bread"', '\033[0m' ---------- As you can see, I also added some escape sequences to color the text in the Terminal window as well. And it works great!! Note that I have Terminal set up with the 'Monaco' font. Thanks again, Greg and Doug, for your incredible help of not only steering me in the right direction, but also teaching me new techniques which are definitely going to come in handy! :-) Jay From igor.tatarinov at gmail.com Thu Dec 13 17:53:03 2007 From: igor.tatarinov at gmail.com (igor.tatarinov at gmail.com) Date: Thu, 13 Dec 2007 14:53:03 -0800 (PST) Subject: python vs perl performance test References: <3b1cef63-f1dc-466c-bf8c-7613fb4b0c3f@a35g2000prf.googlegroups.com> Message-ID: <43f502fd-1e97-4ee9-b42d-d75151822345@s19g2000prg.googlegroups.com> On Dec 13, 1:23 pm, Jakub Stolarski wrote: > If all you need is the result here's simpler and more efficient code: > > from random import randrange > sum = 100 * randrange(128) > print "Sum is ", sum > > And the same in perl: > > my $sum = 100 * int(rand(128)); > print "Sum is $sum\n"; > > If you really want compare performance then look at Computer Language > Benchmarks Game:http://shootout.alioth.debian.org/gp4/benchmark.php?test=all?=pyt... Sorry, this wasn't meant to be a benchmark of any kind and I don't care about the results of the program. It was just an exercise to figure out why the verbatim translation was so slow. It looks like Python's randrange() is very slow. random() is much faster but then I have to use int(N*random()) to get an integer, which is pretty slow too. Initially, I thought the difference was due to Python's slicing implementation that doesn't seem to be the case: with fixed arguments Perl's substr() and Python's slicing seem to have identical performance. From bdesth.quelquechose at free.quelquepart.fr Sat Dec 8 13:44:18 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 08 Dec 2007 19:44:18 +0100 Subject: a Python person's experience with Ruby In-Reply-To: References: <17975.12459.qm@web33510.mail.mud.yahoo.com> Message-ID: <475ae612$0$645$426a34cc@news.free.fr> Colin J. Williams a ?crit : > Steve Howell wrote:> > Thanks for the interesting comparison. > > [snip] > >> 3) I actually like being able to omit parentheses in >> method definitions and method calls. In Ruby you can >> express "add(3,5,7)" as both "add(3,5,7)" and "add 3, >> 5, 7." The latter syntax is obviously more error >> prone, but I don't think I've ever actually gotten bit >> by it, and the code appears more clean to me. >> > [snip] > > I'm not sure that I like add 3, 5, 7 > > but it would be nice to be able to drop the parentheses > when no argument is required. > > Thus: close; > could replace close(); This just could not work given Python's object model. The parens actually *are* the call operator. From bj_666 at gmx.net Wed Dec 12 02:46:35 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Dec 2007 07:46:35 GMT Subject: Text widget updates only after calling method exits (threading issue?) References: Message-ID: <5s9hurF1810imU2@mid.uni-berlin.de> On Tue, 11 Dec 2007 17:58:37 -0800, mariox19 wrote: > If I am supposed to send messages to Tkinter objects only from the > main thread, how can I get the letters to appear 1 per second? Take a look at the `after()` method on widgets. Ciao, Marc 'BlackJack' Rintsch From xkenneth at gmail.com Fri Dec 7 17:37:29 2007 From: xkenneth at gmail.com (xkenneth) Date: Fri, 7 Dec 2007 14:37:29 -0800 (PST) Subject: Securely distributing python source code as an application? Message-ID: <7489fd22-e2dd-44b8-a35b-e2858fa36d32@b1g2000pra.googlegroups.com> Hi All, I'll shortly be distributing a number of python applications that use proprietary. The software is part of a much larger system and it will need to be distributed securely. How can i achieve this? Regards, Ken From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Dec 21 08:14:45 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 21 Dec 2007 14:14:45 +0100 Subject: Extract a number from a complicated string In-Reply-To: <5665e3d2-4f98-4b65-b396-0ec228657413@l1g2000hsa.googlegroups.com> References: <5665e3d2-4f98-4b65-b396-0ec228657413@l1g2000hsa.googlegroups.com> Message-ID: <476bbc02$0$3900$426a34cc@news.free.fr> Horacius ReX a ?crit : > Hi, > > I have to read some data from a file, and on each block it always > appears the followng string; xyz.vs.1-81_1 . It appears a lot of time > with different numbers like; > > xyz.vs.1-81_1 > xyz.vs.1-1234_1 > xyz.vs.1-56431_1 > > and so on > > My problem is that I need to extract from this string the number. For > instance in xyz.vs.1-81_1 I have to extract the number 81, and in > xyz.vs.1-1234_1 I need to get the number 1234. > > What is the easiest way of doing this ? Not necessarily the "easiest", but: >>> data = ['xyz.vs.1-81_1', 'xyz.vs.1-1234_1', 'xyz.vs.1-56431_1'] >>> for d in data: ... print d, ":", d.split('.')[2].split('-')[1].split('_')[0] ... xyz.vs.1-81_1 : 81 xyz.vs.1-1234_1 : 1234 xyz.vs.1-56431_1 : 56431 From yantao at telus.com Wed Dec 26 18:22:06 2007 From: yantao at telus.com (Peter Pei) Date: Wed, 26 Dec 2007 23:22:06 GMT Subject: save gb-2312 web page in a .html file In-Reply-To: References: Message-ID: You must be right, since I tried one page and it worked. But there is something wrong with this particular page: http://overseas.btchina.net/?categoryid=-1. When I open the saved file (with IE7), it is all messed up. url = 'http://overseas.btchina.net/?categoryid=-1' headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' } req = urllib2.Request(url, None, headers) page = urllib2.urlopen(req).read() htmlfile = open('btchina.html','w') htmlfile.write(page) htmlfile.close() From chris.monsanto at gmail.com Sun Dec 9 22:29:23 2007 From: chris.monsanto at gmail.com (Chris M) Date: Sun, 9 Dec 2007 19:29:23 -0800 (PST) Subject: Is a "real" C-Python possible? References: <7tOdnRb-5fMW_MHanZ2dnUVZ_tmhnZ2d@comcast.com> Message-ID: <072ae5ae-7e28-4fa2-b194-dbd9f9c4cba9@i29g2000prf.googlegroups.com> On Dec 9, 10:04 pm, Paul McGuire wrote: > On Dec 9, 6:07 pm, "Jack" wrote: > > > Plus, Psyco is not the > > main stream and has stopped development. > > > > What makes you think it has stopped development? I just swung by the > SF project page, and its most recent news post was just 2 months ago. > > Psyco may not be in the standard Python distribution, but it is > definitely a fixture of the Python landscape, which is about as close > to main stream as you can get. > > -- Paul Maybe because of this line: "Psyco is a reasonably complete project. I will not continue to develop it beyond making sure it works with future versions of Python. My plans for 2006 are to port the techniques implemented in Psyco to PyPy. PyPy will allow us to build a more flexible JIT specializer, easier to experiment with, and without the overhead of having to keep in sync with the evolutions of the Python language." From beijingjing at gmail.com Wed Dec 5 13:58:00 2007 From: beijingjing at gmail.com (beijingjing at gmail.com) Date: Wed, 5 Dec 2007 10:58:00 -0800 (PST) Subject: Welcome to us the website Message-ID: Madam/Dear Sir We are one of the largest wholesaler in China who mainly sell stylish electronic product and equipment such as Digital Cameras, Mobile Phone, Laptops, Mp4, GPS, Digital Video and bulk product such as LCD TV, Motorcycles, Binoculars and Musical Instruments and so on with various international famous brand. We offer our customer good valuable product with very compteted price because we have advanced goods circulating solution and supporter. We have our own warhouse and stores, our clients all over the world. When you choose our products you will also enjoy our fast delivery. We appreciate all of customers' comments and will continue to improve our service in order to satisfied our old and new customer. During Christmas and New Year Holiday we have a various promtotion plan. It will be out soon. Please welcome to visit our websit www.bdaopy.com to check your voucher. Thanks MSN:bdaopy at hotmail.com E-mail:bdaopy at hotmail.com From paddy3118 at googlemail.com Sun Dec 9 05:55:37 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 9 Dec 2007 02:55:37 -0800 (PST) Subject: Recommendations for writing a user guide with examples? References: Message-ID: <3aaf641b-4f83-4895-aeae-10138d4e6d19@e67g2000hsc.googlegroups.com> On Dec 8, 9:22 pm, Neal Becker wrote: > I'm looking for recommendations for writing a user manual. It will need > lots of examples of command line inputs and terminal outputs. > > I'd like to minimize the effort to integrate the terminal input/output into > my document. I have lots of experience with latex, but I wonder if there > may be some other choices. Maybe docutils, pydoc, something else? The > code I'm documenting is written in python, if that matters. Doctest and restructuredtext. http://docutils.sourceforge.net/docs/user/rst/quickref.html - Paddy. From horpner at yahoo.com Fri Dec 14 16:15:44 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 14 Dec 2007 21:15:44 GMT Subject: container.___le___ can use only <=? Message-ID: When implementing the rich comparison operators for some sort of container, it's tempting to save code by doing something like: class LarchTree: ... def __gt__(self, other): # A lot of code to traverse the tree def __le__(self): return not self > other However, if I'm thinking correctly, this is a bad idea. The reasoning being that > and <= are not required to be each others opposite for arbitrary value types, and may not even both be supplied by the contained objects. If a LarchTree user stores objects that don't support __gt__, will he have a legitimate complaint when using LarchTree.__le__ results in an attribute error? -- Neil Cerutti From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Dec 4 11:04:36 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 04 Dec 2007 17:04:36 +0100 Subject: read lines In-Reply-To: References: <47555ab4$0$31357$426a74cc@news.free.fr> Message-ID: <47557a93$0$5448$426a74cc@news.free.fr> Peter Otten a ?crit : > Bruno Desthuilliers wrote: > >> # You don't need to read the whole file in memory > >> lines1, lines2 = tee(infile) >> print min(extract_numbers(lines1)), max(extract_numbers(lines2)) > > tee() internally maintains a list of items that were seen by > one but not all of the iterators returned. Therefore after calling min() > and before calling max() you have a list of one float per line in memory > which is quite close conceptually to reading the whole file in memory. > > If you want to use memory efficiently, stick with the for-loop. Indeed - I should have specified that the second version was not necesseraly better wrt/ either perfs and/or resources usage. Thanks for having made this point clear. From paul.nospam at rudin.co.uk Wed Dec 12 13:03:18 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Wed, 12 Dec 2007 18:03:18 +0000 Subject: Newbie NameError problem References: <877ijj5018.fsf@rudin.co.uk> <9cb09020-247f-48a6-a0f9-9742e7c84358@x69g2000hsx.googlegroups.com> Message-ID: <873au74wpl.fsf@rudin.co.uk> cokofreedom at gmail.com writes: > On Dec 12, 5:51 pm, Paul Rudin wrote: >> MartinRineh... at gmail.com writes: >> > I don't understand what I don't understand in the following: >> >> I haven't tried to understand what your code is doing - but the >> NameError arises because you try to use Loc before its definition. Put >> the definition first and the error should go away. > > Class Loc must be placed ABOVE the code that uses it. Isn't that what I said? From newsgroups at debain.org Mon Dec 3 05:26:50 2007 From: newsgroups at debain.org (Samuel) Date: Mon, 3 Dec 2007 10:26:50 +0000 (UTC) Subject: Generating API documentation as a textfile Message-ID: Does anyone know an easy way to extract the API documentation that is embedded into a Python file as a text file? -Samuel From sjmachin at lexicon.net Sat Dec 15 23:24:29 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 15 Dec 2007 20:24:29 -0800 (PST) Subject: Inter-process communication, how? References: <13m90jvnpbi6m41@corp.supernews.com> Message-ID: On Dec 16, 2:34 pm, ecir.h... at gmail.com wrote: > > If it is a one-shot (spawn sub, wait, retrieve results) you could > > generate a temporary file name in the parent, pass that name to the sub > > when invoking it, wait for the sub to complete (giving you a status > > code) and then read the result the sub has written to the file. > > Yes, it's once shot. But how do I pass "that name"? > From all the arguments of class Popen (http://docs.python.org/lib/ > node529.html) perhaps I could use "env" only. Or am I wrong? Yes. Consider this: If you were to run your calculation script from the shell prompt [strongly recommended during testing], how would you tell it the name of the file? Now look at the docs again. > > PS: both with mmpam and temp file you probably meant that I should > hard code some as-weirdest-filename-as-possible two both programs but > what if I run the computation several times? That's mmap, not mmpam. No, Dennis didn't mean that you should hard code a filename. Have a look at the tempfile module. > > And thanks for reply! > > > > > Or, you could have parent and sub both mmap the same "file", > > essentially passing data in memory unless it becomes too large and pages > > out to swap disk. You might even be able to do bidirectional and dynamic > > updates (rather than waiting for the sub to exit)... Define, say, an > > epoch count for each process -- these would be the first two words of > > the mmap file > > > |p-epoch|s-epoch|n-words of p-data (fixed constant known to both)|n-words of s-data| > > > periodically the parent would examine the value of s-epoch, and if it > > has changed, read the s-data.. (both sides write the data first, then > > update the epoch count). When the epoch stays the same and two > > consecutive reads of the data match, you have stable data (so the reads > > should occur more often than updates) and can process the data > > transferred. > > > OR, you could have the parent open a TCP/IP socket as a server, and > > pass the socket port number to the sub. The sub would then connect to > > that port and write the data. For bidirectional you could pass the > > parent port, and the sub's first action is to connect and pass a port > > that it will be monitoring. > > > On a VMS system, the processes would connect to named "mailboxes" > > and use QIO operations to pass data between them. > > > On an Amiga you'd use "message ports" (which operated somewhat > > similar to VMS mailboxes except that mailboxes had an independent > > existence, multiple processes can read or write to them -- message ports > > were readable by the creating process, but could have messages sent from > > anywhere; typically passing the message port [address of a linked list > > of messages] for replies). Or a higher level message port: an ARexx > > port. > > > On a Windows NT class system, the win32 extensions allow access to > > Windows Named Pipes... Or maybe the Windows clipboard could be used... > > -- > > Wulfraed Dennis Lee Bieber KD6MOG > > wlfr... at ix.netcom.com wulfr... at bestiaria.com > > HTTP://wlfraed.home.netcom.com/ > > (Bestiaria Support Staff: web-a... at bestiaria.com) > > HTTP://www.bestiaria.com/ From deets at nospam.web.de Mon Dec 3 05:17:06 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Dec 2007 11:17:06 +0100 Subject: Thread References: Message-ID: <5ri3d2F14hnb3U2@mid.uni-berlin.de> Gianmaria Iaculo - NVENTA wrote: > > Hi all, > i'm using python 1.5.2. > > Is it possible to use the Thread module? I need it for the Timer library. According to http://www.python.org/doc/1.5.2/lib/lib.html it's there. Why don't you just import it and try? Would have cost less time than posting here & waiting for an answer (This is not meant to be discouraging you posting here - just showing you that in Python, trying first is often easier than "gathering intelligence" first) Diez From gagsl-py2 at yahoo.com.ar Sun Dec 30 09:57:26 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Dec 2007 12:57:26 -0200 Subject: What is the best way to do dynamic imports ? References: Message-ID: En Sun, 30 Dec 2007 12:24:53 -0200, escribi?: > I'm playing with some mod_python and web development. And in me code I > need to do som dynamic imports. > Right now I just do a: > > exec 'import '+some_modulename > > But it seems to easy, is there a "dark side" to doing it this way? > (memory use,processing ,etc) Use __import__, specially if some_modulename comes from the outside. What if some_modulename contains "modulename\nsome_nasty_function_call()" > And have to I check if the modul is already loaded? Not needed; the standard import machinery already does that. > Another thing is how to call my dynamic imported moduls. > Now I use exec (as with my modules), like this: > > exec 'newclass = '+classname+'()' > newclass.somefunction() > > Again it seems to easy. Is there a better/proper way to do it? Use getattr to obtain the desired class from the containing module, then use it as any other class: the_module = __import__(some_modulename) the_class = getattr(the_module, classname) o = the_class() o.somefunction() Never use exec/eval and friends - and never ever use them in a web application! > Do anybody now a good howto or tutorial to this? No... what do you want covered? > Many thanks and hope you all have a happy new year :-) Thanks, and a happy new year for you too! -- Gabriel Genellina From stanc at al.com.au Thu Dec 13 00:11:41 2007 From: stanc at al.com.au (Astan Chee) Date: Thu, 13 Dec 2007 16:11:41 +1100 Subject: python "sounds-like" module In-Reply-To: References: Message-ID: <4760BF0D.2080907@al.com.au> John Machin wrote: > Someone is sure to trot out the hoary old soundex ... believe me, it's > teh suxxor. > > Plus febrl has soundex in it (as well as several modified versions of it) among other things. Looks like this is what Im looking for. Thanks! Astan From sndive at gmail.com Thu Dec 6 21:22:20 2007 From: sndive at gmail.com (sndive at gmail.com) Date: Thu, 6 Dec 2007 18:22:20 -0800 (PST) Subject: PyImport_ImportModule("foo.bar") Message-ID: <3404abed-6af0-48be-8d6a-a2457c729b52@x69g2000hsx.googlegroups.com> I'm trying to import foo.bar in order not to add every single directory with python files to the search path. i immediately follow the import with the PyModule_AddObject call to put the imported module to __main__ module but later on PyEval_EvalCode on Py_CompileString compiled code "foo.bar.baz()" and dictionary of __main__ used for global and local context does not work (I get NameError). is there an equivalent of import foo.bar as Bar; in c api or should i call into submodules differently? From trekker182 at comcast.net Sun Dec 9 12:48:04 2007 From: trekker182 at comcast.net (Shawn Minisall) Date: Sun, 09 Dec 2007 12:48:04 -0500 Subject: a way to keep track of # of clicks Message-ID: <475C2A54.7000400@comcast.net> Is there a way to keep track of the number of times someone clicks on a menu item in a prorgam? What I want to do is make the rectangle disappear after they click on it at the main menu 3 times so visually show them they can't do it any longer. Since I appended the button to a main menu list, I would think undrawing it would have something like pop.mainMenuList[8] in it after they click on it three times. (not in succession, after it takes them to the questions screen and then back to the main menu) Any suggestions? thx From tjreedy at udel.edu Sat Dec 8 16:25:04 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 8 Dec 2007 16:25:04 -0500 Subject: Newbie edit/compile/run cycle question References: <1f995159-fc02-4cd1-aa99-7f8500eeaeec@b1g2000pra.googlegroups.com> Message-ID: wrote in message news:1f995159-fc02-4cd1-aa99-7f8500eeaeec at b1g2000pra.googlegroups.com... | What don't I know that I should know to just edit/run, preferably at | the tap of a function key? In IDLE, which come with Python, it is F5. (See Options/General/Autosave) Startup is about .1 sec since the program runs in a window of the same interpreter. Stand-alone editors require longer to start a separate interpreter, but then you have a clean new interpreter that is not running TK or anything else. Your choice. Have fun. If you run a separate interpreter, you might benefit from also having an interactive interpreter window open in which to run quick experiments to check names or syntax you are not sure of. This comes with running idle. tjr From timr at probo.com Sun Dec 9 02:24:16 2007 From: timr at probo.com (Tim Roberts) Date: Sun, 09 Dec 2007 07:24:16 GMT Subject: how to convert 3 byte to float References: <475a7336$0$13116$9b4e6d93@newsspool2.arcor-online.net> <5rvc6hF17032iU1@mid.individual.net> <475a8591$0$17533$9b4e6d93@newsspool4.arcor-online.net> Message-ID: "Mario M. Mueller" wrote: >Bjoern Schliessmann wrote: > >[...] >> BTW, who in his mind designs three byte floats? Memory isn't that >> expensive anymore. Even C bool is four bytes long. > >It's output of a digitizer (but not that old). I was also wondering about >the reason for this limitation (maybe the design is ~20 years old). The IEEE-754 standard was adopted in 1985. Before that (and after that, too), many people used whatever bit layout they wanted for floating point numbers. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From lars at larsjohansen.org Fri Dec 7 03:37:22 2007 From: lars at larsjohansen.org (Lars Johansen) Date: Fri, 07 Dec 2007 09:37:22 +0100 Subject: Any simpler way to do this Message-ID: <1197016642.2753.4.camel@lars-laptop.ez.no> I have a function that looks like this: def Chooser(color): if color == "RED": x = term.RED elif color == "BLUE": x = term.BLUE elif color == "GREEN": x = term.GREEN elif color == "YELLOW": x = term.YELLOW elif color == "CYAN": x = term.CYAN elif color == "MAGENTA": x = term.MAGENTA return x Wouldn there been easier if I could just skip all the "*if's" and just "return term.color", however this gives a syntax error, are there any clever way to do this ? -- Lars Johansen From martin at v.loewis.de Wed Dec 19 04:55:01 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 19 Dec 2007 10:55:01 +0100 Subject: Static linking of python and pyqt In-Reply-To: References: Message-ID: <4768EA75.7050109@v.loewis.de> > I'm trying to link python statically with qt and pyqt. I've tried this in > several ways but never succeeded. At the moment the final make runs without > errors but I get import errors when accessing pyqt. > How can I solve this problem? You'll need to include QtCore into Modules/config.c, preferably by adding it to Modules/Setup.local. HTH, Martin From nytrokiss at gmail.com Thu Dec 27 17:48:03 2007 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 27 Dec 2007 23:48:03 +0100 Subject: Cheat sheet In-Reply-To: <13n886h5u1f2913@corp.supernews.com> References: <13n886h5u1f2913@corp.supernews.com> Message-ID: <8a6b8e350712271448x1a8b0f9cne4e6c4e581ebe8a2@mail.gmail.com> Looks good thanks! On Dec 27, 2007 11:06 PM, Scott David Daniels wrote: > Riccardo T. wrote: > > I wrote a little cheat sheet for this wonderful language, but because of > > my still little experience with it, I would like to have a feedback > > Could you have a look at it and tell me what do you think about, please? > > > > http://greyfox.imente.org/index.php?id=73 > > > > -- > > GreyFox > > [in the .png] > > ... > > Callable types > > ... > > User-definet methods > > I personally prefer "User-defined methods" > > > ... > > Class instances > I'd try: > Class instances with a __call__ method. > > > ... > > Classes > > Classes Instances > > This probably wants to be > Class Instances > > "file" objects are generally supposed to be built with the > open function, not instantiated as shown. > Also note iterating on a file gets the lines. > > Do you know about seq[i:] and seq[::-1]? > > --Scott David Daniels > Scott.Daniels at Acm.Org > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From digitnctu at gmail.com Thu Dec 27 09:05:16 2007 From: digitnctu at gmail.com (digitnctu at gmail.com) Date: Thu, 27 Dec 2007 06:05:16 -0800 (PST) Subject: interactive mode in python with ctypes??? References: <09cb597a-6674-40b8-a93f-aeecbb38a69b@d21g2000prf.googlegroups.com> Message-ID: <8d1e011e-54d7-48ea-a169-43ce2745ced7@l6g2000prm.googlegroups.com> On 12??27??, ????4?r40??, "Gabriel Genellina" wrote: > En Wed, 26 Dec 2007 12:57:44 -0300, escribi??: > > > libdll.dll is a third-party library. The below code segment will > > run well under the batch mode(ie. python test.py 11060) > > but when I type sequencially it doesn't work as usual. Can any > > give me a hand?? > > Define "doesn't work as usual"; at least describe what actually happens > and what you expected to happen instead. If you get an exception, post the > full traceback. > > > run(string.atoi(sys.argv[1])) > > string.atoi is deprecated eons ago; use int() instead > > -- > Gabriel Genellina "doesn't work" means there is no result without exception. The python interpretter still run without complains; but when running under batch mode it run as the expectation. Are there difference for python interpretter between batch mode and interactive mode ? Thanks for Gabriel. From sjmachin at lexicon.net Sat Dec 1 17:31:56 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 1 Dec 2007 14:31:56 -0800 (PST) Subject: "Python" is not a good name, should rename to "Athon" References: <78bdd499-a263-4c68-8e43-e3e59b111c7e@a39g2000pre.googlegroups.com> <5rcq90F13re18U1@mid.individual.net> <2bd39781-94e2-4d3d-b185-47a247d3acc2@d27g2000prf.googlegroups.com> Message-ID: <20a6e1c5-a865-45f4-b511-59ebd734ac74@e10g2000prf.googlegroups.com> On Dec 2, 8:40 am, "Russ P." wrote: > > None. None of them are good names by my criteria. But then, a name is > only a name. One of the few names I like is Pascal, because he was a > great mathematician and scientist. > > After thinking about it a bit, here are examples of what I would > consider a good name for a programming language: > > Newton# > Newton* > Newton+ > > Newton was a great scientist, and his name is easy to spell and > pronounce. Should be, but a large proportion of the population pronounce it so that it rhymes with "hootin" as in "hootin n hollerin" :-) From arnodel at googlemail.com Sun Dec 9 08:39:27 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 9 Dec 2007 05:39:27 -0800 (PST) Subject: Newbie edit/compile/run cycle question References: <1f995159-fc02-4cd1-aa99-7f8500eeaeec@b1g2000pra.googlegroups.com> Message-ID: On Dec 9, 1:26 pm, MartinRineh... at gmail.com wrote: > Thanks for all the help. Thought I'd spend my newbie days right in the > Python shell (there's lots to test when you're just starting) but I > guess that's not going to happen. It would be a shame not to use the shell. > Everyone told me to get out of the Python shell, one way or another. > OK. But this means that every execution must first load Python, then > import my stuff. Import becoming a NOP after first use in the shell is > a six-legged feature, at best. Don't jump to conclusions too early. In the shell, type 'help(reload)'. This might help. -- Arnaud From bignose+hates-spam at benfinney.id.au Tue Dec 11 05:49:11 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 11 Dec 2007 21:49:11 +1100 Subject: Job Offer: Python Ninja or Pirate! References: Message-ID: <87hcip5wwo.fsf@benfinney.id.au> "jay at etsy.com" writes: > Just a few months ago, we found a few amazingly talented ninjas and > even a few swarthy pirates. The team is doing wonderfully, and we're > hoping to add a few more adventure-loving souls to our ranks. For job postings, please don't use the mailing lsits. Instead, make use of the Python Job Board . -- \ "Remember: every member of your 'target audience' also owns a | `\ broadcasting station. These 'targets' can shoot back." -- | _o__) Michael Rathbun to advertisers, news.admin.net-abuse.email | Ben Finney From deets at nospam.web.de Mon Dec 3 17:44:10 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Dec 2007 23:44:10 +0100 Subject: "Python" is not a good name, should rename to "Athon" In-Reply-To: References: <47546949$0$31456$426a74cc@news.free.fr> Message-ID: <5rjf5rF155hc9U1@mid.uni-berlin.de> Russ P. schrieb: > On Dec 3, 1:58 pm, "Dan Upton" wrote: > >> ...and thus, maybe the joke is on you? Just to play devil's advocate... > > Yes, the joke *is* on me -- every time I have to explain to someone > why I am using this funny-sounding language. That's the point. Yeah, but today you drank Java, your favourite Coffe blend, while telling your best buddy you plan to get Groovy tonight with Ada, buying her a Ruby collier & explaining her some Basic concepts of computer science - because that always makes her express her astonishment about your mad coding skillz with that cute little Lisp she has. Just don't forget to not use a Clipper in front of her again. She only forgave you for that because you tooke her to the Eiffel Tower, meeting Pascal there. He just got his degree from Haskell university - which is a major break-through, because all of his professors working on a Scheme to expel him from there. But he showed it to these little Brainfucks. Sorry, but if people are joking on you - there must be other reasons for that than a name of a programming language. And I'm beginning to think I know it.... Diez From steve at REMOVE-THIS-cybersource.com.au Sat Dec 29 19:37:32 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Dec 2007 00:37:32 -0000 Subject: Tab indentions on different platforms? References: <14a26d3f-94de-4887-b3f4-d837a2723f35@21g2000hsj.googlegroups.com> Message-ID: <13ndq2ca87epk79@corp.supernews.com> On Sat, 29 Dec 2007 15:29:25 +0000, Thorsten Kampe wrote: > I'd personally go for spaces because: > > 1. I don't like things I cannot see (control characters) You can see spaces but not tabs? Your editor is pretty weird. In all the editors I've every used, both spaces and tabs show up as empty white space. (Or coloured space if I set the editor to use a coloured background.) > 2. I never had problems with spaces but plenty with tabs Periodically, I ask on this list what problems people have with tabs. (I'm fully aware that mixing tabs and spaces is a Bad Thing.) I've had little luck getting any answer except "Tabs are bad, m'kay?". I'm only aware of two problems that some people run into due to the consistent use of tabs rather than spaces. * Some news clients don't display tabs correctly, thus making it hard to copy and paste code direct out of the news reader into your source; (But of course if you copy code using spaces, and the number of space characters used per indent level doesn't match your source code, you'll have problems too.) * Some applications "helpfully" convert tabs into spaces, thus meaning that when copy code from them, you end up with spaces instead of tabs. What problems have you had with tabs that aren't related to buggy applications or users that mix tabs and spaces? -- Steven From cwitts at gmail.com Tue Dec 11 13:13:19 2007 From: cwitts at gmail.com (Chris) Date: Tue, 11 Dec 2007 10:13:19 -0800 (PST) Subject: problem parsing lines in a file References: Message-ID: <6c45d9a9-d724-4bfa-bcab-c706d5461ca0@o6g2000hsd.googlegroups.com> On Dec 11, 7:25 pm, barronmo wrote: > I'm having difficulty getting the following code to work. All I want > to do is remove the '0:00:00' from the end of each line. Here is part > of the original file: > > 3,3,"Dyspepsia NOS",9/12/2003 0:00:00 > 4,3,"OA of lower leg",9/12/2003 0:00:00 > 5,4,"Cholera NOS",9/12/2003 0:00:00 > 6,4,"Open wound of ear NEC*",9/12/2003 0:00:00 > 7,4,"Migraine with aura",9/12/2003 0:00:00 > 8,6,"HTN [Hypertension]",10/15/2003 0:00:00 > 10,3,"Imerslund syndrome",10/27/2003 0:00:00 > 12,4,"Juvenile neurosyphilis",11/4/2003 0:00:00 > 13,4,"Benign paroxysmal positional nystagmus",11/4/2003 0:00:00 > 14,3,"Salmonella infection, unspecified",11/7/2003 0:00:00 > 20,3,"Bubonic plague",11/11/2003 0:00:00 > > output = open('my/path/ProblemListFixed.txt', 'w') > for line in open('my/path/ProblemList.txt', 'r'): > newline = line.rstrip('0:00:00') > output.write(newline) > output.close() > > This result is a copy of "ProblemList" without any changes made. What > am I doing wrong? Thanks for any help. > > Mike rstrip() won't do what you think it should do. you could either use .replace('0:00:00','') directly on the input string or if it might occur in one of the other elements as well then just split the line on delimeters. In the first case you can do. for line in input_file: output_file.write( line.replace('0:00:00','') ) in the latter rather. for line in input_file: tmp = line.split( ',' ) tmp[3] = tmp[3].replace('0:00:00') output_file.write( ','.join( tmp ) ) Hope that helps, Chris From devicerandom at gmail.com Wed Dec 12 10:04:09 2007 From: devicerandom at gmail.com (massimo s.) Date: Wed, 12 Dec 2007 07:04:09 -0800 (PST) Subject: Is anyone happy with csv module? References: <15ab759b-0aec-45dd-88b9-c446c2b7d299@e10g2000prf.googlegroups.com> Message-ID: <40d6ad04-7ea3-42d5-b10c-3c829779d304@e10g2000prf.googlegroups.com> On Dec 12, 2:58 pm, Neil Cerutti wrote: > On 2007-12-11, massimo s. wrote: > > > Hi, > > > I'm struggling to use the python in-built csv module, and I > > must say I'm less than satisfied. Apart from being rather > > poorly documented, I find it especially cumbersome to use, and > > also rather limited. What I dislike more is that it seems > > working by *rows* instead than by *columns*. > > It is very *thoroughly* documented, which is a style that won't > suit every purpose. > > So I have some questions: > > 1) Is there a good tutorial, example collection etc. on the csv > > module that I'm missing? > > Just skip to 9.1.5 Examples, and you'll be on your way. If by "thoroughly" you mean "it actually describes technically what it is and does but not how to really do things", yes, it is thoroughly documented. The examples section is a joke. It gives good examples for the simplest usage cases (good), then it almost immediately digs into details like the Unicode stuff, leaving aside the rest. DictWriter and DictReader are absent from the examples. And also the Sniffer. And, as a sidenote, why putting something useful like the unicode decoder-encoders in the example section instead of inserting them directly in the library? I don't want to be mean with the author of csv and its docs. I now understand there are excellent reasons for csv to be done the way it is, and it's only my fault if I didn't see that before. I also know first hand that documenting code is hard and boring stuff. Kudos to anyone doing that, but in the Example section there is surely room for improvement. It's probably OK for people doing things row-by-row and that already know perfectly their way in and out all that, but if this thread teaches us something, is that the same thing can be used for vastly different purposes. I will try to submit a patch to the documentation based on examples coming from here and what I will learn by digging into csv. > > 3) In case anyone else is as unhappy as me, and no tutorial > > etc. enlighten us, and no alternative is present, anyone is > > interested in an alternative csv module? I'd like to write one > > if it is the case. > > I was intimidated by it at first, implemented my own reader > (mostly as a fun parsing exercise), used that for a while, and > then threw it out. > > I advise you to spend time staring at the examples, and use the > simplest example the suits your needs. Also search this archives > of this group for examples. OK, thanks! As for people advicing xlrd/xlrwt: thanks for the useful tip, I didn't know about it and looks cool, but in this case no way I'm throwing another dependency to the poor users of my software. Csv module was good because was built-in. m. From mensanator at aol.com Fri Dec 7 16:17:07 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Fri, 7 Dec 2007 13:17:07 -0800 (PST) Subject: Converting Excel time-format (hours since 1.1.1901) References: <6c5cc79e-a121-45c5-9a97-b8564ca9f3bf@l16g2000hsf.googlegroups.com> <716882bb-ab0f-4eb5-b577-1f12372d7b93@w56g2000hsf.googlegroups.com> <6653408b-7b2e-4acb-968a-f06d37ef064e@t47g2000hsc.googlegroups.com> Message-ID: <93837c98-b7f9-4461-9201-7d73a1470c03@l1g2000hsa.googlegroups.com> On Dec 7, 9:59?am, Dirk Hagemann wrote: > On 7 Dez., 16:50, Dirk Hagemann wrote: > > > > > > > On 7 Dez., 16:21, Tim Golden wrote: > > > > mensana... at aol.com wrote: > > > > On Dec 7, 7:20?am, Dirk Hagemann wrote: > > > >> Hello, > > > > >> From a zone-file of a Microsoft Active Directory integrated DNS server > > > >> I get the date/time of the dynamic update entries in a format, which > > > >> is as far as I know the hours since january 1st 1901. > > > > If it *is* then the easiest way is this: > > > > > > > import datetime > > > print datetime.date (1901, 1, 1) + datetime.timedelta (hours=3566839) > > > > > > > > But, as someone pointed out, that puts you somewhere in 2300. > > > Where are you getting the 1901 from (and the hours, for that > > > matter). If it's based, as AD dates are, for example, from 1601, > > > then the calc becomes: > > > > > > > import datetime > > > print datetime.date (1601, 1, 1) + datetime.timedelta (hours=3566839) > > > > > > > > which looks more realistic. But frankly I'm guessing. > > > > TJG > > > (3566839/24)/365 = 407 ? - YES I did this calculation too and was > > surprised. But if you try this out in MS Excel: > > ?="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0) ?(put > > 3566839 in field A1 and switch the format of the result-fieldby right- > > click on it to the > > date format "14.3.01 13:30") > > > and then replace 3566839 by, let's say, "2", Excel calculates the date > > 01.10.1901 2:00 AM. Try out other values like 5 or 24! So I thought > > 3566839 represents hours. > > > Dirk > > Oh - sorry again: in the Excel formula replace also ZEIT with TIME Also, Excel unformatted dates are DAYS, not hours. And it's from 1900, not 1901. Hours are always fractional parts: 1/1/01 0:00 367 1/1/01 12:00 367.5 It sure sounds like the number being given you ISN'T the same as Excel date serial numbers. From jstroud at mbi.ucla.edu Fri Dec 21 04:59:57 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 21 Dec 2007 01:59:57 -0800 Subject: Why does __builtins__ mean different things... In-Reply-To: References: Message-ID: Erik Max Francis wrote: > James Stroud wrote: > >> Thank you for your help. I will import the __builtin__ module as you >> have suggested--it is what I need. >> >> But....what the heck? You mean if I drop an s I get predictable >> behavior and if I don't, I get unpredictable behavior? > > You don't get unpredictable behavior, you just get different behavior > you didn't expect, which is not the same thing. Python is a programming > language, like any other; randomly dropping letters in names is going to > result in bad behavior, so be more careful about it. Are you responding to some other thread? Its like you read every other word and then filled in the rest randomly... -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From jeremy at omba.demon.co.uk Sat Dec 8 21:45:46 2007 From: jeremy at omba.demon.co.uk (Jeremy C B Nicoll) Date: Sun, 9 Dec 2007 02:45:46 +0000 Subject: Newbie edit/compile/run cycle question References: Message-ID: Steve Howell wrote: > > --- Jeremy C B Nicoll wrote: > > What command (in XP) does one need to issue to > > syntax check a saved python > > script without running it? > > Perhaps oversimplifying a bit, running "python" does a > syntax check, and if it passes, moves on the next > steps of interpretation/execution. Ah, I've been using IDLE so far (but would probably prefer to write Python in my normal text editor). In IDLE Alt-X syntax checks the saved copy of the file being edited (at least it seems to), and I was wondering how to replicate that elsewhere. > > Does a syntax check report all syntax errors or just > > the first one found? > > Just the first one. In practice, you end up fixing > them one at a time anyway, so this works for me, as > long as I have a fluid way to call out to python and > return to the editor. Yes, I suppose so. -- Jeremy C B Nicoll - my opinions are my own. From bdesth.quelquechose at free.quelquepart.fr Fri Dec 28 13:33:00 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 28 Dec 2007 19:33:00 +0100 Subject: OOP: How to implement listing al 'Employees'. In-Reply-To: <77fbd06e-4692-4a6c-9251-986f41cae1ee@r60g2000hsc.googlegroups.com> References: <6a600f6a-76f1-4397-9fc8-6f5bab63913a@f53g2000hsg.googlegroups.com> <5tk95uF1dmpvkU1@mid.individual.net> <77fbd06e-4692-4a6c-9251-986f41cae1ee@r60g2000hsc.googlegroups.com> Message-ID: <4775415b$0$19658$426a74cc@news.free.fr> Petar a ?crit : > On 28 dec, 13:40, Bjoern Schliessmann mail-0306.20.chr0n... at spamgourmet.com> wrote: > >>Petar wrote: >> >>>What is the better way of doing this? And should a class always >>>reference only on 'item'? >> >>It fully depends on what you want to do in your program. If you just >>want to have a list of employees, a list or dict will suffice. If >>you need a full-fledged employee database, an "Employees" class may >>be a good API. >> (snip) > > It's a pure hypothetical question about where to put the function for > the list of employees when already having a Employee class. The problem with "pure hypothetical" questions is that they usually have no single good answer, and sometimes even no answer at all. Now since you're talking database, the most common patterns seems to have either some YourDomainClassNameHere methods to query instances, or some module/singleton object providing such querying interfaces for the whole app (or FWIW to provide both, the first calling on the second...). > Do I make it a method of the class, or do i create a instance of the > class for every employee (sitting inside a list)? If you have an Employee class, I don't get how you would avoid creating an instance for each and every, well, instance ? Unless you're thinking about something like MS "recordsets" ? But then, you don't need any domain class at all... From matiassurdi at gmail.com Mon Dec 17 12:20:38 2007 From: matiassurdi at gmail.com (Matias Surdi) Date: Mon, 17 Dec 2007 18:20:38 +0100 Subject: Getting al classes inside a package Message-ID: How can I get all the clasess inside a package (including it subpackages) ? for example, I have a package with classes A and B and with a subpackage wichs has class C. How can I get a list (and a path) of the classes that exists under the root package ? Thanks a lot! From duncan.booth at invalid.invalid Tue Dec 18 13:14:06 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Dec 2007 18:14:06 GMT Subject: Best idiom to unpack a variable-size sequence References: <3c91f3c1-3eb0-4aa0-a136-a99ac361f80c@1g2000hsl.googlegroups.com> Message-ID: ram wrote: > Here's a little issue I run into more than I like: I often need to > unpack a sequence that may be too short or too long into a fixed-size > set of items: > > a, b, c = seq # when seq = (1, 2, 3, 4, ...) or seq = (1, 2) > > What I usually do is something like this: > > a, b, c = (list(seq) + [None, None, None])[:3] > > but that just feels rather ugly to me -- is there a good Pythonic > idiom for this? Pythonic might be to be explicit: i.e. know in advance how long the sequence actually is. One drawback I see with your code is that it doesn't give you any way to specify different defaults for the values. So here's an alternative to consider: try passing your sequence to a function. This lets you specify appropriate defaults, and it reads quite cleanly. Of course it also forces you to extract the code using those variables out into a separate function, but that may not be a bad thing. >>> def process(a=None, b=None, c=None): print a, b, c >>> seq = iter('abcd') >>> process(*itertools.islice(seq,0,3)) a b c >>> seq = iter('ab') >>> process(*itertools.islice(seq,0,3)) a b None >>> From a24061 at ducksburg.com Fri Dec 21 05:43:02 2007 From: a24061 at ducksburg.com (Adam Funk) Date: Fri, 21 Dec 2007 10:43:02 +0000 Subject: Does fileinput.input() read STDIN all at once? References: <940l35-7lu.ln1@news.ducksburg.com> Message-ID: On 2007-12-20, Tim Roberts wrote: >>As a test, I tried this: >> >> for line in fileinput.input(): >> print '**', line >> >>and found that it would print nothing until I hit Ctl-D, then print >>all the lines, then wait for another Ctl-D, and so on (until I pressed >>Ctl-D twice in succession to end the loop). > > Note that you are doing a lot more than just reading from a file here. This > is calling a function in a module. Fortunately, you have the source to > look at. > > As I read the fileinput.py module, this will eventually call > FileInput.next(), which eventually calls FileInput.readline(), which > eventually calls stdin.readlines(_bufsize). The default buffer size is > 8,192 bytes. OK, I think I've got this figured out! I'll keep using fileinput.input() for the normal case (reading from files named as arguments) and use sys.stdin.readline() for testing (reading from the keyboard, when no filenames are given). Thanks to you and Jonathan for your advice. From Lie.1296 at gmail.com Sat Dec 22 08:17:47 2007 From: Lie.1296 at gmail.com (Lie) Date: Sat, 22 Dec 2007 05:17:47 -0800 (PST) Subject: Odd behavior in Python/Tkinter? References: <3e6fc1b0-ac5e-42ed-8fe1-76da015c46ac@i29g2000prf.googlegroups.com> Message-ID: <9eab04df-1ad0-4ede-aead-70c8128ec5a3@e25g2000prg.googlegroups.com> On Dec 22, 7:35?pm, Fredrik Lundh wrote: > Lie wrote: > > But an expression (e.g. string) is NOT a variable. > > in this case, it is. ?I don't know if it's worth spending more time on > this, since you're not listening, but let's make one more attempt. Sure I'm listening (well, actually I'm reading), but please spare me since I can't understand what you meant in the previous posts (I'm just starting Python, and yesterday was my first introduction to Tkinter/Tk/Tcl). Everyone has their own newbie moments... > for the Entry widget, the "textvariable" argument, if given, identifies > an *internal* Tkinter variable (managed by the embedded Tcl inter- > preter, not Python). ?changes to this variable will be reflected in the > widget, and changes to the widget will be reflected in the variable. That clears things up. I never realized that we can even specify the name for the Tcl's variable, setting its values is a behavior, but setting its name is... some kind of incomplete encapsulation (well its understandable, complete encapsulation is never a Pythonic thing and proper ways to keep the encapsulation is available [through StringVar]). > the *usual* way to create such a variable is to use StringVar, and leave > it to Tkinter to come up with an internal variable name, but you can > refer to any Tcl variable; if it doesn't exist, it's created. > > in your example, you told both widgets to use the same internal > variable. ?you can do the same thing with a StringVar: > > ? ? ?var = Tk.StringVar() > > ? ? ?e1 = Tk.Entry(root, textvariable = var) > ? ? ?e2 = Tk.Entry(root, textvariable = var) > > doing this has the advantage that you can access the internal variable > via the StringVar object (held in the Python variable named "var"), but > at the Tkinter level, it's exactly the same thing. ?changes to the > variable will be reflected in both widgets, and changes to *either* > widget will be reflected in the variable, and therefore also in the > other widget. > ?> On the other hand, the oddness multiplied since the value replication > ?> doesn't happen if I set the textvariable to a variable. > > sure does, if you use the same internal variable for both widgets. After reading your post, I realized the reason why it doesn't replicate was because I set the variable to an empty string, which doesn't initialize the textvariable. From martin at v.loewis.de Thu Dec 6 14:23:43 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 06 Dec 2007 20:23:43 +0100 Subject: pipeline encoding In-Reply-To: References: <5rqre3F165k2mU1@mid.uni-berlin.de> Message-ID: <47584C3F.2090309@v.loewis.de> > Are there any command line option for telling python what encoding to > use for stdout? Not a command line option. However, you can wrap sys.stdout with a stream that automatically performs an encoding. If all your print statements output Unicode strings, you can do sys.stdout = codecs.getwriter("utf-8")(sys.stdout) HTH, Martin From bj_666 at gmx.net Sat Dec 29 12:24:30 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 29 Dec 2007 17:24:30 GMT Subject: Optional code segment delimiter? References: Message-ID: <5tne6eF1e8nljU4@mid.uni-berlin.de> On Sat, 29 Dec 2007 09:20:00 -0800, xkenneth wrote: > Is it possible to use optional delimiters other than tab and colons? No. > And is there an alternate delimiter for statements other than the > newline? > > print this;print that; #for example Yes. But both are reasons to yell at you. ;-) Ciao, Marc 'BlackJack' Rintsch From lists at cheimes.de Wed Dec 12 21:01:54 2007 From: lists at cheimes.de (Christian Heimes) Date: Thu, 13 Dec 2007 03:01:54 +0100 Subject: Vista + Rails 2.0 upgrade => subprocess hangs In-Reply-To: <13f1941e-7a7d-4be4-92cf-fcec53874b73@d4g2000prg.googlegroups.com> References: <13f1941e-7a7d-4be4-92cf-fcec53874b73@d4g2000prg.googlegroups.com> Message-ID: <47609292.3020506@cheimes.de> Eric Promislow wrote: > Here's a small Python program I use to grab the output from rake: > > ===== > > from subprocess import Popen, PIPE > > p = Popen(args='c:\\ruby\\bin\\ruby.exe c:\\ruby\\bin\\rake -T', > cwd=u'c:\\Users\\ericp\\testing\\file07', > shell=True, > stdin=None, > stderr=PIPE, > stdout=PIPE, > creationflags=0x8000000 > ); > p.wait() > data = p.stdout.read() > print data Your usage of wait() is dangerous. The code can block indefinitely when the stdout or stderr buffer is full. Christian From nagle at animats.com Fri Dec 14 02:46:10 2007 From: nagle at animats.com (John Nagle) Date: Thu, 13 Dec 2007 23:46:10 -0800 Subject: urlparse.urlparse bug - misparses long URL In-Reply-To: <47622f71$0$36368$742ec2ed@news.sonic.net> References: <47622f71$0$36368$742ec2ed@news.sonic.net> Message-ID: <47623400$0$36387$742ec2ed@news.sonic.net> John Nagle wrote: > Here's a hostile URL that "urlparse.urlparse" seems to have mis-parsed. ... Simpler example: import urlparse s = 'http://www.example.com.mx?https://www.example.com' print urlparse.urlparse(s) produces ('http', 'www.example.com.mx?https:', '//www.example.com', '', '', '') which is wrong. John Nagle SiteTruth From horpner at yahoo.com Thu Dec 13 10:09:05 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 13 Dec 2007 15:09:05 GMT Subject: efficient data loading with Python, is that possible possible? References: Message-ID: On 2007-12-13, igor.tatarinov at gmail.com wrote: > On Dec 12, 4:03 pm, John Machin wrote: >> Inside your function >> [you are doing all this inside a function, not at global level in a >> script, aren't you?], do this: >> from time import mktime, strptime # do this ONCE >> ... >> blahblah = int(mktime(strptime(s, "%m%d%y%H%M%S"))) >> >> It would help if you told us what platform, what version of Python, >> how much memory, how much swap space, ... >> >> Cheers, >> John > > I am using a global 'from time import ...'. I will try to do that > within the > function and see if it makes a difference. > > The computer I am using has 8G of RAM. It's a Linux dual-core AMD or > something like that. Python 2.4 > > Here is some of my code. Tell me what's wrong with it :) > > def loadFile(inputFile, loader): > # .zip files don't work with zlib > f = popen('zcat ' + inputFile) > for line in f: > loader.handleLine(line) > ... > > In Loader class: > def handleLine(self, line): > # filter out 'wrong' lines > if not self._dataFormat(line): return > > # add a new output record > rec = self.result.addRecord() > > for col in self._dataFormat.colFormats: > value = parseValue(line, col) > rec[col.attr] = value > > def parseValue(line, col): > s = line[col.start:col.end+1] > # no switch in python > if col.format == ColumnFormat.DATE: > return Format.parseDate(s) > if col.format == ColumnFormat.UNSIGNED: > return Format.parseUnsigned(s) > if col.format == ColumnFormat.STRING: > # and-or trick (no x ? y:z in python 2.4) > return not col.strip and s or rstrip(s) > if col.format == ColumnFormat.BOOLEAN: > return s == col.arg and 'Y' or 'N' > if col.format == ColumnFormat.PRICE: > return Format.parseUnsigned(s)/100. > > And here is Format.parseDate() as an example: > def parseDate(s): > # missing (infinite) value ? > if s.startswith('999999') or s.startswith('000000'): return -1 > return int(mktime(strptime(s, "%y%m%d"))) An inefficient parsing technique is probably to blame. You first inspect the line to make sure it is valid, then you inspect it (number of column type) times to discover what data type it contains, and then you inspect it *again* to finally translate it. > And here is parseValue (will using a hash-based dispatch make > it much faster?): Not much. You should be able to validate, recognize and translate all in one pass. Get pyparsing to help, if need be. What does your data look like? -- Neil Cerutti From arnodel at googlemail.com Mon Dec 10 03:37:08 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 10 Dec 2007 00:37:08 -0800 (PST) Subject: Are Python deques linked lists? References: Message-ID: <963d4ed7-48fc-4a3a-bbff-9b5e91b01704@18g2000hsf.googlegroups.com> On Dec 9, 10:54 pm, John Machin wrote: > On Dec 10, 9:43 am, "Just Another Victim of the Ambient Morality" > > wrote: > > I'm looking for a linked list implementation. Something iterable with > > constant time insertion anywhere in the list. > > It's on the shelf between the jar of phlogiston and the perpetual > motion machine. I recommend a quick glance at any article on linked list. Here's one: http://en.wikipedia.org/wiki/Linked_list -- Arnaud From NikitaTheSpider at gmail.com Sat Dec 22 15:30:36 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Sat, 22 Dec 2007 15:30:36 -0500 Subject: Inter-process communication, how? References: Message-ID: In article , ecir.hana at gmail.com wrote: > Hi, > let's say I have two scripts: one does some computations and the other > one is a graphical front end for launching the first one. And both run > in separate processes (front end runs and that it spawns a subprocess > with the computation). Now, if the computation has a result I would > like to display it in the front end. In another words, I would like to > pass some data from one process to another. How to do that? I'm > affraid I can't use a pipe since the computation could print out some > logging (if I understant pipes correctly). Others have given you good suggestions; there's also this option which may or may not be an appropriate tool for what you want to do: http://NikitaTheSpider.com/python/shm/ -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From ctrachte at gmail.com Sun Dec 30 21:56:04 2007 From: ctrachte at gmail.com (infixum) Date: Sun, 30 Dec 2007 18:56:04 -0800 (PST) Subject: Help please with code to find and move files. References: <79776f34-be23-470f-9fe7-56e3741075d3@l6g2000prm.googlegroups.com> <18mgn3d140ladphb15lo17epi6lpd5j8ed@4ax.com> Message-ID: > > after changing i got this > > ? ? path = r"c:\" > ? ? ? ? ? ? ? ? ^ > SyntaxError: EOL while scanning single-quoted string Sorry about that. You can't end with a backslash - my bad. I just tried this in the interpreter and 'c:' works. From tgrav at mac.com Mon Dec 3 14:24:11 2007 From: tgrav at mac.com (Tommy Grav) Date: Mon, 3 Dec 2007 14:24:11 -0500 Subject: takes no arguments (1 given) In-Reply-To: <2b9a029c-20e4-4f20-9613-10617f6f540d@a39g2000pre.googlegroups.com> References: <2b9a029c-20e4-4f20-9613-10617f6f540d@a39g2000pre.googlegroups.com> Message-ID: <4A43DB3A-3777-4818-9B3F-D53608C75347@mac.com> On Dec 3, 2007, at 2:10 PM, Mike wrote: > In the following Display inherits from the Tkinter class Canvas: > > import sys > from Tkinter import * > class Display(Canvas) : > ... > def fill_canvas() : def fill_canvas(self): > slop=self.slop > set_sr(int(self.cget('width'))+slop, > int(self.cget('height'))+slop) > self.refresh() > ... > > disp=Display(fred, None) > disp.pack() > def stupid(unused) : disp.fill_canvas() > disp.bind("", stupid) > mainloop() > >> From the above I get: > Exception in Tkinter callback > ... > File Ca_canvas.py, line 173, in stupid > def stupid(unused) : disp.fill_canvas() > TypeError: fill_canvas() takes no arguments (1 given) > > > What is going on? > I tried to do something similar with lambda > and got the same result. The class method needs a self argument so that disp.fill_canvas() can parse the class instance disp to the method. Cheers TG From kw at codebykevin.com Mon Dec 31 10:47:23 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 31 Dec 2007 10:47:23 -0500 Subject: TK 8.5 In-Reply-To: References: Message-ID: <47790F0B.2090402@codebykevin.com> Christian Heimes wrote: > Leon wrote: > >> 2) Is it a way to use Tk 8.5 with the present version of Python (2.5) ? > > No, not yet. It may be possible to back port Tcl Tk 8.5 support from 2.6 > to 2.5 once we have finished the migration to 8.5. Actually, you can. I'm using a custom-built Python that links to 8.5 with no problem. However, you do have to use some additional modules (referenced in another post) to get things working properly. --Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From arnodel at googlemail.com Mon Dec 31 12:22:14 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 31 Dec 2007 09:22:14 -0800 (PST) Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <4a5d4311-c5ec-4f3c-8800-c30ac30e399d@t1g2000pra.googlegroups.com> Message-ID: <6aba9463-f0ea-43a2-b8de-9c7026c4d14e@e4g2000hsg.googlegroups.com> On Dec 31, 10:58?am, Odalrick wrote: > On 30 Dec, 17:26, George Sakkis wrote: > > > On Dec 29, 9:14 pm, bukzor wrote: > > > > Here's the answer to the question:http://www.python.org/doc/faq/general/#why-are-default-values-shared-... > > > > It looks like Guido disagrees with me, so the discussion is closed. > > > Note that the FAQ mainly explains *what* happens, not *why* was this > > decision taken. Although it shows an example where "this feature can > > be useful", it's neither the only way to do it nor is memoization as > > common as wanting fresh default arguments on every call. > > I'm surprised noone has said anything about the why of default > mutables. I think it is becasue it isn't easy to do it an other way. [...] There is an easy enough way: evaluate default values when the function is called rather than when it is defined. This behaviour comes with its own caveats as well I imagine, and it's not 'as easy' to implement as the current one. What's good about the current behaviour is that it is easy to reason with (once you know what happens), even though you almost have to get bitten once. But using this to have static variable is extremely ugly IMHO. -- Arnaud From devnew at gmail.com Thu Dec 20 10:20:41 2007 From: devnew at gmail.com (devnew at gmail.com) Date: Thu, 20 Dec 2007 07:20:41 -0800 (PST) Subject: clearing text on canvas References: <4371c80c-2a97-4c3c-99c1-813459d28f32@d27g2000prf.googlegroups.com> Message-ID: <9d065a34-ade5-4f5e-816f-46f56b9787ec@s19g2000prg.googlegroups.com> thanx a lot Peter dn From rurpy at yahoo.com Thu Dec 20 10:57:02 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Thu, 20 Dec 2007 07:57:02 -0800 (PST) Subject: Is there *any* real documentation to PyWin32? References: Message-ID: <8d7d12b1-eebd-45b7-86e0-f1c09f4aa58b@b1g2000pra.googlegroups.com> On Dec 20, 6:35 am, Benoit wrote: > I understand that the Win32 has been said to be itself poorly > documented, so perhaps that the documentation that comes with the > modules is of similar quality is no coincidence. Maybe I'm still too > young in my programming to grasp the good of that documentation, but > for myself, it tells me next to nothing. Could anyone point me to > anything which may exist that does a better job of explaining the > extensions' use? I tried to take a look @ Microsoft's documentation, > but it was confusing. There is Mark Hammond's book [1] about python-win32 though I haven't used it and don't know if it contains anything that would be helpful to you. It is rather old now but some claim that is not important. [2] Personally I consider Python-win32 to be docware -- software that is sufficiently difficult to use with the included free documentation that many people will just buy the $$$ documentation. Numpy is another prominent example of docware. A misappropriation of the good- will value of legitimate open source software. [1]http://www.amazon.com/Python-Programming-Win32-Windows-Programmers/ dp/1565926218/ref=sr_1_1?ie=UTF8&s=books&qid=1198165983&sr=1-1 [2] http://groups.google.com/group/comp.lang.python/browse_thread/thread/e5a1f274ec411cbe/78b1390a6f6d75b2?hl=en&lnk=st&q=com+win32+(doc+OR+documentation)+group%3Acomp.lang.python#78b1390a6f6d75b2 From tommy.nordgren at comhem.se Sat Dec 8 08:26:29 2007 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Sat, 8 Dec 2007 14:26:29 +0100 Subject: how to convert 3 byte to float In-Reply-To: <5rvil4F16qk56U1@mid.individual.net> References: <475a7336$0$13116$9b4e6d93@newsspool2.arcor-online.net> <5rvc6hF17032iU1@mid.individual.net> <475a8591$0$17533$9b4e6d93@newsspool4.arcor-online.net> <5rvil4F16qk56U1@mid.individual.net> Message-ID: <91A91818-2955-401D-9238-ED800EFD1FA5@comhem.se> On 8 dec 2007, at 13.57, Bjoern Schliessmann wrote: > Mario M. Mueller wrote: > >> It's output of a digitizer (but not that old). I was also >> wondering about the reason for this limitation (maybe the design >> is ~20 years old). > > Uh, that's weird. Since Python cannot guess its format, you'll have > to try it out. Why don't you try to let the device output > well-known values and write a python script to display them > bitwise? With some luck you can reverse engineer the format. > > Regards, > > > Bj?rn > > -- > BOFH excuse #12: > > dry joints on cable plug > It will probably require a high quality voltage standard to do this. There are special high precission voltage standard chips to do this. For producing other voltages than the standard voltage of the chip, use pulsewith modulation with a low pass filter. ------------------------------------- This sig is dedicated to the advancement of Nuclear Power Tommy Nordgren tommy.nordgren at comhem.se From diesch at spamfence.net Sun Dec 23 10:32:51 2007 From: diesch at spamfence.net (Florian Diesch) Date: Sun, 23 Dec 2007 16:32:51 +0100 Subject: exception message output problem References: <482a0572-8dbe-42b6-9058-118ee0d28254@d4g2000prg.googlegroups.com> Message-ID: <3mb245-cee.ln1@mid.florian-diesch.de> Lie wrote: > # Python have an odd (read: broken) singleton implementation > # single member tuple must have a comma behind it Otherwise (1+2)+(3+4) would evaluate to (3, 7) instead of 10. Florian -- ----------------------------------------------------------------------- ** Hi! I'm a signature virus! Copy me into your signature, please! ** ----------------------------------------------------------------------- From nir1408 at gmail.com Thu Dec 20 08:21:15 2007 From: nir1408 at gmail.com (Nir) Date: Thu, 20 Dec 2007 05:21:15 -0800 (PST) Subject: New to Python Would like debug advice References: Message-ID: On Dec 17, 9:17 pm, PatrickMinnesota wrote: > Yep, I'm new to the language, it's been a couple of months. > > I opted for gvim and console window for developing on a Windows XP > box. I'm not a huge fan of IDEs except for when I need some > debugging. I've done my googling and see a bunch of options out there > for a debugging solution for Python on Windows. > > I've used Eclipse for a few years for Java development and I > understand there is a Python module for it that might make sense. > > What I'm looking for is advice on what to use todebuggeneral Python > programs at the source level, some will be graphical. If the eclipse > route is the way to go, that's fine, but I'm wondering what other > options people have good luck with. Keep in mind I will probably > continue to use Vi/Emacs and a console window for my main development. > > Thanks. Try Winpdb (On Linux as well). From t.rectenwald at gmail.com Wed Dec 26 13:23:39 2007 From: t.rectenwald at gmail.com (t_rectenwald) Date: Wed, 26 Dec 2007 10:23:39 -0800 (PST) Subject: Writing Oracle Output to a File References: <9ea3f90b-23e1-46c2-beb9-2b7cd8cf83cc@s48g2000hss.googlegroups.com> <9205dee1-cecf-4c55-9edd-35b2a4c4d96f@j64g2000hsj.googlegroups.com> <3a3c6c6c-8497-4db8-892e-d6f898f3f367@i3g2000hsf.googlegroups.com> Message-ID: <633d8f91-8866-444d-a905-e9f806fae75d@p69g2000hsa.googlegroups.com> On Dec 26, 12:10?pm, t_rectenwald wrote: > On Dec 26, 12:06?pm, Paul Hankin wrote: > > > > > > > On Dec 26, 4:51?pm, t_rectenwald wrote: > > > > On Dec 26, 10:36?am, t_rectenwald wrote: > > > > > Hello, > > > > > I attempting to execute an Oracle query, and write the results to a > > > > file in CSV format. ?To do so, I've done the following: > > > > > import cx_Oracle > > > > db = cx_Oracle.connect('user/pass at DBSID') > > > > cursor = db.cursor() > > > > cursor.arraysize = 500 > > > > cursor.execute(sql) > > > > result = cursor.fetchall() > > > > > The above works great. ?I'm able to connect to the database and print > > > > out the results as a list of tuples. ?Here is where I get lost. ?How > > > > do I work with a "list of tuples?" ?My understanding is that a "list" > > > > is basically an array (I don't come from a Python background). ?Tuples > > > > are a "collection of objects." ?So, if I do... > > > > > print result[0] > > > > > I get the first row of the query, which would make sense. ?The problem > > > > is that I cannot seem to write tuples to a file. ?I then do this... > > > > > csvFile = open("output.csv", "w") > > > > csvFile = write(result[0]) > > > > csvFile.close > > > > > This generates an exception: > > > > > TypeError: argument 1 must be string or read-only character buffer, > > > > not tuple > > > > > So, I'm a bit confused as to the best way to do this. ?I guess I could > > > > try to convert the tuples into strings, but am not sure if that is the > > > > proper way to go. ?Any help would be appreciated. ?I've also seen a > > > > csv module out there, but am not sure if that is needed in this > > > > situation. > > > > > Best Regards, > > > > Tom > > > > Hello, > > > > I was able to figure this out by using join to convert the tuples into > > > strings, and then have those write to the filehandle: > > > > csvFile = open("output.csv", "w") > > > for row in cursor.fetchall(): > > > ? ? csvFile.write(','.join(row) + "\n") > > > csvFile.close > > > As usual, the python standard library has functions that do what you > > want! Using the csv module will help you avoid trouble when your data > > contains commas or control characters such as newlines. > > > import csv > > help(csv) > > > Suggests this code: > > import csv > > csv_file = open('output.csv', 'w') > > csv_writer = csv.writer(csvFile) > > csv_writer.writerows(cursor.fetchall()) > > csv_file.close() > > > -- > > Paul Hankin- Hide quoted text - > > > - Show quoted text - > > Thanks for the tip. ?I'll read up on the csv module and use that > instead. ?I'm already running into errors with null values, etc... and > I believe some of the data in this DB will have commas, so this will > be a much cleaner way of doing things. > > Regards, > Tom- Hide quoted text - > > - Show quoted text - I read up on the csv module. BTW, thanks again! That took care of null values, I didn't even have to iterate anything in a loop, or convert the tuples. Great stuff. I'm loving Python. Regards, Tom From caroliina at hot.ee Sun Dec 9 11:11:00 2007 From: caroliina at hot.ee (caroliina) Date: Sun, 9 Dec 2007 08:11:00 -0800 (PST) Subject: reading list of list to a file Message-ID: <14239876.post@talk.nabble.com> i made a list of lists but i cant write it into a file. how do i get the first string in a sublist? -- View this message in context: http://www.nabble.com/reading-list-of-list-to-a-file-tp14239876p14239876.html Sent from the Python - python-list mailing list archive at Nabble.com. From answer654 at 8439.e4ward.com Mon Dec 3 09:10:50 2007 From: answer654 at 8439.e4ward.com (Michael Goerz) Date: Mon, 03 Dec 2007 15:10:50 +0100 Subject: converting to and from octal escaped UTF--8 In-Reply-To: References: <5rh3q7F142qimU1@mid.uni-berlin.de> <634f39ae-a0a9-4d07-983a-198445d8c849@w34g2000hsg.googlegroups.com> Message-ID: <5rih37F14a0jjU1@mid.uni-berlin.de> MonkeeSage wrote: > On Dec 3, 1:31 am, MonkeeSage wrote: >> On Dec 2, 11:46 pm, Michael Spencer wrote: >> >> >> >>> Michael Goerz wrote: >>>> Hi, >>>> I am writing unicode stings into a special text file that requires to >>>> have non-ascii characters as as octal-escaped UTF-8 codes. >>>> For example, the letter "?" (latin capital I with acute, code point 205) >>>> would come out as "\303\215". >>>> I will also have to read back from the file later on and convert the >>>> escaped characters back into a unicode string. >>>> Does anyone have any suggestions on how to go from "?" to "\303\215" and >>>> vice versa? >>> Perhaps something along the lines of: >>> >>> def encode(source): >>> ... return "".join("\%o" % ord(c) for c in source.encode('utf8')) >>> ... >>> >>> def decode(encoded): >>> ... bytes = "".join(chr(int(c, 8)) for c in encoded.split('\\')[1:]) >>> ... return bytes.decode('utf8') >>> ... >>> >>> encode(u"?") >>> '\\303\\215' >>> >>> print decode(_) >>> ? >>> HTH >>> Michael >> Nice one. :) If I might suggest a slight variation to handle cases >> where the "encoded" string contains plain text as well as octal >> escapes... >> >> def decode(encoded): >> for octc in (c for c in re.findall(r'\\(\d{3})', encoded)): >> encoded = encoded.replace(r'\%s' % octc, chr(int(octc, 8))) >> return encoded.decode('utf8') >> >> This way it can handle both "\\141\\144\\146\\303\\215\\141\\144\\146" >> as well as "adf\\303\\215adf". >> >> Regards, >> Jordan > > err... > > def decode(encoded): > for octc in re.findall(r'\\(\d{3})', encoded): > encoded = encoded.replace(r'\%s' % octc, chr(int(octc, 8))) > return encoded.decode('utf8') Great suggestions from both of you! I came up with my "final" solution based on them. It encodes only non-ascii and non-printables, and stays in unicode strings for both input and output. Also, low ascii values now encode into a 3-digit octal sequence also, so that decode can catch them properly. Thanks a lot, Michael ____________ import re def encode(source): encoded = "" for character in source: if (ord(character) < 32) or (ord(character) > 128): for byte in character.encode('utf8'): encoded += ("\%03o" % ord(byte)) else: encoded += character return encoded.decode('utf-8') def decode(encoded): decoded = encoded.encode('utf-8') for octc in re.findall(r'\\(\d{3})', decoded): decoded = decoded.replace(r'\%s' % octc, chr(int(octc, 8))) return decoded.decode('utf8') orig = u"bla?blub" + chr(10) enc = encode(orig) dec = decode(enc) print orig print enc print dec From piet at cs.uu.nl Wed Dec 5 13:11:59 2007 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 05 Dec 2007 19:11:59 +0100 Subject: "Python" is not a good name, should rename to "Athon" References: <78bdd499-a263-4c68-8e43-e3e59b111c7e@a39g2000pre.googlegroups.com> Message-ID: >>>>> "Adrian Cherry" (AC) wrote: >AC> For that matter C# is no better, I thought that # was pronounced >AC> hash, I still refer to C# as C-hash. Are you musically illiterate? -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From robin at reportlab.com Mon Dec 10 09:43:27 2007 From: robin at reportlab.com (Robin Becker) Date: Mon, 10 Dec 2007 14:43:27 +0000 Subject: distutils & OS X universal binaries In-Reply-To: <475BC83D.9040903@jessikat.plus.net> References: <475AA774.7020904@jessikat.plus.net> <475ab088$0$19620$9b622d9e@news.freenet.de> <475ACA77.5030802@jessikat.plus.net> <475ACEBE.8070509@v.loewis.de> <475AD50F.1060301@jessikat.plus.net> <475ad8cd$0$5335$9b622d9e@news.freenet.de> <475AE13B.8070901@jessikat.plus.net> <475bc092$0$1221$9b622d9e@news.freenet.de> <475BC83D.9040903@jessikat.plus.net> Message-ID: <475D508F.8070502@chamonix.reportlab.co.uk> Robin Becker wrote: ........ >> Ok. Still, I would write it as >> >> #if defined(__LITTLE_ENDIAN__) >> #undef WORDS_BIGENDIAN >> #elif defined(__BIG_ENDIAN__) >> #undef WORDS_BIGENDIAN >> #define WORDS_BIGENDIAN 1 >> #endif >> >> Regards, >> Martin > I'm never sure if undef gives an error if the variable isn't defined, > but that is cleaner > > thanks for the assistance Just like to say my testee/victim reports great success with the above snippet inserted into the right config file. Thanks to all. -- Robin Becker From mnordhoff at mattnordhoff.com Sat Dec 29 20:09:14 2007 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sat, 29 Dec 2007 20:09:14 -0500 Subject: sqlobject question... In-Reply-To: <086201c84a80$1e3e2e40$0301a8c0@tmesa.com> References: <086201c84a80$1e3e2e40$0301a8c0@tmesa.com> Message-ID: <4776EFBA.8080208@mattnordhoff.com> bruce wrote: > hi... > > this continues my investigation of python/sqlobject, as it relates to the > need to have an id, which is auto-generated. > > per various sites/docs on sqlobject, it appears that you can override the > id, by doing something similar to the following: > > def foo(SQLObject): > def _init(self, id, connection=None): > id = str(id) > SQLObject._init(self, id, connection) > > cat=StringCol() > dog=StringCol() > > > however, no matter what i do, i can't seem to insert anything into "id" so > that i can use the "id"!!!! > > any thoughts/comments/pointers, code samples would be helpful!!! > > thanks SQLObject may do something weird, but normally the init method is named "__init__", not "_init". Try changing that. -- From hniksic at xemacs.org Tue Dec 18 11:35:49 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 18 Dec 2007 17:35:49 +0100 Subject: checking a string against multiple patterns References: Message-ID: <87lk7sklju.fsf@mulj.homelinux.net> tomasz writes: > here is a piece of pseudo-code (taken from Ruby) that illustrates the > problem I'd like to solve in Python: [...] I asked the very same question in http://groups.google.com/group/comp.lang.python/browse_frm/thread/3e8da954ff2265e/4deb5631ade8b393 It seems that people either write more elaborate constructs or learn to tolerate the nesting. > Is there an alternative to it? A simple workaround is to write a trivial function that returns a boolean, and also stores the match object in either a global storage or an object. It's not really elegant, especially in smaller scripts, but it works: def search(pattern, s, store): match = re.search(pattern, s) store.match = match return match is not None class MatchStore(object): pass # irrelevant, any object with a 'match' attr would do where = MatchStore() if search(pattern1, s, where): pattern1 matched, matchobj in where.match elif search(pattern2, s, where): pattern2 matched, matchobj in where.match ... From DirkHagemann at gmail.com Fri Dec 7 10:57:52 2007 From: DirkHagemann at gmail.com (Dirk Hagemann) Date: Fri, 7 Dec 2007 07:57:52 -0800 (PST) Subject: Converting Excel time-format (hours since 1.1.1901) References: <6c5cc79e-a121-45c5-9a97-b8564ca9f3bf@l16g2000hsf.googlegroups.com> <716882bb-ab0f-4eb5-b577-1f12372d7b93@w56g2000hsf.googlegroups.com> Message-ID: <522c5cd1-10c2-4ebd-b34d-9e7578617e4e@e10g2000prf.googlegroups.com> On 7 Dez., 16:50, Dirk Hagemann wrote: > On 7 Dez., 16:21, Tim Golden wrote: > > > > > mensana... at aol.com wrote: > > > On Dec 7, 7:20?am, Dirk Hagemann wrote: > > >> Hello, > > > >> From a zone-file of a Microsoft Active Directory integrated DNS server > > >> I get the date/time of the dynamic update entries in a format, which > > >> is as far as I know the hours since january 1st 1901. > > > If it *is* then the easiest way is this: > > > > > import datetime > > print datetime.date (1901, 1, 1) + datetime.timedelta (hours=3566839) > > > > > > But, as someone pointed out, that puts you somewhere in 2300. > > Where are you getting the 1901 from (and the hours, for that > > matter). If it's based, as AD dates are, for example, from 1601, > > then the calc becomes: > > > > > import datetime > > print datetime.date (1601, 1, 1) + datetime.timedelta (hours=3566839) > > > > > > which looks more realistic. But frankly I'm guessing. > > > TJG > > (3566839/24)/365 = 407 - YES I did this calculation too and was > surprised. But if you try this out in MS Excel: > ="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0) (put > 3566839 in field A1 and switch the format of the result-fieldby right- > click on it to the > date format "14.3.01 13:30") > > and then replace 3566839 by, let's say, "2", Excel calculates the date > 01.10.1901 2:00 AM. Try out other values like 5 or 24! So I thought > 3566839 represents hours. > > Dirk Additional to my last posting: if you want to try this out in Excel you should replace the command "REST" by the english command what should be something like "remainder". From mblume at socha.net Fri Dec 28 08:55:14 2007 From: mblume at socha.net (Martin Blume) Date: Fri, 28 Dec 2007 14:55:14 +0100 Subject: Compiler or stg. to get exe! References: Message-ID: <47750042$0$29615$5402220f@news.sunrise.ch> "SMALLp" schrieb > I have question. After short goggling, I haven't found > anything good. So my question is: > I wrote a program in python and i Get .py files and some > .pyc in working folder. Now i want program tu run under > windows, so i need to get exe files or something. > If python is installed on the target machine (Windows or Linux or ...) you do not need an exe, just copy the py file. > And what do i need to do to make program for linux. > (stg. like .deb package) a .deb package is more than a "program". You'll have to look at the .deb developer documentation. Again, for simple programs, just copying the .py file is sufficient, provided that Python (and all the modules your .py needs) is installed. HTH Martin From lists at cheimes.de Fri Dec 28 08:46:10 2007 From: lists at cheimes.de (Christian Heimes) Date: Fri, 28 Dec 2007 14:46:10 +0100 Subject: parallel processing in standard library In-Reply-To: <4774BCDD.40503@web.de> References: <32e43bb70712270552n76d460e8y9d1d2acaa73f829e@mail.gmail.com> <4774BCDD.40503@web.de> Message-ID: Stefan Behnel wrote: > Well, there is one parallel processing API that already *is* part of stdlib: > the threading module. So the processing module would fit just nicely into the > idea of a "standard" library. Don't you forget the select module and its siblings for I/O bound concurrency? Christian From gagsl-py2 at yahoo.com.ar Mon Dec 17 22:38:07 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Dec 2007 00:38:07 -0300 Subject: Keyword args to SimpleXMLRPCServer References: <15144ed7-05a1-4812-8cf3-4cc8aba9c949@e6g2000prf.googlegroups.com> Message-ID: En Mon, 17 Dec 2007 21:13:32 -0300, Sean DiZazzo escribi?: > Why is the following not working? Is there any way to get keyword > arguments working with exposed XMLRPC functions? > > ~~~~~~~~~~~~~~~~ server.py > import SocketServer > from SimpleXMLRPCServer import > SimpleXMLRPCServer,SimpleXMLRPCRequestHandler > > # Threaded mix-in > class > AsyncXMLRPCServer(SocketServer.ThreadingMixIn,SimpleXMLRPCServer): > pass > > class XMLFunctions(object): > def returnArgs(*args, **kwargs): > return kwargs.items() You forget the self argument. But this is not the problem. XMLRPC does not allow passing parameters by name, only positional parameters. See http://www.xmlrpc.com/spec: "If the procedure call has parameters, the must contain a sub-item. The sub-item can contain any number of s, each of which has a . " Parameters have no , just a , so you can only use positional parameters. But you can simulate keyword arguments by collecting them in a dictionary and passing that dictionary as an argument instead. (server side) def returnArgs(self, x, y, other={}): return x, y, other (client side) print server.returnArgs("xvalue", "yvalue", dict(foo=123, bar=234, baz=345)) -- Gabriel Genellina From nagle at animats.com Fri Dec 14 11:43:42 2007 From: nagle at animats.com (John Nagle) Date: Fri, 14 Dec 2007 08:43:42 -0800 Subject: urlparse.urlparse bug - misparses long URL In-Reply-To: <47623ac0$0$36369$742ec2ed@news.sonic.net> References: <47622f71$0$36368$742ec2ed@news.sonic.net> <47623ac0$0$36369$742ec2ed@news.sonic.net> Message-ID: <4762b1fd$0$36318$742ec2ed@news.sonic.net> John Nagle wrote: > Matt Nordhoff wrote: >> John Nagle wrote: >>> Here's a hostile URL that "urlparse.urlparse" seems to have mis-parsed. >>> ==== > ... > >> >> It's breaking on the first slash, which just happens to be very late in >> the URL. >> >>>>> urlparse('http://example.com?blahblah=http://example.net') >> ('http', 'example.com?blahblah=http:', '//example.net', '', '', '') > > That's what it seems to be doing: > > sa1 = 'http://example.com?blahblah=/foo' > sa2 = 'http://example.com?blahblah=foo' > print urlparse.urlparse(sa1) > ('http', 'example.com?blahblah=', '/foo', '', '', '') # WRONG > print urlparse.urlparse(sa2) > ('http', 'example.com', '', '', 'blahblah=foo', '') # RIGHT > > That's wrong. RFC3896 ("Uniform Resource Identifier (URI): Generic > Syntax"), page 23 says > > "The characters slash ("/") and question mark ("?") may represent data > within the query component. Beware that some older, erroneous > implementations may not handle such data correctly when it is used as > the base URI for relative references (Section 5.1), apparently > because they fail to distinguish query data from path data when > looking for hierarchical separators." > > So "urlparse" is an "older, erroneous implementation". Looking > at the code for "urlparse", it references RFC1808 (1995), which > was a long time ago, three revisions back. > > Here's the bad code: > > def _splitnetloc(url, start=0): > for c in '/?#': # the order is important! > delim = url.find(c, start) > if delim >= 0: > break > else: > delim = len(url) > return url[start:delim], url[delim:] > > That's just wrong. The domain ends at the first appearance of > any character in '/?#', but that code returns the text before the > first '/' even if there's an earlier '?'. A URL/URI doesn't > have to have a path, even when it has query parameters. "urlparse" doesn't use regular expressions. Is there some good reason for that? It would be easy to fix the code above with a regular expression to break on any char in '/?#'. But urlparse would have to import "re". Is that undesirable? John Nagle From gagsl-py2 at yahoo.com.ar Sun Dec 16 23:46:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Dec 2007 01:46:44 -0300 Subject: Immutable Geometry Types References: <91b0efda-7fc4-4914-93e3-bf7a7101a4e8@l32g2000hse.googlegroups.com> Message-ID: En Sun, 16 Dec 2007 23:13:47 -0300, PeterBraden1 at googlemail.com escribi?: > Hi, > > I am learning python, having learnt most of my object orientation with > java, and decided to port some of my geometry classes over. I haven't > used immutability in python before, so thought this would be an > interesting chance to learn. > > I am looking for feedback on any ways in which I might have left > variables unprotected, and ways in which I am not being pythonic. Immutable classes usually implement __new__ and leave __init__ unimplemented: def __new__(cls, val, measure='rad'): # using 'type' as a name shadows the builtin type instance = super(Angle, self).__new__() if measure == 'rad': pass elif measure == 'deg': value = math.radians(value) else: raise ValueError, "unknown Angle measure: %r" % measure instance._value = value return instance For the various comparison operators, since this class "plays well" with ordering, it's easier to implement __cmp__ and make all operators refer to it: def __cmp__(self, other): if isinstance(other, Angle): return cmp(self._value, other._value) raise NotImplementedError __eq__ = lambda self,other: self.__cmp__(other)==0 __ne__ = lambda self,other: self.__cmp__(other)!=0 __lt__ = lambda self,other: self.__cmp__(other)<0 __ge__ = lambda self,other: self.__cmp__(other)>=0 __gt__ = lambda self,other: self.__cmp__(other)>0 __le__ = lambda self,other: self.__cmp__(other)<=0 > def __setattr__(self, name, value): > """ > Suppress setting of data - Angle is immutable > """ > self._immutableError() Why? This class contains a single attribute, value, and we could make it immutable. But why restrict the possibility to add *other* attributes? (There is __slots__ too, but I would not recommend it at this stage) > def __delattr__(self, name): Same as above. > def __mul__(self, other): > def __div__(self, other): (I've never seen those operations on angles) > def fromCos(self, c): > """ > return angle with specified cos > """ > return Angle(math.acos(c)) > > fromCos = classmethod(fromCos) I prefer to write @classmethod def fromCos(self, c): > radians = property(lambda self: self._value, lambda x: > self._immutableError()) > degrees = property(lambda self: math.degrees(self._value), lambda > x: self._immutableError()) > cos = property(lambda self: math.cos(self._value), lambda x: > self._immutableError()) > sin = property(lambda self: math.sin(self._value), lambda x: > self._immutableError()) > tan = property(lambda self: math.tan(self._value), lambda x: > self._immutableError()) You don't have to write them that way. Just omit the property setter, and it will be read-only. tan = property(lambda self: math.tan(self._value)) Or: @property def tan(self): return math.tan(self.value) > def withinRange(self, angle, range): > """ > angle is within range of self > """ > return (self._value < angle._value + range) and (self._value > > angle._value - range) I think this is more readable: return angle.value-range < self.value < angle.value+range > class Point2D (object): Same as above, replace __init__ by __new__. You may inherit from tuple instead, and get some basic methods already implemented. > length = property(lambda self: return math.sqrt(self.x*self.x + > self.y*self.y), lambda x: self._immutableError()) Using math.hypot is safer in some circunstances. > def normalise(self): > return Point2D(self.x/self.length, self.y/self.length); > def translate(self, other) { > return self + other > } I'd use "normalised", "translated", etc. because they return a *new* object, instead of modifying self. (You forgot to remove some braces, I presume...) -- Gabriel Genellina From rodmena.com at gmail.com Mon Dec 10 06:08:50 2007 From: rodmena.com at gmail.com (farsheed) Date: Mon, 10 Dec 2007 03:08:50 -0800 (PST) Subject: Best way to protect my new commercial software. References: <8c9a903b-7f57-4a90-883a-5bb1f06fedf6@e6g2000prf.googlegroups.com> <46303db5-7cd0-4424-9834-3458c4061229@w56g2000hsf.googlegroups.com> <9e1711a2-688b-4643-a276-659163e867f1@d61g2000hsa.googlegroups.com> Message-ID: <9771eb4a-fae5-472d-9cba-9a09ae077e3d@x69g2000hsx.googlegroups.com> So you say there is not any trusted way? From larry.bates at websafe.com Tue Dec 11 18:30:44 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 11 Dec 2007 17:30:44 -0600 Subject: Elementtree find problem In-Reply-To: References: Message-ID: Willemsjunk at gmail.com wrote: > I tried the tips I found in other posts but I still get 'none' back: > > import easygui as eg > import xml.etree.ElementTree as ET > import sys > > #kml source is: > # > # > # > # Simple placemark > # Attached to the ground. Intelligently places itself > # at the height of the underlying terrain. > # > # -122.0822035425683,37.42228990140251,0 coordinates> > # > # > # > > > #select a file and open it in python > f_name=eg.fileopenbox("select kml file", "Select kml file") > f_kml=open(f_name,'r') > > #parse and create Elementtree and go to root > tree=ET.parse(f_kml) > kml=tree.getroot() > > #look for description > coord= kml.find('.//description') > print coord > > > _______________________ > > the result is 'None' ... > > If I print out the kml with tostring I can see the entire file and to > me the XPath string also seems correct > > any idea? This works: >>> url='http://earth.google.com/kml/2.2' >>> coord=kml.find('{%s}Placemark/{%s}Point/{%s}coordinates' % \ (url, url, url)).text >>> print coord '-122.0822035425683,37.42228990140251,0' -Larry From thorsten at thorstenkampe.de Sat Dec 29 10:44:28 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 29 Dec 2007 15:44:28 -0000 Subject: i18n questions References: Message-ID: * Donn Ingle (Fri, 28 Dec 2007 20:01:48 +0200) > I'm 100% new to this i18n lark and my approach so far has been to create > a .mo file per module in my app. > My thinking was, why load one huge .mo file when a single module only needs > a few strings? Since then, it seems, I have made the wrong decision. > > For example I have module A that imports module B. Each one does this: > > gettext.install( domain, localedir, unicode = True ) > lang = gettext.translation(domain, localedir, languages = [ loc ] ) > lang.install(unicode = True ) > > (where doman is the name of the module, so "A" and "B") > > The problem is that domain "A" loads and then import B happens and so > the "lang" reference (I think) gets replaced by domain "B" -- the result is > that module A can only translate strings that are in domain "B". > > How does one 'merge' gettext.translations objects together? Or is that > insane? > > What's the best way to handle a project with multiple domain.mo files? I can give you just general advice how I dealt with internationalization in my example app. "scipt" is the main app with its own mo file and imports optparse which has again its own mo file # gettext.textdomain('optparse') gettext.install('script', unicode = True) from optparse import OptionParser, \ OptionGroup # [...] Thorsten From gherron at islandtraining.com Thu Dec 13 04:42:38 2007 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 13 Dec 2007 01:42:38 -0800 Subject: what the heck does this mean? In-Reply-To: <104510.96718.qm@web57307.mail.re1.yahoo.com> References: <104510.96718.qm@web57307.mail.re1.yahoo.com> Message-ID: <4760FE8E.8060101@islandtraining.com> katie smith wrote: > Traceback (most recent call last): > File "C:\Python25\empire\Empire Strategy.pyw", line 322 > Maty = Searched(number) > TypeError: 'list' object is not callable > > My list is NewMap1 =[0,0,0,0,0,0,2,0,2,2,3,2,0,0,0,0] > > so Maty Searched(number is supposed to give me 0 when > Search = "NewMap" > number = 0 > bignum = 1 > bignumer = repr(bignum) > Searching = Search+bignumer > Searched = eval(Searching) > Maty = Searched[number] > > instead i get that error whats up? i thought it is suppose to give me > NewMap1(0).when I print it it works fine and gives me the result 0 > but when I go to save the number as Maty-(randomletters) it keeps > giving me the stupid error. You're not telling us something important. When I execute the statements you give, I do indeed get 0 for the value of Maty, which is what you expect -- so I see no problem. But then in your next claim, you say "save the number as Maty-(randomletters)". What does that mean? What Python statement are you running? What means "save"? What is "randomletters"? The error you are getting is usually gotten by code that tries to treat a variable containing a list as a function. Example: someList = [1,2,3] someList(99) Traceback (most recent call last): File "", line 1, in TypeError: 'list' object is not callable Gary Herron > > please help > > Ps: rather than doing in your head making a test prgram to run exactly > that might be better > > ------------------------------------------------------------------------ > Looking for last minute shopping deals? Find them fast with Yahoo! > Search. > From mail at timgolden.me.uk Fri Dec 7 08:59:40 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 07 Dec 2007 13:59:40 +0000 Subject: eclipse pywintypes.com_error In-Reply-To: References: <64ee0bd0-f39f-4906-af4d-b39cb04696cf@b15g2000hsa.googlegroups.com> Message-ID: <475951CC.9050008@timgolden.me.uk> gurkan wrote: > i have treid the script : > > #import active_directory > import win32com.client > > win32com.client.Dispatch ("ADODB.Command") > #me = active_directory.find_user () > > #print me > > again i got the error : > > Traceback (most recent call last): > File "H:\dev\eclipse\workspace\pyProject\src\pyPackage > \adDeneme3.py", line 4, in > win32com.client.Dispatch ("ADODB.Command") > File "E:\Python25\Lib\site-packages\win32com\client\__init__.py", > line 95, in Dispatch > dispatch, userName = > dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) > File "E:\Python25\Lib\site-packages\win32com\client\dynamic.py", > line 98, in _GetGoodDispatchAndUserName > return (_GetGoodDispatch(IDispatch, clsctx), userName) > File "E:\Python25\Lib\site-packages\win32com\client\dynamic.py", > line 78, in _GetGoodDispatch > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, > pythoncom.IID_IDispatch) > pywintypes.com_error: (-2147024770, 'The specified module could not be > found.', None, None) I don't think it's that the CoCreateInstance can't be found: that's a COM error you're seeing and it means that the IDispatch mechanism can't find the "ADODB.Command" you're looking for. If I get the chance I'll try to find a Vista machine to find out what the equivalent is. If anyone on the list has Vista and/or knows what the score is here, please let me know. To double-check, Gurkan, could you open the Registry and browse to HKEY_CLASSES_ROOT and look for a key ADODB.Command. I presume it's not present. TJG From mail at timgolden.me.uk Fri Dec 7 10:21:10 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 07 Dec 2007 15:21:10 +0000 Subject: Converting Excel time-format (hours since 1.1.1901) In-Reply-To: <716882bb-ab0f-4eb5-b577-1f12372d7b93@w56g2000hsf.googlegroups.com> References: <6c5cc79e-a121-45c5-9a97-b8564ca9f3bf@l16g2000hsf.googlegroups.com> <716882bb-ab0f-4eb5-b577-1f12372d7b93@w56g2000hsf.googlegroups.com> Message-ID: <475964E6.7020708@timgolden.me.uk> mensanator at aol.com wrote: > On Dec 7, 7:20?am, Dirk Hagemann wrote: >> Hello, >> >> From a zone-file of a Microsoft Active Directory integrated DNS server >> I get the date/time of the dynamic update entries in a format, which >> is as far as I know the hours since january 1st 1901. If it *is* then the easiest way is this: import datetime print datetime.date (1901, 1, 1) + datetime.timedelta (hours=3566839) But, as someone pointed out, that puts you somewhere in 2300. Where are you getting the 1901 from (and the hours, for that matter). If it's based, as AD dates are, for example, from 1601, then the calc becomes: import datetime print datetime.date (1601, 1, 1) + datetime.timedelta (hours=3566839) which looks more realistic. But frankly I'm guessing. TJG From mario at ruggier.org Fri Dec 28 06:00:59 2007 From: mario at ruggier.org (mario) Date: Fri, 28 Dec 2007 03:00:59 -0800 (PST) Subject: unicode(s, enc).encode(enc) == s ? References: <5e49e7e6-f2b3-4c9f-9dec-e5f01f12d59a@e4g2000hsg.googlegroups.com> <4773f0de$0$15825$9b622d9e@news.freenet.de> Message-ID: <7cb20641-ab33-4818-a911-80c684cb9792@q77g2000hsh.googlegroups.com> On Dec 27, 7:37 pm, "Martin v. L?wis" wrote: > Certainly. ISO-2022 is famous for having ambiguous encodings. Try > these: > > unicode("Hallo","iso-2022-jp") > unicode("\x1b(BHallo","iso-2022-jp") > unicode("\x1b(JHallo","iso-2022-jp") > unicode("\x1b(BHal\x1b(Jlo","iso-2022-jp") > > or likewise > > unicode("\x1b$@BB","iso-2022-jp") > unicode("\x1b$BBB","iso-2022-jp") > > In iso-2022-jp-3, there are even more ways to encode the same string. Wow, that's not easy to see why would anyone ever want that? Is there any logic behind this? In your samples both of unicode("\x1b(BHallo","iso-2022-jp") and unicode("\x1b(JHallo","iso-2022-jp") give u"Hallo" -- does this mean that the ignored/lost bytes in the original strings are not illegal but *represent nothing* in this encoding? I.e. in practice (in a context limited to the encoding in question) should this be considered as a data loss, or should these strings be considered "equivalent"? Thanks! mario From gagsl-py2 at yahoo.com.ar Sun Dec 30 08:55:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Dec 2007 05:55:49 -0800 (PST) Subject: difference between `x in list` and `list.index(x)` for instances of a new-style class References: <288b260d-96b9-43ef-9218-d21b44b7f8fc@s19g2000prg.googlegroups.com> Message-ID: <38b983b6-b4bc-4fcc-bf19-f810e3c52e00@f3g2000hsg.googlegroups.com> On 30 dic, 06:24, Riccardo Murri wrote: > bpgbai... at gmail.com writes: > > >> ? (Pydb) p graph == self.base[27] ? > >> ? True > >> ? (Pydb) p graph in self.base > >> ? True > >> ? (Pydb) self.base.index(graph) > >> ? *** ValueError: list.index(x): x not in list > > Looking at the source for both methods, they only > > use the __eq__ operator, but there is a slight difference: while one > > evaluates list[i]==x, the other reverses the operands. If your __eq__ > > is not reflexive, that could explain the difference. > > That was indeed the reason: a bug in Graph.__eq__ broke reflexivity in > certain cases. Combined with some other WTF bugs I've found at work, lately I feel more like a detective than a software developer :) -- Gabriel Genellina From wdrpower at hotmail.com Sat Dec 15 03:20:29 2007 From: wdrpower at hotmail.com (Michael Lalonde) Date: Sat, 15 Dec 2007 00:20:29 -0800 (PST) Subject: mike lalonde Message-ID: Michael Lalonde traveled with Mr Harnwell in an icy cave and went around killing rats with a jackhammer because his leg hurt and fell violently ill. Michael Lalonde just dodged three bullets, he went around killing rats with plastic bombs and to the disappointment of some he got the girl, the treasure and a nasty rash. Mike Lalonde was owed money by a man in a wheelchair after winning the lottery and got locked in a room full of greasy meat very happily and all hell broke loose which made him cry, he stole a car and as if it were a miracle he escaped narrowly and hitch-hiked all the way home. Michael Lalonde was owed money by John Howard down the back of Galston High and fell into the eternal pit of hell but it was all an accident and fell violently ill. Michael Lalonde just dodged three bullets, he blew up a truck with a hand grenade and with relative ease he got the girl, the treasure and a nasty rash. mike Lalonde got a letter bomb from his mum in an icy cave and fell into the eternal pit of hell very happily and all hell broke loose which started a party, he made a giant leap across the ravine and with the help of $120 000 worth of special effects he defeated his enemy and the world was safe again... but for how long? mike Lalonde traveled with an axe murderer down the back of Galston High and got locked in a room full of greasy meat for no reason at all and went for a long walk through the park. mike Lalonde just dodged three bullets, he made a run for it and as he nearly gave up all hope he got the money and lived the rest of his life in Tokalue Michael Lalonde was owed money by an axe murderer in the fire place and almost got killed by an army of birds because his leg hurt and a heated argument arosewhich got him in a lot of trouble, he felt a sudden ray of hope and as if it were a miracle he failed the mission and the bad guys made it away with the gold. Michael Lalonde saw a movie made by a wild dog in the fire place and got locked in prison because he felt like it and fell violently illwhich got him in a lot of trouble, he made a run for it and with the help of $120 000 worth of special effects he got the girl, the treasure and a nasty rash. Danny Lalonde got a letter bomb from an axe murderer after winning the lottery and fell into the eternal pit of hell because he felt like it and chased a bunny which completely freaked him out he jumped out of the way as the roof collapsed and to the surprise of the audience he failed the mission and the bad guys made it away with the gold. mike Lalonde fought his enemy: Mr Harnwell on a pirate ship and got locked in prison because he had no sleep the night before and decided to sleep it off. Then mike Lalonde ran around like a lunatic, he shot all the bad guys and to the disappointment of some he accidently tripped and smashed his face against a rock. From no at no.no Tue Dec 4 08:36:20 2007 From: no at no.no (Zepo Len) Date: Tue, 04 Dec 2007 15:36:20 +0200 Subject: read lines References: Message-ID: > Your regex is not working correctly I guess, I don't even know why you > are using a regex, something like this would work just fine: > > import sys > nums = [float(line.split(' -')[1]) for line in open(sys.argv[1])] > print 'min=', min(nums), 'max=', max(nums) Sorry, that should be line.split() - didn't realise those were negative numbers. From timr at probo.com Tue Dec 25 01:20:36 2007 From: timr at probo.com (Tim Roberts) Date: Tue, 25 Dec 2007 06:20:36 GMT Subject: Python DLL in Windows Folder References: <533b7d320712230652w6bd4e90dv905d7112d337d0fd@mail.gmail.com> <533b7d320712231027h26623fffi3b471b6c85873a64@mail.gmail.com> Message-ID: Ross Ridge wrote: >Chris Mellon wrote: >>What the python installer is doing is the Right Thing for making the >>standard python dll available to third party applications. >>Applications that want a specific version of a specific DLL should use >>the mechanisms available for doing so, instead of relying on there >>being a specific version of the python dll in the windows folder. This >>is just general best practice on Windows. > >No, it's not best practice for an application install any of its files >in the Windows system directory. Python is more than an application. It's a development tool, and its DLLs are needed by any of the Python applications I create. I disagree with your assertion. >The system directory is ment only for drivers and system files. In your view, what disqualifies python24.dll as a "system file"? The fact that it wasn't produced by Microsoft? >Installing application DLLs in the system directory is something that >should only be done for backwards compatiblity. Deployment of Python applications is much easier when python24.dll is located there. That has to weigh in the equation. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ismail at pardus.org.tr Wed Dec 19 10:55:49 2007 From: ismail at pardus.org.tr (Ismail =?utf-8?q?D=C3=B6nmez?=) Date: Wed, 19 Dec 2007 17:55:49 +0200 Subject: How to generate pdf file from an html page?? In-Reply-To: <18281.15201.382459.804155@terry.local> References: <13mieavg35e92@corp.supernews.com> <18281.15201.382459.804155@terry.local> Message-ID: <200712191755.49697.ismail@pardus.org.tr> Wednesday 19 December 2007 17:40:17 tarihinde Terry Jones ?unlar? yazm??t?: > >>>>> "Grant" == Grant Edwards writes: > > Grant> On 2007-12-19, abhishek wrote: > >>> > Hi everyone, I am trying to generate a PDF printable format file from > >>> > an html page. Is there a way to do this using python. If yes then > >>> > which library and functions are required and if no then reasons why > >>> > it cant be done. > >>> > >>> Here's one way: > >>> > >>> ------------------------------html2pdf.py------------------------------ > >>>----------- #!/usr/bin/python > >>> import os,sys > >>> > >>> inputFilename,outputFilename = sys.argv[1:3] > >>> > >>> os.system("w3m -dump %s | a2ps -B --borders=no | ps2pdf - %s" % > >>> (inputFilename,outputFilename)) > > Note that this is highly insecure. outputFilename could be passed e.g., as > > /tmp/file.pdf; rm -fr /home/abhishek And the solution is to use subprocess [0] instead of os.system() [0] http://docs.python.org/lib/module-subprocess.html Regards, ismail -- Never learn by your mistakes, if you do you may never dare to try again. From nagle at animats.com Fri Dec 21 12:04:10 2007 From: nagle at animats.com (John Nagle) Date: Fri, 21 Dec 2007 09:04:10 -0800 Subject: It's ok to __slots__ for what they were intended In-Reply-To: References: <3ebb7816-c3ad-44ed-8aed-6c026c3c2b61@d4g2000prg.googlegroups.com> <0829587b-f3a1-4f77-86a1-163e7bcc54d2@l32g2000hse.googlegroups.com> Message-ID: <476bf150$0$36343$742ec2ed@news.sonic.net> Chris Mellon wrote: > On 20 Dec 2007 19:50:31 -0800, Aahz wrote: >> In article <0829587b-f3a1-4f77-86a1-163e7bcc54d2 at l32g2000hse.googlegroups.com>, >> Carl Banks wrote: >>>> Someday I'll have time to write up a proper page about why you shouldn't >>>> use __slots__.... > Barking out your blanket warning in a thread on *the exact use case > slots were implemented to address* just makes you look like a mindless > reactionary. Stick to posting your warning in threads where people ask > how to stop "other people" from setting attributes on "their" > instances. Agreed. I'd like to hear more about what kind of performance gain can be obtained from "__slots__". I'm looking into ways of speeding up HTML parsing via BeautifulSoup. If a significant speedup can be obtained when navigating large trees of small objects, that's worth quite a bit to me. John Nagle SiteTruth From tenax.raccoon at gmail.com Wed Dec 19 12:34:50 2007 From: tenax.raccoon at gmail.com (Jason) Date: Wed, 19 Dec 2007 09:34:50 -0800 (PST) Subject: 3D plotting with python 2.5 on win32 References: <4ea5d1e6-0f25-4006-b72a-42ba2ac5b8e1@e23g2000prf.googlegroups.com> Message-ID: <02fa9e44-2e0c-4d8b-b438-5cd2b590e720@w40g2000hsb.googlegroups.com> On Dec 19, 7:15 am, anton wrote: > Hi, > > I would like to know if some of you knows a > > - working > > - actual > > - out of the box (for me: binaries available) > > Package/Lib to do 3D plotting out of the box. > > I know matplotlib. > > There is MayaVi from enthon but you need to use their python (2.4.3), > all other stuff need picking sources etc. > > IVuPy-0.1 seems to be abandonware, and there are no binaries. > > I don't get qwtplot3d-0.2.7 to compile on my pc, it seems you need the > commercial > qt 4.33 (with opensource qt 4.3.3 I doesnt work). > > Actually there is a big list on python org of 3D software, but I need > only plotting facility (like Matlab for example), and some/most of > the listed projects seem not be up to date (still based on python 2.4, > like PyOpenGL where you get binaries only for python 2.4, > seems to be abandonware too, sigh). > > Thanks for a hint :-) PyOpenGL isn't abandonware. Python 2.5 comes with the ctypes module [1], so there isn't any need for a binary wrapper module anymore. Under 2.5, all pure "wrapper" binary modules are unnecessary. They can work cross-platform from pure Python, calling directly into the C function code. Trust me, this is an excellent improvement. PyOpenGL probably too low-level for what you want, but it isn't dead yet. (It's just pining for the symbol table.) --Jason [1] http://docs.python.org/lib/module-ctypes.html From mkevac at gmail.com Sat Dec 22 10:02:40 2007 From: mkevac at gmail.com (Kevac Marko) Date: Sat, 22 Dec 2007 07:02:40 -0800 (PST) Subject: Twisted: UDP socket not closed. Message-ID: Hi. I have to send UDP packets very often. Approx twice in a second. But socket is not closed after sending packet. So soon i bump into open sockets\files limit. How to close socket after sending data? Python 2.5, Twisted class DataClient(DatagramProtocol): def __init__(self, address, datagram = "PONG"): self.address, self.datagram = address, datagram def startProtocol(self): self.transport.socket.setsockopt(socket.SOL_SOCKET, \ socket.SO_BROADCAST, True) self.transport.connect(self.address[0], self.address[1]) self.sendDatagram() def sendDatagram(self): self.transport.write(self.datagram) debug("Data client: Sending to %s" % repr(self.address)) while True: clientprotocol = DataClient(("255.255.255.255", 5999), data) reactor.listenUDP(0, clientprotocol).stopListening() knight at rknb:~$ ls -la /proc/15429/fd/ | wc -l 43 knight at rknb:~$ ls -la /proc/15429/fd/ | wc -l 44 knight at rknb:~$ ls -la /proc/15429/fd/ | wc -l 44 knight at rknb:~$ ls -la /proc/15429/fd/ | wc -l 44 knight at rknb:~$ ls -la /proc/15429/fd/ | wc -l 45 knight at rknb:~$ ls -la /proc/15429/fd/ | wc -l 45 knight at rknb:~$ ls -la /proc/15429/fd/ | wc -l 46 Thanks in advance. From anne.nospam01 at wangnick.de Mon Dec 31 07:06:31 2007 From: anne.nospam01 at wangnick.de (anne.nospam01 at wangnick.de) Date: Mon, 31 Dec 2007 04:06:31 -0800 (PST) Subject: Unexpected __metaclass__ method behavior References: <2273796e-87c6-4100-a5b5-1c6afa32a276@i29g2000prf.googlegroups.com> Message-ID: Well, you see, I have some database functions that deal with "things" which are either classes or instances thereof. I though polymorphism would be a nice way to handle them identically, like: def do(thing): thing.Foo() do(t) do(Test) But never mind, I now understand that Test.__dict__ can contain only one entry for 'Foo', and that this must be matched. Kind regards, Sebastian From jigisbert.etra-id at grupoetra.com Wed Dec 5 02:36:19 2007 From: jigisbert.etra-id at grupoetra.com (Jose Ignacio Gisbert) Date: Wed, 5 Dec 2007 08:36:19 +0100 Subject: RV: Receiving messages blocks all :-( Message-ID: <001501c83711$88b4a150$2000a8c0@depid.local> First, sorry for sending this mail to this list, I know this is off-topic, but xmpppy-devel mailing list is out of work :-( If someone uses xmpppy, please try to answer me, or at least give me a more adequate mailing list, please. Thank you. ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- --------- Hi all, I am a newby in xmppy, and I want to make a very simple messaging jabber client. As I read from different tutorials, it seems very easy, in fact, I can send messages to other jabber clients from my ?poor? application, but the problem appears when I try to receive messages. I do more or less what Sebastian Moors explains in his ?xmpppy: a practical guide?, i.e (code fragment): def StepOn(conn): try: conn.Process(1) except KeyboardInterrupt: return 0 return 1 def GoOn(conn): while StepOn(conn): pass cl=xmpp.Client(jid.getDomain(),debug=[]) cl.connect() cl.auth(jid.getNode(),jidparams['password']) cl.sendInitPresence() cl.RegisterHandler('message',messageCB) cl.RegisterHandler('presence',presenceCB) GoOn(cl) But when my application enters in GoOn loop, it completely freezes (I have to shut down it by force). Anyone knows why or knows another solution for receiving messages?, I?m using Windows but I don?t think it is the problem. Thanks in advance, best regards, _______________________________ Jos? Ignacio Gisbert Sanus -------------- next part -------------- An HTML attachment was scrubbed... URL: From vladimir at greenmice.info Tue Dec 18 03:53:19 2007 From: vladimir at greenmice.info (Vladimir Rusinov) Date: Tue, 18 Dec 2007 11:53:19 +0300 Subject: Rounding In-Reply-To: <567047.82204.qm@web57302.mail.re1.yahoo.com> References: <567047.82204.qm@web57302.mail.re1.yahoo.com> Message-ID: On 12/15/07, katie smith wrote: > > if i have a number 6.345 and i wanted it to be 6 without subtracting .345 > because it won't always be .345 what do i do? > > how do i round to the nearest whole number. Or in this case round down. Is > there an easy way to round down to the nearest whole number? init() ? -- Vladimir Rusinov GreenMice Solutions: IT-??????? ?? ???? Linux http://greenmice.info/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Dec 4 11:02:03 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 04 Dec 2007 17:02:03 +0100 Subject: Escaping the semicolon? In-Reply-To: <7dd5d462-b8a3-4260-92b9-3c75cd75995f@x69g2000hsx.googlegroups.com> References: <7dd5d462-b8a3-4260-92b9-3c75cd75995f@x69g2000hsx.googlegroups.com> Message-ID: <475579fb$0$5448$426a74cc@news.free.fr> Nick a ?crit : > Hi all, > > Is this expected behavior? > >>>> s = '123;abc' >>>> s.replace(';', '\;') > '123\\;abc' >>> print s.replace(';', '\;') 123\;abc > I just wanted a single backslash. You got it - even if it's not obvious !-) > I can see why this probably happens > but i wondered if it is definitely intentional. >>> s2 = '123\;abc' >>> s2 '123\\;abc' >>> print s2 123\;abc >>> list(s2) ['1', '2', '3', '\\', ';', 'a', 'b', 'c'] As you can see, '\\' is counted as a single character !-) Since the backslash is the escape character, you need to escape it to have a litteral backslash: >>> s3 = '\' File "", line 1 s3 = '\' ^ SyntaxError: EOL while scanning single-quoted string >>> From rocco.rossi at gmail.com Fri Dec 14 10:25:42 2007 From: rocco.rossi at gmail.com (rocco.rossi at gmail.com) Date: Fri, 14 Dec 2007 07:25:42 -0800 (PST) Subject: Loops and things Message-ID: <41b40fae-5ca7-4823-851d-bba2aaca3bcd@t1g2000pra.googlegroups.com> I was wondering how and if it's possible to write a loop in python which updates two or more variables at a time. For instance, something like this in C: for (i = 0, j = 10; i < 10 && j < 20; i++, j++) { printf("i = %d, j = %d\n", i, j); } So that I would get: i = 0, j = 0 i = 1, j = 1 i = 2, j = 2 ... ... ... i = 9, j = 19 Can this be done in Python? Thanks. From jfabiani at yolo.com Thu Dec 20 10:44:19 2007 From: jfabiani at yolo.com (johnf) Date: Thu, 20 Dec 2007 07:44:19 -0800 Subject: where is uno? Message-ID: I'm using SUSE 10.3 have installed OpenOffice Python interface from the distro DVD. But still I need help because I can't "import uno". And that's because it's not in my site-packages. I read about how to use it and have reviewed code that uses it but no where did any of the articles explain where to retrieve the actual 'uno' py package. Can someone provide a hint? Johnf From matthieu.brucher at gmail.com Tue Dec 18 03:23:07 2007 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Tue, 18 Dec 2007 09:23:07 +0100 Subject: OpenOpt install In-Reply-To: References: <65e61980-a21b-4ba2-81f2-a2c23ccb43f2@1g2000hsl.googlegroups.com> <89ecef85-b670-40ab-bc8a-74271ff4cff0@y5g2000hsf.googlegroups.com> Message-ID: Hi, My solution was the correct way to go, IIRC, only a few changes were to be done so that those files were detected correctly (I think there were some __init__.py files that were not present this may have to do with the fact that you add a lot of additional paths in sys.path when you load openopt, but I already told you we should simplify this). Matthieu 2007/12/18, dmitrey : > > When earlier OpenOpt versions had been installed there were no > compiled pyc-files (in destination directory). I called to mailing > list but no obvious receipt had been achieved. Matthieu had done some > changes but it yielded other mistakes (no some py-files detected or > kind of), so I had removed those changes and write my own, for to have > OO py-files being compiled when installed, because next time when they > will be run user may not have root permissions, so he will recompile > source files each time OO starts. > > On Dec 17, 10:27 pm, Robert Kern wrote: > > dmitrey wrote: > > > Use > > > python setup.py install > > > > People should be able to run the distutils commands independently. > > > > What are you trying to achieve with this block of code that follows the > setup() > > call? > > > > new_name = 'tmp55' > > os.rename('scikits', new_name) > > newPath = [] > > for directory in sys.path: > > if not 'scikits' in directory: newPath.append(directory)# > something > > wrong with list.remove() > > sys.path = newPath > > import scikits > > reload(scikits) > > Path = scikits.__path__[0] > > NewPath = os.path.join(Path, 'openopt') > > rmtree(NewPath, True) # True means ignore errors > > copytree(os.path.join(os.path.curdir, new_name, 'openopt'), NewPath) > > NewPath = Path > > compileall.compile_dir(NewPath) > > > > os.rename(new_name, 'scikits') > > > > This just looks like a really bad idea. > > > > -- > > Robert Kern > > > > "I have come to believe that the whole world is an enigma, a harmless > enigma > > that is made terrible by our own mad attempt to interpret it as though > it had > > an underlying truth." > > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list > -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -------------- next part -------------- An HTML attachment was scrubbed... URL: From yozara at terra.es Tue Dec 4 03:38:33 2007 From: yozara at terra.es (Zara) Date: Tue, 04 Dec 2007 09:38:33 +0100 Subject: "Python" is not a good name, should rename to "Athon" References: <78bdd499-a263-4c68-8e43-e3e59b111c7e@a39g2000pre.googlegroups.com> <5rcq90F13re18U1@mid.individual.net> <2bd39781-94e2-4d3d-b185-47a247d3acc2@d27g2000prf.googlegroups.com> Message-ID: On Sat, 1 Dec 2007 13:40:10 -0800 (PST), "Russ P." wrote: >On Dec 1, 12:47 pm, "J. Clifford Dyer" wrote: >> On Sat, 2007-12-01 at 12:10 -0800, Russ P. wrote: >> > On Dec 1, 2:10 am, Bjoern Schliessmann > > mail-0306.20.chr0n... at spamgourmet.com> wrote: >> > > Russ P. wrote: >> > > > I agree that Python is not a good name for a programming language, >> >> > > Why not? >> >> > Think about proposing its use to someone who has never heard of it >> > (which I did not too long ago). As the OP pointed out, a Python is a >> > snake. Why should a programming language be named after a snake? >> >> That's not a persuasive argument. >> >> First of all, Python is named for a comedy troupe from England. For >> comparison, Perl is named for a knitting technique, Lisp is named for a >> speech impediment, Ruby is named for a rock, Smalltalk is named for a >> not-so-useful form of communication, and Java is named after a beverage >> or an island. >> >> Which of those is a good name for a programming language by your >> criterion? > >None. None of them are good names by my criteria. But then, a name is >only a name. One of the few names I like is Pascal, because he was a >great mathematician and scientist. > >After thinking about it a bit, here are examples of what I would >consider a good name for a programming language: > >Newton# >Newton* >Newton+ > >Newton was a great scientist, and his name is easy to spell and >pronounce. The trailing character serves to disambiguate it from >Newton in online searches. For shorthand in online discussions, N#, >N*, or N+ could be used as aliases. > >Names of other great scientists, mathematicians, or computer >scientists could also be used, of course. Take your pick. > >How about renaming Python3000? I would never use the name of a mathematician for a procedural language. Mathemathician names should be for funtional languages (such as Haskell). Procedural languages are flexible, they keep on tangling and getting out of it, they like publicity: Houdini or, as suggested in other messages: Houdini3 Best regards, Zara From lists at cheimes.de Wed Dec 12 21:56:29 2007 From: lists at cheimes.de (Christian Heimes) Date: Thu, 13 Dec 2007 03:56:29 +0100 Subject: Improvements to the Python core In-Reply-To: References: Message-ID: <47609F5D.8040405@cheimes.de> Paul Boddie wrote: > Then you haven't been reading the right IRC channel recently. ;-) What's the right channel? I'm on #python and #python-dev > Indeed, but there's arguably a certain amount of deadlock around > making unpatched, released versions of Python available in all these > places, unless there's been some activity below the surface in the > python-dev community on things like cross-compilation and not running > distutils using the newly built Python executable (which, as I > remember, was but one of the problems). Your point stands, naturally, > but if there's potential for some real movement on some > uncontroversial issues, and yet we see no movement, one remains > skeptical about getting even slightly controversial improvements into > vanilla CPython. I don't get your point, especially when you talk about distutils. Please elaborate. (C)Python has a well known process to get new features or changes into the language: Write a PEP, convince enough core developers and/or Guido, implement the feature. I don't see a PEP about JIT in the list at abouthttp://www.python.org/dev/peps/, do you? :] Besides nobody is going to stop you from creating a fork. Christian Tismer forked of stackless years ago. It's a successful branch with useful additions to the language. It got never merged back because Christian didn't feel right about it. > Perhaps, but what would people prefer: yet more language bolt-ons or > better performance? I prefer a fast, stable and maintainable Python over a faster but unstable. > It will be interesting to see what happens with recent work on > improving threading within CPython. As for Psyco (which perhaps offers > concurrency benefits only through instruction-level parallelism, if we > briefly consider that topic), I can understand that just-in-time > compilation can bring certain penalties in terms of memory usage and > initialisation times (as Java virtual machines have demonstrated), but > there's a compelling argument for trying to make such technologies > available to CPython if they can be switched off and won't then incur > such penalties. But we presumably return to the point of people not > wanting to touch code that has anything to do with such features: a > combination of social factors and the priorities of the group. Rhamph is working on a GIL-less Python version. It may become a compile time option someday in the future. Others have worked hard to speed up other parts of Python. We have multiple pending patches which speed up small parts of Python. Some are related to peephole (byte code optimizations), other patches speed up attribute access on classes or globals. The global lookup patch makes globals as fast as locals. I've done my share for the poor Windows souls when I created the VS 2008 PCbuild9 directory and enabled PGO builds. PGO builds are about 10% faster than ordinary VS 2008 builds. VS 2008 should be slightly faster than VS 2003 but I can bench mark it on my machine. In my opinion an optional JIT as compile time or startup option has good chances to become part of the CPython implementation. You "only" have to replace ceval.c ... :] Christian From mattb at wageslavery.org Sat Dec 1 20:31:24 2007 From: mattb at wageslavery.org (Matt Barnicle) Date: Sat, 1 Dec 2007 17:31:24 -0800 (PST) Subject: python newbie - question about lexical scoping In-Reply-To: <49832.75.62.111.233.1196556017.squirrel@webmail.wageslavery.org> References: <49832.75.62.111.233.1196556017.squirrel@webmail.wageslavery.org> Message-ID: <50590.75.62.111.233.1196559084.squirrel@webmail.wageslavery.org> >> On Dec 1, 4:47 pm, Matt Barnicle wrote: > aye yaye aye... thanks for the pointers in the right direction.. i > fiddled around with the code for a while and now i've reduced it to the > *real* issue... i have a class dict variable that apparently holds its > value across instantiations of new objects.. the problem can be > illustrated in the following much simpler code: > >>>> class foo(): > ... bar = { 'baz': 'bing' } > ... >>>> a = foo() >>>> a.bar > {'baz': 'bing'} >>>> a.bar['baz'] = 'bong' >>>> a.bar > {'baz': 'bong'} >>>> b = foo() >>>> b.bar > {'baz': 'bong'} ok, i see... python has a concept i'm not accustomed to which i found described here: http://zephyrfalcon.org/labs/python_pitfalls.html 4. Class attributes vs instance attributes so i'm sure what is going on is obvious to experienced python programmers... i'm not really sure how to get around this though. i'll need to spend some time on reworking our models code i guess... i inherited this from someone, and what he was trying to do was to set default values for objects representing tables (in kind of a simple ORM layer) and storing the values in a dict, and when the object is instantiated, the table is queried and the default dict values are overwritten. so obviously this method is not going to work as such.. sorry for the misdirection, i didn't quite understand at first.. - m@ From arkanes at gmail.com Thu Dec 13 13:54:44 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 13 Dec 2007 12:54:44 -0600 Subject: python vs perl performance test In-Reply-To: <3b1cef63-f1dc-466c-bf8c-7613fb4b0c3f@a35g2000prf.googlegroups.com> References: <3b1cef63-f1dc-466c-bf8c-7613fb4b0c3f@a35g2000prf.googlegroups.com> Message-ID: <4866bea60712131054g69abbc6ete6b205a7c4c8b568@mail.gmail.com> On Dec 13, 2007 12:11 PM, wrote: > First, let me admit that the test is pretty dumb (someone else > suggested it :) but since I am new to Python, I am using it to learn > how to write efficient code. > > my $sum = 0; > foreach (1..100000) { > my $str = chr(rand(128)) x 1024; > foreach (1..100) { > my $substr = substr($str, rand(900), rand(100)); > $sum += ord($substr); > } > } > print "Sum is $sum\n"; > > Basically, the script creates random strings, then extracts random > substrings, and adds up the first characters in each substring. This > perl script takes 8.3 secs on my box and it can probably be improved. > > When I first translated it to Python verbatim, the Python script took > almost 30 secs to run. > So far, the best I can do is 11.2 secs using this: > > from random import randrange > from itertools import imap, repeat > from operator import getitem, add, getslice > > result = 0 > zeros = [0]*100 > for i in xrange (100000): > s = [chr(randrange(128))] * 1024 > starts = repeat(randrange(900), 100) > ends = imap(add, starts, repeat(randrange(1,100), 100)) > substrs = imap(getslice, repeat(s, 100), starts, ends) > result += sum(imap(ord, imap(getitem, substrs, zeros))) > > print "Sum is ", result > > There's got to be a simpler and more efficient way to do this. > Can you help? Benchmarking is usually done to test the speed of an operation. What are you trying to measure with this test? String slicing? Numerical operations? Looping? You're doing all sorts of bogus work for no reason. The use of randomness is also totally arbitrary and doesn't do anything except make it harder to confirm the correctness of the test. Is the ability to generate 0-length substrings (which perl claims have an ordinal of 0) intentional? For the record, taking the randomness out makes this take 4 seconds for perl, and 6 seconds for a literal translation in python. Moving it into a function drops the python function to 3.5 seconds. From davidtweet at gmail.com Sat Dec 1 22:21:28 2007 From: davidtweet at gmail.com (David Tweet) Date: Sat, 1 Dec 2007 19:21:28 -0800 Subject: [OT] minimalist web server In-Reply-To: References: <7xy7cdke3g.fsf@ruckus.brouhaha.com> Message-ID: <3fd0162e0712011921p115ed680s9a041a0f19d49ed4@mail.gmail.com> Running this in Python should create a server running on localhost port 80 that only serves blank pages: import SimpleHTTPServer import SocketServer class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): print >> self.wfile, "" server = SocketServer.TCPServer(("", 80), MyHandler) server.serve_forever() (also see http://effbot.org/librarybook/simplehttpserver.htm) On Dec 1, 2007 7:02 PM, Daniel Fetchinson wrote: > > > I'm looking for the most minimalist web server ever that does nothing > > > else than return a fixed static page for every request. Regardless of > > > what the request is, it just needs to be an HTTP request to port 80, > > > the web server should return always the same html document. What would > > > be the best choice for this? The goal is of course to minimize system > > > resources in terms of memory, cpu, etc, etc. > > > > If you're running linux, maybe you want tux. > > > > publicfile isn't exactly what you describe, but its description might > > be of some interest: > > > > http://cr.yp.to/publicfile.html > > > Thanks, tux looks good, the only problem is that one needs to > recompile the kernel which I really don't want to do (so yes, I'm on > linux). Publicfile seems to "know" already too much. > > The reason I need this is that my current best strategy to avoid ads > in web pages is putting all ad server names into /etc/hosts and stick > my local ip number next to them (127.0.0.1) so every ad request goes > to my machine. I run apache which has an empty page for 404 errors so > I'll just see that blank page for every ad. Now I guess apache is a > pretty heavy weight guy so I'm looking for a lightweight alternative. > Lighttpd, nginx and company are all too complex and "know" too much. I > even considered just putting netcat into an infinite loop but I'm > afraid if there is a security hole in netcat I might be screwed. > > Maybe now that I outlined a little more why I need this others can > come up with more suggestions. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -David From robert.kern at gmail.com Wed Dec 19 04:38:14 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 19 Dec 2007 03:38:14 -0600 Subject: how to get string printed by PyErr_Print( )? In-Reply-To: References: Message-ID: grbgooglefan wrote: > PythonC API function PyErr_Print( ) prints an error string onto stderr > if PyErr_Occurred() is true. > I don't want to print this to stderr because my Python+C code is > running daemon mode & won't have terminal / stderr. > So, I want to retrieve the string which PyErr_Print( ) will print. > E.g., PyErr_Print() printed following string when I tried to call > setTuple with one extra argument > Traceback (most recent call last): > File "", line 2, in isTacticSafe > IndexError: tuple assignment index out of range > > How do I get this error message in a local char* & use it for further > error handling? > > Also, is there any way to get an error number associated for these > error conditions using some getError function on the object returned > by PyErr_Occurred()? PyErr_Print() will import the sys module and try to use whatever file-like object is sys.stderr. Replace this with a StringIO or an open file object just like you would for output from the Python level. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From showell30 at yahoo.com Sat Dec 8 15:37:42 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 8 Dec 2007 12:37:42 -0800 (PST) Subject: Newbie edit/compile/run cycle question In-Reply-To: <475af655$0$28302$426a34cc@news.free.fr> Message-ID: <700244.69501.qm@web33505.mail.mud.yahoo.com> --- Bruno Desthuilliers wrote: > MartinRinehart at gmail.com a ?crit : > > I'm a java guy used to the effective edit/run > cycle you get with a > > good IDE. > > > > Today I'm writing my first Python, but can't seem > to find the way to > > use Python's inherent edit/run cycle. > > > > Use an IDE then. Or a real code editor like emacs - > it's python-mode is > way more powerful than what I saw in any IDE. Martin, for Python-specific IDEs, I recommend looking at the following page, although I think you might want to get some feedback from the list as well: http://c2.com/cgi/wiki?PythonIde Having said that, I'm more in Bruno's camp that the choice of an editor usually transcends Python. I prefer to use a powerful editor that's good for working on several languages, as long as it has a good Python mode. There are a zillion powerful editors out there. I've been productive in EditPlus, MultiEdit, SlickEdit, vim, and emacs, just to throw out a few examples. I'm confident you'll find a solution that fits your style, and you are obviously doing a good thing in terms of optimizing edit/run cycle, as it's pretty key to productivity. ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From victorsubervi at gmail.com Fri Dec 14 09:50:26 2007 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 14 Dec 2007 10:50:26 -0400 Subject: [Plone-Users] Why Can't I Do This? In-Reply-To: <4762955B.2080403@trueblade.com> References: <4dc0cfea0712140624j3eee0726q893062d14107c595@mail.gmail.com> <4762955B.2080403@trueblade.com> Message-ID: <4dc0cfea0712140650v6933439cq5638d2fffccd837c@mail.gmail.com> Great! Thanks! On Dec 14, 2007 10:38 AM, Eric Smith wrote: > Victor Subervi wrote: > > Hi; > > Why can't I do this? > > > > >>> author = "By Juan Garcia" > > >>> if author[0:2] == "by " | "By " | "BY": > > ... author = author[3:] > > ... > > Traceback (most recent call last): > > File "", line 1, in ? > > TypeError: unsupported operand type(s) for |: 'str' and 'str' > > > > This is a python question, not a plone question. The python logical or > operator is "or", but for this you might want to use "in". This code > might point you in the right direction, although it's not a complete (or > very good) solution: > > author = "By Juan Garcia" > if author[0:2] in ["by", "By", "BY"]: > author = author[2:] > print author > > ------------------------------------------------------------------------- > SF.Net email is sponsored by: > Check out the new SourceForge.net Marketplace. > It's the best place to buy or sell services > for just about anything Open Source. > > http://ad.doubleclick.net/clk;164216239;13503038;w?http://sf.net/marketplace > _______________________________________________ > Plone-Users mailing list > Plone-Users at lists.sourceforge.net > https://lists.sourceforge.net/lists/listinfo/plone-users > -------------- next part -------------- An HTML attachment was scrubbed... URL: From DustanGroups at gmail.com Thu Dec 13 20:17:57 2007 From: DustanGroups at gmail.com (Dustan) Date: Thu, 13 Dec 2007 17:17:57 -0800 (PST) Subject: Python implementation of "include" References: <44880.192.168.1.71.1197575420.webmail@192.168.1.71> Message-ID: > ll... at paisite.com wrote: > > Hello, > > > I've been using the Python-based Karrigell web application framework. > > It has the very handy word "include" that inserts a code file into > > into the stream of execution. E.g. if myFile.py contains the code: > > > print "This is a message from myFile.py
" > > > and my script is: > > > print "Something
" > > include "myFile.py" > > print "Something more
" > > > The output would be: > > > Something > > This is a message from myFile.py > > Something more > > > Since I'm considering moving my application to a different web > > application framework, I'd like to replace include with a pure python > > construct. I've discovered several ways to do it, but they all seem > > kludgy in one way or another. Is there a simple, elegant way to do this? No. Python is not C. The closest you can get is: from myFile import * print some_variable_from_myFile But instead, you should probably just import: import myFile print myFile.some_variable_from_myFile From bj_666 at gmx.net Mon Dec 17 09:36:17 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 Dec 2007 14:36:17 GMT Subject: checking for negative values in a list References: <9be8b3e1-e9c6-40ba-b104-9ca406ecff59@e6g2000prf.googlegroups.com> Message-ID: <5snfr1F19o1laU4@mid.uni-berlin.de> On Mon, 17 Dec 2007 06:20:23 -0800, vimal wrote: > i have a list of numbers > > say a = [1,-1,3,-2,4,-6] > > how should i check for negative values in the list In [6]: a = [1, -1, 3, -2, 4, -6] In [7]: any(n < 0 for n in a) Out[7]: True Ciao, Marc 'BlackJack' Rintsch From lukasz.f24 at gmail.com Wed Dec 5 04:43:49 2007 From: lukasz.f24 at gmail.com (lukasz.f24 at gmail.com) Date: Wed, 5 Dec 2007 01:43:49 -0800 (PST) Subject: Timezones in python References: Message-ID: Thanks guys for your answers! I know those library's but I was wondering is there something build-in for this simple convert convert. I have to do it only from +4 to +0. From fuck at spammer.sp Sat Dec 29 14:15:39 2007 From: fuck at spammer.sp (Lorenzo Mainardi) Date: 29 Dec 2007 19:15:39 GMT Subject: Howto on callbacks, queues and good design patterns References: <47766da0$0$2085$edfadb0f@dtext02.news.tele.dk> Message-ID: <47769cdb$0$17944$4fafbaef@reader1.news.tin.it> Nel mezzo del cammin di nostra vita, mi ritrovai con Michael Bernhard Arp S?rensen che diceva: > Hi there. > > As a newbie, I need to learn about callbacks and queues(syntax and > examples) working together. > > At work we talk a lot about design patterns. Does any of you know a good > site about that or any good books from Amazon? > Hello, I think the best way to understanding queues and callbacks is to learn Twisted. That's a very big framework for asynchronous network programming; it's completely callback based. For more info you should visit the Twisted Matrix website: http:// twistedmatrix.com/trac/ There also a good documentation, but it's a few embedded, so you need to looking for that with care:-) Good 2008 and have fun! -- "Le opinioni dei fanatici prescindono dai fatti" python -c "print 'bG9ybWF5bmFAZ21haWwuY29t'.decode('base64')" From showell30 at yahoo.com Sun Dec 9 11:17:41 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 9 Dec 2007 08:17:41 -0800 (PST) Subject: reading list of list to a file In-Reply-To: <14239876.post@talk.nabble.com> Message-ID: <204118.16545.qm@web33507.mail.mud.yahoo.com> --- caroliina wrote: > > i made a list of lists but i cant write it into a > file. how do i get the > first string in a sublist? > -- Try doing this: print list_of_lists print list_of_lists[0] print list_of_lists[0][0] print list_of_lists[0][0][0] It might give you some insight. If you're still stuck after that, it would help if you posted a little bit of your code. Good luck! ____________________________________________________________________________________ Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Dec 26 03:28:13 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 26 Dec 2007 09:28:13 +0100 Subject: how to generate html table from "table" data? In-Reply-To: References: Message-ID: <4772109d$0$5194$426a34cc@news.free.fr> petr.jakes.tpc at gmail.com a ?crit : > Hi group, > I would like to convert the output of the SQL query, or more generally > I would like to convert any "table" data to the html table. There's MoreThanOneWayToDoIt... from simple string formatting to a full-blown template engine. > I would like to set some rules to format cells, columns or rows (font, > colour etc.) of the html table, according to the values in the > specific cells. Markup should only convey semantic informations - presentation is best done using css. IOW : presentation-related stuff in the html should be restricted to css class declarations. > Googling for a while I have found only this tool: > http://pasko.net/PyHtmlTable/ > > Your tips to some other tools or/and your suggestion how to solve > above mentioned will be very helpful. As I said, wrt/ html generation, there are quite a lot of possible solutions - FWIW, generating an html table from a set of tabular data is nothing difficult. So without more information on the context, it's hard to give any valuable advice. Are you doing a web application ? If yes, you should already use a template engine, so just use it. Else, why is your application generating html at all ? From bearophileHUGS at lycos.com Thu Dec 6 10:42:34 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 6 Dec 2007 07:42:34 -0800 (PST) Subject: multidimensional "arrays" References: Message-ID: <56f116fa-3ac0-4833-bd1a-f3429a7454ad@s36g2000prg.googlegroups.com> Horacius ReX: > do you know how to do similar but in two dimensions ? >>> nr = 3 >>> nc = 4 >>> [[None] * nc for _ in xrange(nr)] [[None, None, None, None], [None, None, None, None], [None, None, None, None]] Bye, bearophile From chrisspen at gmail.com Tue Dec 11 17:31:22 2007 From: chrisspen at gmail.com (Chris) Date: Tue, 11 Dec 2007 14:31:22 -0800 (PST) Subject: Matching XML Tag Contents with Regex References: <38ea9cbc-a222-4c0f-ba2d-f6b415d02fb1@d27g2000prf.googlegroups.com> <4e09aece-f39f-4c5b-a966-ac6abfb3f7de@p69g2000hsa.googlegroups.com> <3cdbc226-bb3a-4945-949b-a0ec28b0e5c0@e6g2000prf.googlegroups.com> <5s8205F186vhuU1@mid.uni-berlin.de> Message-ID: <55392af5-b474-4118-8346-f81185d6b231@b1g2000pra.googlegroups.com> On Dec 11, 1:08 pm, "Diez B. Roggisch" wrote: > Chris wrote: > > On Dec 11, 11:41 am, garage wrote: > >> > Is what I'm trying to do possible with Python's Regex library? Is > >> > there an error in my Regex? > > >> Search for '*?' onhttp://docs.python.org/lib/re-syntax.html. > > >> To get around the greedy single match, you can add a question mark > >> after the asterisk in the 'content' portion the the markup. This > >> causes it to take the shortest match, instead of the longest. eg > > >> <%(tagName)s\s[^>]*>[.\n\r\w\s\d\D\S\W]*?[^(%(tagName)s)]* > > >> There's still some funkiness in the regex and logic, but this gives > >> you the three matches > > > Thanks, that's pretty close to what I was looking for. How would I > > filter out tags that don't have certain text in the contents? I'm > > running into the same issue again. For instance, if I use the regex: > > > <%(tagName)s\s[^>]*>[.\n\r\w\s\d\D\S\W]*?(targettext)+[^(% > > (tagName)s)]* > > > each match will include "targettext". However, some matches will still > > include , presumably from the tags which didn't contain > > targettext. > > Stop using the wrong tool for the job. Use lxml or BeautifulSoup to parse & > access HTML. > > Diez I was hoping a simple pattern like .*text.* wouldn't be too complicated for Regex, but now I'm starting to agree with you. Parsing the entire XML Dom would probably be a lot easier. From roy at panix.com Sun Dec 2 15:53:55 2007 From: roy at panix.com (Roy Smith) Date: Sun, 02 Dec 2007 15:53:55 -0500 Subject: Limit Guessing Algorithm References: <6527e349-27ba-4de4-bc29-75ff4511787c@b40g2000prf.googlegroups.com> Message-ID: In article <6527e349-27ba-4de4-bc29-75ff4511787c at b40g2000prf.googlegroups.com>, "ram.rachum at gmail.com" wrote: > Hello hello, > > I'm looking for a piece of code, preferably in Python, that will do > the following. It will accept a few data points (x,f(x)) of a function > that converges to some finite value when x converges to infinity. I > need the algorithm to guess what that limit is, to whatever precision > it can. > > For example, if the input is: > > [ > [1,8], > [2,7.5], > [3,7.25], > [4,7.125] > ] > > Then the output will be 7. Or at least something close. > > Does anyone know anything like that? I suggest any introductory calculus or math analysis text. Perhaps even the one your professor assigned you for the course :-) Look under "limits" in the table of contents. From horpner at yahoo.com Thu Dec 13 10:09:05 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 13 Dec 2007 15:09:05 GMT Subject: Is Python really a scripting language? References: <009101c83c55$4ee07a00$6501a8c0@aristotle> <2bc2ab76-da7b-43ec-969d-33f77b174a56@e6g2000prf.googlegroups.com> <13m12513p8pfqb4@corp.supernews.com> Message-ID: On 2007-12-13, Steven D'Aprano wrote: > I have repeatedly argued in the past that we do ourselves a > disservice by describing Python as an interpreted language. > > Python is compiled. It has a compiler. It even has a built-in > function "compile". It's just not compiled to *machine code* -- > but with even machine code often running on a virtual machine > in the CPU(s), the distinction is far less important now than > it was when Sun described Java as a compiled language despite > the lack of JIT compilers. When folks say Python is an interpreted language I think they mean it informally--they just mean you have to run an interpreter to execute it. *How* it's translated is irrelevent to the *informal* meaning. And I'd further argue that the informal meaning is the only one that makes any sense. Formally: >>> hasattr(Language, 'iterpreted') False >>> hasattr(Implementation, 'interpreted') True ;-) -- Neil Cerutti From enleverlesX.XmcX at XmclaveauX.com Mon Dec 10 09:24:31 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Mon, 10 Dec 2007 15:24:31 +0100 Subject: GUI development with 3D view In-Reply-To: References: <5s4sc7F17o5duU1@mid.uni-berlin.de> Message-ID: <475d4e72$0$5086$ba4acef3@news.orange.fr> Hi! > no idea how it works with windows. On XP: fine. On Vista: very difficult... @+ MCI From JohnRoth1 at jhrothjr.com Fri Dec 14 01:27:59 2007 From: JohnRoth1 at jhrothjr.com (John Roth) Date: Thu, 13 Dec 2007 22:27:59 -0800 (PST) Subject: Windows XP unicode and escape sequences References: Message-ID: <6ddde505-d0f9-4b24-a2e2-804e15061973@t1g2000pra.googlegroups.com> On Dec 12, 2:51 pm, wrote: > I mainly work on OS X, but thought I'd experiment with some Python code on XP. The > problem is I can't seem to get these things to work at all. > > First of all, I'd like to use Greek letters in the command prompt window, so I was going to > use unicode to do this. But in the command prompt, the unicode characters are displaying > as strange looking characters. I tried installing the 'Bitstream Vera Sans Mono' font in hopes > it had all the characters I needed but this didn't seem to work either. Is the problem the font? > And if so, is there a certain font that has unicode '03B1', etc? Here's some code I tried: > > v = u'\u03B1\u03B2\u03B3'.encode('utf-8') > print v #just displays squares You've got two problems. First, you don't need to encode it; if the command prompt window displayed your output after encoding it would display the multi-byte form of your characters. You should just send it a unicode object. Second, check the .encoding attribute of the sys.stdout object. Therein lies enlightenment about what the command prompt window will accept. No info on your other problem. John Roth > > If anyone has any thoughts, I'd love to hear them. > > Thanks! > > Jay From jayabarathi2007 at gmail.com Mon Dec 3 00:39:30 2007 From: jayabarathi2007 at gmail.com (Barathi) Date: Sun, 2 Dec 2007 21:39:30 -0800 (PST) Subject: i need true friends like u Message-ID: It takes a minute to have a crush on someone, a hour to like someone, and a day to fall in love with someone, but it takes a lifetime to forget someone (Friend). http://jayabarathi.50webs.com/ From sturlamolden at yahoo.no Tue Dec 18 10:37:28 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Dec 2007 07:37:28 -0800 (PST) Subject: More than one interpreter per process? References: Message-ID: On 18 Des, 10:24, Roger Binns wrote: > You can. Have a look at mod_python and mod_wsgi which does exactly > this. But extension modules that use the simplified GIL api don't work > with them (well, if at all). mod_python implements use Py_NewInterpreter() to create sub- interpreters. They all share the same GIL. The GIL is declared static in ceval.c, and shared for the whole process. But ok, if PyEval_AquireLock() would take a pointer to a 'sub-GIL', sub- interpreters could run concurrent on SMPs. But it would require a separate thread scheduler in each subprocess. From ctrachte at gmail.com Sun Dec 30 21:42:50 2007 From: ctrachte at gmail.com (infixum) Date: Sun, 30 Dec 2007 18:42:50 -0800 (PST) Subject: Help please with code to find and move files. References: Message-ID: <79776f34-be23-470f-9fe7-56e3741075d3@l6g2000prm.googlegroups.com> > path = r"c:\\" I don't know if this is the whole problem, but this line should read r'c:\' (one backslash). From MonkeeSage at gmail.com Mon Dec 10 10:55:42 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: Mon, 10 Dec 2007 07:55:42 -0800 (PST) Subject: searching a value of a dict (each value is a list) References: <13lpc0el80j2p7d@corp.supernews.com> <1ddd41dd-1e2e-4312-adc1-f374e7f53def@l1g2000hsa.googlegroups.com> Message-ID: <106172f8-0dfb-4245-b08d-2dbe63b44250@w40g2000hsb.googlegroups.com> On Dec 10, 9:45 am, MonkeeSage wrote: > On Dec 10, 8:31 am, Neil Cerutti wrote: > > > > > On 2007-12-10, MonkeeSage wrote: > > > > If I'm not mistaken, building a reverse dictionary like that will be > > > O(n*m) because dict/list access is O(n) (ammortized). Somebody correct > > > me if I'm wrong. In that case, it really depends on how you will use > > > the dict to see whether you get any benefit from building the reversed > > > dict. If you want to do several lookups, then the initial overhead > > > (speed/memory) of building the reversed dict might be worth it so that > > > you can just run lookups at O(n). > > > It also depends on if the dictionary shall be mutated between > > reverse lookups. > > > > But if you only need it once, it is a waste of time and space > > > to create a reverse dict when your access time is the same for > > > the lookup as for building the reversed dict. > > > > If you do need more than one lookup, it would also be a good > > > optimization strategy to build the reverse dict in parallel, as > > > you execute the first search; that way you can combine the time > > > spent on building the reverse dict and the lookup, to get a > > > total of O(n*m) rather than O(n^2*m). The first search is > > > "free" since you need the reverse dict anyway. > > > It wouldn't be merely an optimization if reverse lookups and > > mutations were interleaved. > > > -- > > Neil Cerutti > > You only get a once-in-a-lifetime opportunity so many times. --Ike Taylor > > Well true, but you enter a whole other level of complexity in that > case...something like Theta(log(n*(m-n))). I might have calculated > that incorrectly, but that just goes to show how complex a lookup > is(!) in such a case. > > Regards, > Jordan Sorry for the double-post...google is being beligerant right now. From bj_666 at gmx.net Sun Dec 23 11:40:33 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 23 Dec 2007 16:40:33 GMT Subject: Passing by reference References: <34cade84-6f3d-46ad-a39d-377235a56689@x69g2000hsx.googlegroups.com> <27d0c1c4-6bab-42de-b3ab-af47a607326f@i29g2000prf.googlegroups.com> <13mloevf5jbkbac@corp.supernews.com> <254d6de7-7196-4059-a5de-84d81b820a97@e4g2000hsg.googlegroups.com> <476bc271$0$31106$426a34cc@news.free.fr> <47e0776a-c4b7-47c9-80ca-4670f168290b@21g2000hsj.googlegroups.com> <476c2bd1$0$6135$426a74cc@news.free.fr> <476d8aee$0$31237$426a74cc@news.free.fr> <6ccd480d-f2bd-41a1-b13a-c813fbd6a858@c4g2000hsg.googlegroups.com> Message-ID: <5t7hc1F1cjjhoU1@mid.uni-berlin.de> On Sun, 23 Dec 2007 03:10:48 -0800, MartinRinehart wrote: > Bruno, right now I've got this: > > def __init__ ( self, t ): > """ Constructor, called with array of strings. """ > > self.text = t > ... > > Some other program will say: > tok = Toker( text_array ) > tokens = tok.tokenize() > > So how does the constructor make the array of strings available to the > tokenize() method? Assuming the `__init__()` above belongs to the `Toker` class then the `tokenize()` method can access it via `self.text` of course. Ciao, Marc 'BlackJack' Rintsch From zip at got.no.mail Tue Dec 18 20:38:59 2007 From: zip at got.no.mail (__zip__) Date: Wed, 19 Dec 2007 02:38:59 +0100 Subject: pySerial In-Reply-To: References: Message-ID: Tnx for help. Done it. The problem was that returning bytes were on few lines and I didn't look after first \n :( tnx. From arkanes at gmail.com Tue Dec 18 13:24:36 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 18 Dec 2007 12:24:36 -0600 Subject: Changing intobject to use int rather than long In-Reply-To: References: Message-ID: <4866bea60712181024s5b4071ddn67fdc76e74055d3a@mail.gmail.com> On Dec 18, 2007 11:59 AM, Clarence wrote: > Does anyone think (or know) that it might cause any internal problems > if the ival member of the struct defining an intobject were to be > changed from its current "long int" to just "int"? > > When you move your application to a 64-bit system in order to get a > bigger address space to store your millions/billions of integers in > RAM, but they get twice as big, you don't gain very much. > Your int objects get twice as large, but you get 4294967296 times more address space. (They don't always get twice as large, and you don't actually get that much address space, and there's lots of other things wrong with this answer, but the core truth - that your available address space grows at a greater rate than the size of your ints - is correct). > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > From hennebry at web.cs.ndsu.nodak.edu Mon Dec 3 14:24:51 2007 From: hennebry at web.cs.ndsu.nodak.edu (Mike) Date: Mon, 3 Dec 2007 11:24:51 -0800 (PST) Subject: takes no arguments (1 given) References: <2b9a029c-20e4-4f20-9613-10617f6f540d@a39g2000pre.googlegroups.com> Message-ID: <334b5247-ef71-4d6d-ae3e-7dd41ca4b99f@l16g2000hsf.googlegroups.com> Oops. I just forgot self. From sgeiger at ncee.net Wed Dec 12 01:20:39 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Wed, 12 Dec 2007 00:20:39 -0600 Subject: Loading an exe icon into a pixmap/bitmap In-Reply-To: <968135a3-fde1-4f44-a1b7-cec64a4744e8@t1g2000pra.googlegroups.com> References: <968135a3-fde1-4f44-a1b7-cec64a4744e8@t1g2000pra.googlegroups.com> Message-ID: <475F7DB7.5040304@ncee.net> Are you looking for these kinds of tools? In Debian: icoutils - Extract MS Windows icons and cursors I don't recall where I saw this: FileJuicer - Extract images from Powerpoint, PDF, HTML, and CAB files ob.lutz at gmail.com wrote: > I've been searching for a way to load an icon from an executable into > something that I can eventually display either through pygame or > pygtk. I've tried the stuff found at > http://groups.google.com/group/comp.lang.python/browse_thread/thread/d7f61f270cce368/3ff38c1ced504e43?lnk=gst&q=win32+icon#3ff38c1ced504e43 > but the tests just output all black (not surprising, as that guy > couldn't get it to work either). I've mucked around with taht code and > the ExtractIcon stuff from pywin32, but still am stuck. I've seen some > reference to a wxpython ways to do it, but I'm trying to not have to > convert over to that. Any help is appreciated. Thanks > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From istvan.albert at gmail.com Sun Dec 30 15:32:04 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Sun, 30 Dec 2007 12:32:04 -0800 (PST) Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <4a5d4311-c5ec-4f3c-8800-c30ac30e399d@t1g2000pra.googlegroups.com> Message-ID: <601e4a81-a69a-4576-a276-41d82a256482@e50g2000hsh.googlegroups.com> On Dec 30, 11:26 am, George Sakkis wrote: > I'm with you on this one; IMHO it's one of the relatively few language > design missteps of Python, favoring the rare case as the default > instead of the common one. George, you pointed this out this link in a different thread http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877 how would you rewrite the code below if you could not use mutable default arguments (global variables not accepted)? Maybe there is a way, but I can't think of it as of now. --------------------------------------- def blocks(s, start, end): def classify(c, ingroup=[0]): klass = c==start and 2 or c==end and 3 or ingroup[0] ingroup[0] = klass==1 or klass==2 return klass return [tuple(g) for k, g in groupby(s, classify) if k == 1] print blocks('the {quick} brown {fox} jumped', start='{', end='}') From sgeiger at ncee.net Thu Dec 6 10:49:35 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Thu, 06 Dec 2007 09:49:35 -0600 Subject: which configparse? In-Reply-To: References: Message-ID: <47581A0F.7050900@ncee.net> Best, is naturally, a somewhat subjective evaluation. That being said, configparser is well regarded. I have also seen these two options that you might want to check out: http://wiki.woodpecker.org.cn/moin/Dict4Ini http://www.voidspace.org.uk/python/configobj.html > I have all my options setup with optparse. Now, I'd like to be able to > parse an ini file to set defaults (that could be overridden by command line > switches). > > I'd like to make minimal change to my working optparse setup (there are lots > of options - I don't want to duplicate all the cmdline parsing with ini > file parsing code) > > I've looked at configparse, cfgparse, iniparse. > > configparse looks like what I want, but it seems last commit was >2years > ago. > > What is the best choice? > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 257 bytes Desc: OpenPGP digital signature URL: From m.gritsch at gmail.com Mon Dec 24 15:04:33 2007 From: m.gritsch at gmail.com (Markus Gritsch) Date: Mon, 24 Dec 2007 21:04:33 +0100 Subject: Python DLL in Windows Folder In-Reply-To: <4866bea60712241007r1db5de8w75abab3c8a2e024e@mail.gmail.com> References: <533b7d320712230652w6bd4e90dv905d7112d337d0fd@mail.gmail.com> <533b7d320712231027h26623fffi3b471b6c85873a64@mail.gmail.com> <4866bea60712241007r1db5de8w75abab3c8a2e024e@mail.gmail.com> Message-ID: <533b7d320712241204o17f6a7bycbe9caf31a93652b@mail.gmail.com> On 24/12/2007, Chris Mellon wrote: > On Dec 23, 2007 12:27 PM, Markus Gritsch wrote: > > On 23/12/2007, Christian Heimes wrote: > > > Markus Gritsch wrote: > > > > why does the Python installer on Windows put the Python DLL into the > > > > Windows system32 folder? Wouldn't it be more clean to place it into > > > > the Python installation folder beside the python.exe file? > > > > > > It's the easiest and best way to expose Python for 3rd party > > > applications and COM. The DLL is removed by the Windows Installer when > > > its usage counter drops to 0. There is no need to worry ;) > > > > I am not worrying about an orphaned DLL. The Problem is that this way > > the Python DLL is being made available for 3rd party applications, > > which possibly need a version of Python which is compiled using > > another compiler. We are embedding Python into our application which > > gets compiled using MSVC 8.0. We like to link dynamically, so the > > Python interpreter is not statically linked into the program. The > > Python DLL from the Python installer in the Windows system32 folder is > > compiled using MSVC 7.1. > > > > > What the python installer is doing is the Right Thing for making the > standard python dll available to third party applications. But this forces the 3rd party application being compiled with the same compiler as the Python DLL which is MSVC 7.1 for Python 2.5 which is a quite old compiler nowadays. > Applications that want a specific version of a specific DLL should use > the mechanisms available for doing so, instead of relying on there > being a specific version of the python dll in the windows folder. We do not rely on having some specific version of the Python DLL in the Windows system 32 folder. However, the MSVC 7.1 compiled version gets in the way when using a different compiler. Kind regards, Markus From gagsl-py2 at yahoo.com.ar Tue Dec 18 21:06:54 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Dec 2007 18:06:54 -0800 (PST) Subject: askopenfilename() as root window References: Message-ID: On 18 dic, 22:43, Sean DiZazzo wrote: > Is there any way to open a Tkinter.askopenfilename() without opening a > root window alongside the file chooser? > > I simply want a script to open a dialog and return the chosen file's > path to stdout. Yes, create the root yourself so you can call the withdraw() method: root = Tk() root.withdraw() print askopenfilename() -- Gabriel Genellina From mdelliot at gmail.com Fri Dec 28 12:01:40 2007 From: mdelliot at gmail.com (Micah Elliott) Date: Fri, 28 Dec 2007 09:01:40 -0800 (PST) Subject: Building Python statically on linux References: <0300530c-5550-4fff-bac6-66dbfa1b82b9@d21g2000prf.googlegroups.com> <9c2ead09-d84d-4972-b3a2-8bff510fcb94@b40g2000prf.googlegroups.com> Message-ID: <526a1ce2-6a74-4b76-ba03-3c8aacdfbba3@e25g2000prg.googlegroups.com> On Dec 28, 5:44 am, Christian Heimes wrote: > Can you work on the topic and write a small howto for your wiki > (http://wiki.python.org/moin/)? Good idea. I've created a placeholder (with what I know so far, not much) to track this: http://wiki.python.org/moin/BuildStatically I'll plan to be updating it today if I can get it working. Anyone else is welcome to add their knowledge/experience. From ajauctionpro at gmail.com Thu Dec 6 06:17:18 2007 From: ajauctionpro at gmail.com (ajauctionpro at gmail.com) Date: Thu, 6 Dec 2007 03:17:18 -0800 (PST) Subject: Surfing Script Message-ID: <8a1a75e3-b994-4545-812d-0bb8cdf86458@i12g2000prf.googlegroups.com> AJ Surfing is a fully functional surfing website with full administration controls. Users need no programming experience to change any site features. It is a complete web application developed using PHP with MYSQL as back-end. Full developer API allows for endless possibilities and use in your own project! Sources: http://www.ajsquare.com/ajsurfing/index.php From sjmachin at lexicon.net Tue Dec 18 04:07:42 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 18 Dec 2007 01:07:42 -0800 (PST) Subject: Rounding References: <567047.82204.qm@web57302.mail.re1.yahoo.com> Message-ID: <357fc17e-932a-498c-a0e4-93e1c97c99c0@e6g2000prf.googlegroups.com> On Dec 18, 7:53 pm, "Vladimir Rusinov" wrote: > On 12/15/07, katie smith wrote: > > > > > if i have a number 6.345 and i wanted it to be 6 without subtracting .345 > > because it won't always be .345 what do i do? > > > how do i round to the nearest whole number. Or in this case round down. Is > > there an easy way to round down to the nearest whole number? > > init() ? Perhaps you mean int. The OP may also be interested in another built- in function, just in case a float result or more versatility is needed; it's called round. From trekker182 at comcast.net Tue Dec 4 19:43:32 2007 From: trekker182 at comcast.net (Shawn Minisall) Date: Tue, 04 Dec 2007 19:43:32 -0500 Subject: project - trivia game Message-ID: <4755F434.7030005@comcast.net> For my final project, I'm trying to do a GUI based game similar to are you smarter then a 5th grader. I've been working on it and am stuck with some code someone helped me with to randomize the A,B,C,D letters that the correct answer is assigned too. The code that does this is highlighted in bold and the code that assigns it to a variable is also in bold so I can test it in the console window. Problem is, it's always stuck at letter A and doesn't always give the correct answer. The correct answer is always position 1 in my make math question list. Could someone please help? thanks BTW, to whoever asked me why I don't use functions b4, I'm using them now that I've learned how to... :P ;) from graphics import * from random import * def drawMainMenu(win): #define and draw the buttons mainMenuList = [] mainMenuList.append (CreateRect(4,6,7,8,"grey",win)) mainMenuList.append (CreateRect(3.5,6.5,5,6,"grey",win)) mainMenuList.append (CreateRect(3.5,6.5,3,4,"grey",win)) mainMenuList.append (CreateRect(3.1,7,1,2,"grey",win)) mainMenuList.append (CreateRect(8,10,0,1,"grey",win)) #define and draw the main menu mainMenuList.append (CreateText(5,9.5,"MAIN MENU","times roman", 30, "normal", "red",win)) mainMenuList.append (CreateText(2,8.5,"Please pick a subject from below: ","times roman", 14, "normal", "purple",win)) mainMenuList.append (CreateText(5,7.5,"MATH","times roman", 28, "italic", "blue",win)) mainMenuList.append (CreateText(5,5.5,"SCIENCE","times roman", 28, "italic", "yellow",win)) mainMenuList.append (CreateText(5,3.5,"HISTORY","times roman", 28, "italic", "pink",win)) mainMenuList.append (CreateText(5,1.5,"GEOGRAPHY","times roman", 28, "italic", "green",win)) mainMenuList.append (CreateText(9,.5,"Quit","times roman", 20, "italic", "black",win)) return(mainMenuList) def UndrawMenu (menulist): for i in range(len(menulist)): menulist[i].undraw() def CreateText(x,y,myString,myFace,mySize, myStyle, myColor,win): myText = Text(Point(x,y), myString) myText.setFace(myFace) myText.setSize(mySize) myText.setStyle(myStyle) myText.setTextColor(myColor) myText.draw(win) return myText def CreateRect(x1,x2,y1,y2,myFill,win): myRect = Rectangle(Point(x1,y1,), Point(x2,y2)) myRect.setFill(myFill) myRect.draw(win) return myRect def isValidClick(x1,x2, y1, y2, p1, win): if p1.getX()>=x1 and p1.getY()>=y1 and p1.getX()<=x2 and p1.getY()<=y2: return True else: return False def drawQuestion (subject, question, answers, win): menuList = [] #define and draw the entry boxes entchoice = Entry(Point(6.4,6.5), 1) entchoice.setText("A") entchoice.setTextColor ("blue") entchoice.draw(win) menuList.append(entchoice) menuList.append(CreateText(5,9.5,question,"times roman", 18, "normal", "red",win)) menuList.append(CreateText(2,8.5,"A. " + answers[0],"times roman", 16, "normal", "purple",win)) menuList.append(CreateText(7.5,8.5,"B. " + answers[1],"times roman", 16, "normal", "purple",win)) menuList.append(CreateText(2,7.5,"C. " + answers[2],"times roman", 16, "normal", "purple",win)) menuList.append(CreateText(7.5,7.5,"D. " + answers[3],"times roman", 16, "normal", "purple",win)) menuList.append(CreateText(4.7,6.5,"Please enter your choice:","times roman", 16, "normal", "purple",win)) #draw answer box and text answerButton = Rectangle(Point(7,5.5), Point(3,4)) answerButton.setFill("grey") answerButton.draw(win) answerButton = Text(Point(5,4.8),"Answer") answerButton.setTextColor("black") answerButton.setSize(22) answerButton.draw(win) menuList.append(answerButton) return(menuList) def main(): #Declare and initialize variables #make math question list mathlist = [] question = ["An equilateral triangle has how many sides?", "3", "4" , "1", "5"] mathlist.append(question) question = ["How many inches are in a foot?", "12", "6", "3", "9"] mathlist.append(question) question = ["One Kilogram equals how many grams?", "1000", "230", "450", "100"] mathlist.append(question) question = ["Which means nine hundred sixty three thousandths?", ".963", ".0963", ".0.0963", "9.63"] mathlist.append(question) question = ["A fathom is a unit of measurement for which of the following?", "depth", "space", "time", "distance"] mathlist.append(question) question = ["What is 111, plus 112, plus 113?", "336", "332", "331", "333"] mathlist.append(question) #show the rules of the game window win = GraphWin("RULES OF THE GAME",600,600) win.setBackground("orange") win.setCoords(0.0,0.0,10.0,10.0) txtrules1 = CreateText(5,9.5,"The rules of the game are as follows:","times roman", 16, "normal", "red",win) txtrules2 = CreateText(5,8.5,"The game will be made up of 10 questions, 2 from each grade 1-5.","times roman", 12, "normal", "black",win) txtrules3 = CreateText(5,7.5,"You will be able to pick 2 subjects you want to answer for each grade.","times roman", 12, "normal", "black",win) txtrules4 = CreateText(5,6.5,"The subjects you can pick from are Math, Science, History and Geography.","times roman", 12, "normal", "black",win) txtrules5 = CreateText(5,5.5,"No more then 3 questions can be answered from each subject.","times roman", 12, "normal", "black",win) txtrules6 = CreateText(5,2.5,"HAVE FUN AND GOOD LUCK!","times roman", 26, "normal", "yellow",win) #define window and set coords win =GraphWin("Are You Smarter Then a Fifth Grader???",800,800) win.setBackground("orange") win.setCoords(0.0,0.0,10.0,10.0) mainMenuList = drawMainMenu(win) #getMouse p1 = win.getMouse() while(isValidClick(8,10,0,1,p1,win)==False): if (isValidClick(4,6,7,8,p1,win)==True): currentList = mathlist subject = "Math" elif (isValidClick(3.5,6.5,5,6,p1,win)==True): UndrawMenu(mainMenuList) elif (isValidClick(3.5,6.5,3,4,p1,win)==True): UndrawMenu(mainMenuList) elif (isValidClick(3.1,7,1,2,p1,win)==True): UndrawMenu(mainMenuList) UndrawMenu(mainMenuList) * #Picks random question qNum = randrange(0, len(currentList)) qList = currentList[qNum] aList = [] tmpList = qList[1:5] #Randomizes answers while(len(tmpList) > 0): rNum = randrange(0, len(tmpList)) aList.append(tmpList[rNum]) tmpList.pop(rNum)* currentScreen = drawQuestion(subject, qList[0], aList, win) currentList.pop(qNum) #getMouse p1 = win.getMouse() while(isValidClick(7,3,5.5,4,p1,win)==True): print "hello" * pResult = (currentScreen[0].getText()) print pResult cResult = (currentScreen[2].getText()) print cResult* #compare player's answer to correct answer #if correct/incorrect do a print statement #add/take away from score UndrawMenu(currentScreen) #Quit win.close() From chrisspen at gmail.com Tue Dec 11 11:05:29 2007 From: chrisspen at gmail.com (Chris) Date: Tue, 11 Dec 2007 08:05:29 -0800 (PST) Subject: Matching XML Tag Contents with Regex Message-ID: <38ea9cbc-a222-4c0f-ba2d-f6b415d02fb1@d27g2000prf.googlegroups.com> I'm trying to find the contents of an XML tag. Nothing fancy. I don't care about parsing child tags or anything. I just want to get the raw text. Here's my script: import re data = """
here's some text!
here's some text!
here's some text!
""" tagName = 'div' pattern = re.compile('<%(tagName)s\s[^>]*>[.\n\r\w\s\d\D\S\W]*[^(% (tagName)s)]*' % dict(tagName=tagName)) matches = pattern.finditer(data) for m in matches: contents = data[m.start():m.end()] print repr(contents) assert tagName not in contents The problem I'm running into is that the [^%(tagName)s]* portion of my regex is being ignored, so only one match is being returned, starting at the first
and ending at the end of the text, when it should end at the first
. For this example, it should return three matches, one for each div. Is what I'm trying to do possible with Python's Regex library? Is there an error in my Regex? Thanks, Chris From larry.bates at websafe.com Wed Dec 12 17:34:46 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 12 Dec 2007 16:34:46 -0600 Subject: Finding Line numbers of HTML file In-Reply-To: <3f6e6190-32a0-462c-b38c-d57d6215646c@j20g2000hsi.googlegroups.com> References: <3f6e6190-32a0-462c-b38c-d57d6215646c@j20g2000hsi.googlegroups.com> Message-ID: Ramdas wrote: > I am doing some HTML scrapping for a side project. > > I need a method using sgmllib or HTMLParser to parse an HTML file and > get line nos of all the tags > > I tried a few things, but I am just not able to work with either if > the parsers. > > > > Can someone help > HTML doesn't really have "lines" it is just a stream of text that can be formatted with line end characters to make it somewhat easier for humans to read. Parsers probably won't give you any line numbers. What is the use case for this (e.g. why do you think you need the line numbers)? Extraction is done using tags not line numbers. All that said, you should look at Beautiful Soup module before continuing. -Larry From alexLIGO at googlemail.com Tue Dec 4 06:42:28 2007 From: alexLIGO at googlemail.com (alexLIGO at googlemail.com) Date: Tue, 4 Dec 2007 03:42:28 -0800 (PST) Subject: Problems with import Message-ID: <4d4415d1-9469-45da-8364-49b5c5b4fc87@o6g2000hsd.googlegroups.com> Hi, I have some problems when importing a library. Suppose I have a directory /home/user/pythonlib/package in which I have a python- library called test.py. Now I want to import that, so I put the following directory into the PYTHONPATH: /home/user/pythonlib and in my main python script I put: from package import test. BUT I get an error: ImportError: cannot import name test So how can I test and check what is going on, why python does not find the library? Thanks Alex From jcd at sdf.lonestar.org Thu Dec 13 11:11:35 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Thu, 13 Dec 2007 11:11:35 -0500 Subject: Question from a python newbie In-Reply-To: <7ae3ca10712130757o32a98fcfr410c0faa43525803@mail.gmail.com> References: <7ae3ca10712130757o32a98fcfr410c0faa43525803@mail.gmail.com> Message-ID: <20071213161135.GA19800@sdf.lonestar.org> On Thu, Dec 13, 2007 at 04:57:04PM +0100, Remco Gerlich wrote regarding Re: Question from a python newbie: > > On Dec 13, 2007 4:39 PM, Russell <[1]rcooknet at gmail.com> wrote: > > I've been learning Python slowly for a few months, coming from a > C/C+ > +, C#, Java, PHP background. I ran across a code fragment I'm > having > trouble wrapping my brain around. I've searched the Language > Reference and was not able to find any info regarding the structure > of > this code fragment: > int(text) if text.isdigit() else text > > Hi, > It's a pretty new construct; basically it's Python's version of the ? : > "ternary operator" in other languages. > The line above is equivalent to > text.isdigit() ? int(text) : text > in, for instance, C. > Remco Gerlich > Or, if you don't know C. It is equivalent to if text.isdigit(): int(text) else: text From lists at cheimes.de Wed Dec 12 21:56:29 2007 From: lists at cheimes.de (Christian Heimes) Date: Thu, 13 Dec 2007 03:56:29 +0100 Subject: Improvements to the Python core In-Reply-To: References: Message-ID: <47609F5D.8040405@cheimes.de> Paul Boddie wrote: > Then you haven't been reading the right IRC channel recently. ;-) What's the right channel? I'm on #python and #python-dev > Indeed, but there's arguably a certain amount of deadlock around > making unpatched, released versions of Python available in all these > places, unless there's been some activity below the surface in the > python-dev community on things like cross-compilation and not running > distutils using the newly built Python executable (which, as I > remember, was but one of the problems). Your point stands, naturally, > but if there's potential for some real movement on some > uncontroversial issues, and yet we see no movement, one remains > skeptical about getting even slightly controversial improvements into > vanilla CPython. I don't get your point, especially when you talk about distutils. Please elaborate. (C)Python has a well known process to get new features or changes into the language: Write a PEP, convince enough core developers and/or Guido, implement the feature. I don't see a PEP about JIT in the list at abouthttp://www.python.org/dev/peps/, do you? :] Besides nobody is going to stop you from creating a fork. Christian Tismer forked of stackless years ago. It's a successful branch with useful additions to the language. It got never merged back because Christian didn't feel right about it. > Perhaps, but what would people prefer: yet more language bolt-ons or > better performance? I prefer a fast, stable and maintainable Python over a faster but unstable. > It will be interesting to see what happens with recent work on > improving threading within CPython. As for Psyco (which perhaps offers > concurrency benefits only through instruction-level parallelism, if we > briefly consider that topic), I can understand that just-in-time > compilation can bring certain penalties in terms of memory usage and > initialisation times (as Java virtual machines have demonstrated), but > there's a compelling argument for trying to make such technologies > available to CPython if they can be switched off and won't then incur > such penalties. But we presumably return to the point of people not > wanting to touch code that has anything to do with such features: a > combination of social factors and the priorities of the group. Rhamph is working on a GIL-less Python version. It may become a compile time option someday in the future. Others have worked hard to speed up other parts of Python. We have multiple pending patches which speed up small parts of Python. Some are related to peephole (byte code optimizations), other patches speed up attribute access on classes or globals. The global lookup patch makes globals as fast as locals. I've done my share for the poor Windows souls when I created the VS 2008 PCbuild9 directory and enabled PGO builds. PGO builds are about 10% faster than ordinary VS 2008 builds. VS 2008 should be slightly faster than VS 2003 but I can bench mark it on my machine. In my opinion an optional JIT as compile time or startup option has good chances to become part of the CPython implementation. You "only" have to replace ceval.c ... :] Christian From nytrokiss at gmail.com Sat Dec 8 17:02:41 2007 From: nytrokiss at gmail.com (James Matthews) Date: Sat, 8 Dec 2007 23:02:41 +0100 Subject: download complete webpage with python In-Reply-To: References: <830031.68574.qm@web53903.mail.re2.yahoo.com> Message-ID: <8a6b8e350712081402y65569578n8f009596a66b9e4e@mail.gmail.com> from urllib import urlopen url = urlopen("http://www.google.com").read() Enjoy! On 12/8/07, Larry Bates wrote: > > Gabriel Genellina wrote: > > En Fri, 07 Dec 2007 17:58:43 -0300, yi zhang > > escribi?: > > > >> The urllib.urlretrieve() can only download the text part of a webpage, > >> not the image associated. How can I download the whole, complete > >> webpage with python? Thanks! > > > > The images are separate from the html document. You have to parse the > > html text, find the tags, and retrieve them. > > > Actually IMHO this is even more difficult than it sounds. Javascript can > change > the webpage after it loads. > > Larry > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Mon Dec 3 11:11:19 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 03 Dec 2007 16:11:19 GMT Subject: "Python" is not a good name, should rename to "Athon" References: <78bdd499-a263-4c68-8e43-e3e59b111c7e@a39g2000pre.googlegroups.com> <5rcq90F13re18U1@mid.individual.net> <13l44ousfqdhfb1@corp.supernews.com> <13l539r1gjt8l7e@corp.supernews.com> <122201b7-7cc7-4315-8c2d-55586552ada3@y5g2000hsf.googlegroups.com> <13l80q05uc12v84@corp.supernews.com> <7a2bff7e-4e54-473a-831f-ef5b873f9aeb@i29g2000prf.googlegroups.com> Message-ID: On 2007-12-03, Russ P. wrote: > On Dec 3, 5:23 am, Steven D'Aprano >> I'm not suggesting that Leibniz was any more of a scientist >> than Newton was, nor am I suggesting that Newton's >> achievements should be *rejected* (er, except for those pesky >> Quantum Mechanics and Relativity things...). I'm just saying >> that we should understand Newton for what he actually was, and >> not based on the 18th Century revisionism. > > Your claim that Newton was "not a scientist" says more about > you than it does about him. He is widely regarded -- by > physicists and many other scientists -- not only as a > scientist, but as the most important one who ever lived. To paraphrase Bertrand Russell, Newton was too successful. Over-veneration of Newton was eventually an impediment to progress--this was not, of course, his fault. -- Neil Cerutti From sgeiger at ncee.net Thu Dec 27 12:58:04 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Thu, 27 Dec 2007 11:58:04 -0600 Subject: Dynamic DNS with a python script In-Reply-To: <1e5bcefd0712270927p2c23901el8ae6a4283af3faa1@mail.gmail.com> References: <1e5bcefd0712270927p2c23901el8ae6a4283af3faa1@mail.gmail.com> Message-ID: <4773E7AC.80302@ncee.net> Marcelo de Moraes Serpa wrote: > Hello list, > > I'd like to set up ssh access to my home computer so that I will be > able to access it from work - for this no problem, installing sshd is > straightforward. > > The issue here is that I don't have a fixed IP connection at home. > Also, I wouldn't like to use services such as no-ip or similar. > > What I thought was of writing a python program that would detect when > the internet network interface was restarted/started for the first > time and then update a DNS record at my DNS server where I would have > a subdomain that for my home machine's host. > > However, I have no idea on how I could detect if the network has been > restarted nor how I could update this DNS record. Any suggestion would > be greatly appreciated :) > > Thanks in advance, > > Marcelo. How to deal with networking depends on the system you use. For Debian: Debian uses ifupdown (see ifup(8), ifdown(8) and interfaces(5)) to manipulate network interfaces. Each interface is provided with several scripting hooks: pre-up, up, down, and post-down. These hooks are available to each interface as in-line directives in /etc/network/interfaces and also as *.d/ directories called with run-parts (see run-parts(8)): /etc/network/if-up.d/ /etc/network/if-pre-up.d/ /etc/network/if-down.d/ /etc/network/if-post-down.d/ SETTING UP A DOMAIN NAME WITH DYNDNS.ORG Go to their site and set up an account. While doing that (or perhaps after--I don't remember), you can choose a domain name. You *could* think of what they are giving you is a subdomain--not actually a domain. You will be able to choose something like foo.mine.nu where "foo" is the name you choose for the name of your subdomain and "mine.nu" is the domain they already own. (You can choose from many domains they already own.) Since they manage these domains themselves, they do not have to pay a registrar to set up a subdomain...and therefore they can give you a subdomain for free. (Actually, I'm using the term "subdomain" loosely here...but I'm sure you get the point I'm trying to make--which is that you don't have to pay for this name.) Once you have your name (foo.mine.nu, for example), you can set up a program on your computer to update their DNS servers with your new domain name whenever it changes. -------------------------------------------------- SETTING UP IPCHECK WITH DYNDNS.ORG I have been satisfied with my first choice (dyndns.org), so I haven't tried the others. They probably work well, too. Set up an account on dyndns.org, and record the username, password, and domain name in your notes. In the following examples, I use the following values: username: sgeiger pass: asdfasdf domain name: sgeiger.mine.nu apt-get install ipcheck You might want to run this first so that you are in the directory cron will use when you run ipcheck: sudo su; cd ~; HERE'S HOW TO CONFIGURE IT: sgeiger at minime:~$ sudo /usr/sbin/ipcheck.py -l -r checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu ipcheck.py: No ipcheck.dat file found. ipcheck.py: Use same command+options ONCE with --makedat to create from DNS lookup. sgeiger at minime:~$ sudo /usr/sbin/ipcheck.py --makedat -l -r checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu ipcheck.py: ip1 looking up sgeiger.mine.nu ipcheck.py: result: 'sgeiger.mine.nu'[]['139.55.232.72'] sgeiger at minime:~$ sudo /usr/sbin/ipcheck.py -l -r checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine .nu sgeiger at minime:~$ sudo /usr/sbin/ipcheck.py -l -r checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu sgeiger at minime:~$ sudo /usr/sbin/ipcheck.py -l -r checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu sgeiger at minime:~$ When you run this manually and it works you will see no output. To add a cron job to update this automatically once a day at 10 am: ### Note: This script should be run once a day from cron, like this (which runs it at 10:15 am every day) 15 10 * * * /usr/bin/python /usr/sbin/ipcheck.py -l -r checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu To add another names (foobar.mine.nu): sudo /usr/sbin/ipcheck.py --makedat -l -r checkip.dyndns.org:8245 shanerg rQ9ll0 sgeiger.mine.nu,foobar.mine.nu ...and then put this into the cron tab: 15 10 * * * /usr/bin/python /usr/sbin/ipcheck.py -l -r checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu Check the mail messages on the computer you are using in case there were errors. Note: This creates a file named /root/ipcheck.dat and /root/ipcheck.log on my computer. STEPS FOR ADDING ANOTHER HOST: - add the host on dnydns.org - run the script with makedat option - run the script to update the server In the example below, ipcheck will update the dyndns.org servers for the names "sgeiger.mine.nu" and for "myothername.mine.nu": sgeiger at minime:/root$ sudo /usr/sbin/ipcheck.py --makedat -l -r checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu,sgeigerbot.mine.nu,myothername.mine.nu ipcheck.py: There is already an ipcheck.dat file existing. ipcheck.py: Remove this file first before running --makedat sgeiger at minime:/root$ sudo mv ipcheck.dat ipcheck.dat-old sgeiger at minime:/root$ sudo /usr/sbin/ipcheck.py --makedat -l -r checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu,sgeigerbot.mine.nu,myothername.mine.nu ipcheck.py: ip1 looking up sgeiger.mine.nu ipcheck.py: result: 'sgeiger.mine.nu'[]['139.55.233.228'] ipcheck.py: ip2 looking up sgeigerbot.mine.nu ipcheck.py: result: 'sgeigerbot.mine.nu'[]['139.55.233.228'] ipcheck.py: ip2 looking up myothername.mine.nu ipcheck.py: result: 'myothername.mine.nu'[]['139.55.233.228'] sgeiger at minime:/root$ sgeiger at minime:/nu/mine/myothername$ sudo crontab -l 15 10 * * * /usr/sbin/ipcheck.py -l -r checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu,sgeigerbot.mine.nu,myothername.mine.nu --acctfile /root/ipcheck.dat sgeiger at minime:/nu/mine/myothername$ -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From MonkeeSage at gmail.com Sat Dec 1 06:00:24 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: Sat, 1 Dec 2007 03:00:24 -0800 (PST) Subject: "Python" is not a good name, should rename to "Athon" References: <7e55b84a-43b3-43c6-8adb-3760bc8b3a92@d21g2000prf.googlegroups.com> <5rcqbfF13re18U2@mid.individual.net> Message-ID: On Dec 1, 4:11 am, Bjoern Schliessmann wrote: > ureuffyrtu... at gmail.com wrote: > > New name "Pytn" may be better, do you think so ? > > No. How would you pronounce it? Pai-tn? > > Why don't you create a fork where the only difference is the name? > > Regards, > > Bj?rn > > -- > BOFH excuse #194: > > We only support a 1200 bps connection. My vote is for "Pyrotron [1] 10,000", heh. ;) [1] http://en.wikipedia.org/wiki/Disintegrator_ray Regards, Jordan From mensanator at aol.com Fri Dec 7 17:08:32 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Fri, 7 Dec 2007 14:08:32 -0800 (PST) Subject: I'm missing something here with range vs. xrange References: Message-ID: <67b6b3c0-d51b-4ae4-b069-793158ae92bf@j44g2000hsj.googlegroups.com> On Dec 7, 3:08 pm, "Joe Goldthwaite" wrote: > Here's the simple benchmark; > > start = time.time() > for x in xrange(3): > for y in xrange(10000000): > pass > print 'xRange %s' % (time.time() - start) > > start = time.time() > for x in range(3): > for y in range(10000000): > pass > print 'Range %s' % (time.time() - start) > > Here's what I get; > > xRange 92.5529999733 > Range 95.2669999599 > > Not a lot of difference. Range is slower but not by much. I know that range > builds > a list then iterates through it. I thought that xrange just kept a counter > that was > incremented and returned with each call. No list was ever created. If that's > true > (and I guess it's not), xrange would be much faster than range. It seems > almost > identical. Given the amount of performance difference, I don't see why > xrange even > exists. Try tracking your memory usage during the benchmark and it will become very clear why xrange exists. > > P.S. I searched google again to try and find out more about range vs. > xrange and > this thread came up first on the list. That was strange. I thought I'd > found > someone else asking the same question as me until I clicked on the link and > found > out it actually was me. > > > > -----Original Message----- > From: python-list-bounces+joe=goldthwaites.... at python.org > > [mailto:python-list-bounces+joe=goldthwaites.... at python.org]On Behalf Of > Bjoern Schliessmann > Sent: Thursday, December 06, 2007 3:33 PM > To: python-l... at python.org > Subject: Re: I'm missing something here with range vs. xrange > > Joe Goldthwaite wrote: > > I read that the range function builds a list and that xrange > > returns an iterator and is therefore more efficient. > > This is generally not true. > > > In my testing, they both come out to almost exactly the same > > performance wise. Did something get changed in Python 2.4 to make > > them identical? > > No. Try again with a list of length 10000000. > > Regards, > > Bj?rn > > -- > BOFH excuse #359: > > YOU HAVE AN I/O ERROR -> Incompetent Operator error > > --http://mail.python.org/mailman/listinfo/python-list- Hide quoted text - > > - Show quoted text - From half.italian at gmail.com Thu Dec 13 21:04:00 2007 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 13 Dec 2007 18:04:00 -0800 (PST) Subject: RegExp Help References: <0ed0e6b0-a760-4697-9079-fe4153654746@t1g2000pra.googlegroups.com> Message-ID: <14ff8d0e-3ff4-4428-b7b9-fd270715309d@e10g2000prf.googlegroups.com> On Dec 13, 5:49 pm, Sean DiZazzo wrote: > Hi group, > > I'm wrapping up a command line util that returns xml in Python. The > util is flaky, and gives me back poorly formed xml with different > problems in different cases. Anyway I'm making progress. I'm not > very good at regular expressions though and was wondering if someone > could help with initially splitting the tags from the stdout returned > from the util. > > I have the following example string, and am simply trying to split it > into two xml tags... > > simplified = """2007-12-13 > \n2007-12-13 > \n""" > > Basically I want the two tags, and to discard anything in between > using a reg exp. Like this: > > tags = ["", " attr1="text1" attr2="text2" attr3="text3\n" /tag2>"] > > I've tried several approaches, some of which got close, but the > newline in the middle of one of the tags screwed it up. The closest > I've been is something like this: > > retag = re.compile(r'<.+>*') # tried here with re.DOTALL as well > tags = re.findall(retag) > > Can anyone help me? > > ~Sean I found something that works, although I couldn't tell you why it works. :) retag = re.compile(r'<.+?>', re.DOTALL) tags = retag.findall(retag) Why does that work? ~Sean From gnewsg at gmail.com Fri Dec 21 13:44:23 2007 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Fri, 21 Dec 2007 10:44:23 -0800 (PST) Subject: Understanding memory leak reports Message-ID: Hi, I'm in a big trouble since I don't know how to find some memory leaks I just discovered in a program of mine. By putting: import gc gc.set_debug(gc.DEBUG_LEAK) ..at the end of a script which imports a module I wrote it seems I have some memory leaks scattered around. The message printed on screen is the following: gc: collectable gc: collectable gc: collectable gc: collectable gc: collectable gc: collectable gc: collectable Since the main module is very big (more than 2800 lines of code) I do not understand which objects are not garbage collected. Is there a way to have a more detailed message to know which objects are not garbage collected? For example "function foo", "method MyClass.bar", "dict my_dict"... "function 00C70E70" and "tuple 00C09900" are too much generic messages which don't give me an idea about where the leak could be. From mrkafk at gmail.com Fri Dec 7 08:50:13 2007 From: mrkafk at gmail.com (mrkafk at gmail.com) Date: Fri, 7 Dec 2007 05:50:13 -0800 (PST) Subject: File to dict References: <6d552e59-9841-4af3-85ed-bd144f4f7052@i29g2000prf.googlegroups.com> <5rsuf7F166l5tU3@mid.uni-berlin.de> Message-ID: > I guess Duncan's point wasn't the construction of the dictionary but the > throw it away part. If you don't keep it, the loop above is even more > efficient than building a dictionary with *all* lines of the file, just to > pick one value afterwards. Sure, but I have two options here, none of them nice: either "write C in Python" or do it inefficient and still elaborate way. Anyway, I found my nirvana at last: >>> def shelper(line): ... return x.replace(' ','').strip('\n').split(':',1) ... >>> ownerslist = [ shelper(x)[1] for x in it if len(shelper(x)) == 2 and shelper(x)[0] == domain ] >>> ownerslist ['da2'] Python rulez. :-) From deets at nospam.web.de Mon Dec 3 08:54:20 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Dec 2007 14:54:20 +0100 Subject: python 2.5 - f=open('a_file.txt','w') gives [Errno 2] References: <56e9075a-b3aa-4e8e-b5b7-5a58f0305945@s36g2000prg.googlegroups.com> Message-ID: <5rig4cF14rcenU1@mid.uni-berlin.de> dirkheld wrote: > Hi, > > I upgraded my system from tiger to leopard. With leopard came a new > version of python 2.5 > > Now I trying to run some python code that previously worked on tiger > (which included an older version of python). > > This is the error I'm receiving : > > Traceback (most recent call last): > File "test.py", line 18, in print_total > f=open('a_file.txt','w') > IOError: [Errno 2] No such file or directory: 'a_file.txt' > > > Is this a bug in python? This code worked on my old system The obvious question is: do you have 'a_file.txt' on your new system? There are many happy python programmers on leopard, and this is one heck of a basic functionality - I really doubt it's broken in such obvious way (if any at all). Diez From Lie.1296 at gmail.com Sat Dec 22 03:28:20 2007 From: Lie.1296 at gmail.com (Lie) Date: Sat, 22 Dec 2007 00:28:20 -0800 (PST) Subject: Odd behavior in Python/Tkinter? References: <3e6fc1b0-ac5e-42ed-8fe1-76da015c46ac@i29g2000prf.googlegroups.com> Message-ID: On Dec 22, 1:42?pm, Fredrik Lundh wrote: > Lie wrote: > >>> Inspect the following code: > > >>> --- start of code --- > >>> import Tkinter as Tk > >>> from Tkconstants import * > >>> root = Tk.Tk() > >>> e1 = Tk.Entry(root, text = 'Hello World') > >>> e2 = Tk.Entry(root, text = 'Hello World') > > >> the "text" (or "textvariable") option to the Entry widget is the name of > >> the Tcl variable that should hold the result. > > >> to get something that's a bit more usable from Python, use a StringVar > >> instance instead. ?alternatively, use the "get" method to fetch text > >> from the widget, and the "insert" method to add text to it. > > I realized that 'text' isn't a normally valid arguments for Entry (and > > I'm also aware about the insert, get, etc), but what makes me creep is > > the fact that the Entry's value would mirror each other if they're set > > to the same 'text' value > > note that you've set the "textvariable" option, not the "text" option. > Tk allows you to abbreviate option names. > > and since you've set the "textvariable" option for both widgets to the > same variable, you've asked them both to display the same variable. > Tkinter just does what you've asked it to. > > this is no different from using a Tkinter variable to display the same > value in a number of radiobutton widgets. > > But an expression (e.g. string) is NOT a variable. It's fine if the value mirrored when I set the textvariable conf to the same variable, but in this case I'm setting them to the same expression (e.g. string). From ilias at lazaridis.com Tue Dec 18 22:40:10 2007 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Tue, 18 Dec 2007 19:40:10 -0800 (PST) Subject: Detecting memory leaks on apache, mod_python References: <6f624cbd-294b-4a45-bf23-4219d8d6245e@x69g2000hsx.googlegroups.com> Message-ID: <2e1f149b-adc4-4e63-9161-c3de1bcbae77@j20g2000hsi.googlegroups.com> On Dec 17, 8:41 am, Ilias Lazaridis wrote: > How to detect memory leaks of python programms, which run in an > environment like this: > > * Suse Linux 9.3 > * Apache > * mod_python > > The problem occoured after some updates on the infrastructure. It's > most possibly caused by trac and it's dependencies, but several > components of the OS where updated, too. > > Any nice tools which play with the above constellation? > > Thank's for any hints! No tool available to detect memory leaks for python applications? > context: > > http://dev.lazaridis.com/base/ticket/148 From mnordhoff at mattnordhoff.com Wed Dec 26 02:50:40 2007 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 26 Dec 2007 02:50:40 -0500 Subject: Python for web... In-Reply-To: <983c7459-7388-41ca-a192-b39805ea0b69@s8g2000prg.googlegroups.com> References: <983c7459-7388-41ca-a192-b39805ea0b69@s8g2000prg.googlegroups.com> Message-ID: <477207D0.2090701@mattnordhoff.com> thushianthan15 at gmail.com wrote: > Hi everyone, > > I have to develop a web based enterprise application for my final year > project. Since i am interested in open source, i searched the net. > Almost 90% of them were PHP and MySQL. Cant we use python for that ? I > tried several sites, but there is not enough tutorial for beginners > [mod_python, PSP etc]. I couldnt find any detailed book, not even a > single book :( All the python books are covering only CGI part) > > Any suggestions? Any recommended book? > > Execuse my English. > > Thushanthan. Well, there are multiple different Python web frameworks, including Django, Pylons, TurboGears and Zope (also the barebones CherryPy). They're all much more high-level than PHP, including things like database APIs and templating languages. Most/all of them have books or at least good documentation and guides. If you're doing something really simple (one web page, minimal DB usage, whatever), you can use bare WSGI, perhaps like libraries like Beaker for sessions. Google all of the terms I used. There should be information available. :-P -- From greg at cosc.canterbury.ac.nz Fri Dec 14 02:01:18 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 14 Dec 2007 20:01:18 +1300 Subject: Is Python really a scripting language? In-Reply-To: <476109f3$0$13493$426a74cc@news.free.fr> References: <009101c83c55$4ee07a00$6501a8c0@aristotle> <4761011a$0$5462$426a74cc@news.free.fr> <476109f3$0$13493$426a74cc@news.free.fr> Message-ID: <5seob2F18i0o7U1@mid.individual.net> Bruno Desthuilliers wrote: > http://acmqueue.com/modules.php?name=Content&pa=showpage&pid=273 An interesting quote from that: > If you combine Simula and Lisp?Lisp didn?t have data structures, it had > instances of objects?you would have a dynamic type system that would > give you the range of expression you need. Sounds like AK is talking about Python here and doesn't know it... -- Greg From Mark.English at rbccm.com Tue Dec 18 07:15:12 2007 From: Mark.English at rbccm.com (English, Mark) Date: Tue, 18 Dec 2007 12:15:12 -0000 Subject: operator module isSequenceType with builtin set produces False Message-ID: X-Replace-Address: mark.ignorethisbit.english at xxxrbccmxxx.ignorethisbittoo_and_removethosep receding_xxxs_.com This wasn't what I was expecting, so I thought I'd ask those more knowledgeable, which is pretty much everybody. Same result on Python 2.3.5 and Python 2.5.1 installed from python.org binaries on Windows XP. >>> try: set >>> except NameError: from sets import Set as set >>> class myset_fails(set): pass >>> class myset_works(set): >>> def __getitem__(self): pass >>> s = set() >>> fails = myset_fails() >>> works = myset_works() >>> import operator >>> operator.isSequenceType(s) #Not what I expected False >>> operator.isSequenceType(fails) #Not what I expected either False >>> operator.isSequenceType(works) #A hint at what isSequenceType does ? True Are sets not sequences ? I didn't think the isSequenceDisclaimer gave false negatives. See Raymond Hettinger's post here too: http://groups.google.co.uk/group/comp.lang.python/tree/browse_frm/thread /bd04db20cc1f23bb/36f1f48bb7be1e4b?hl=en&rnum=1&q=set+isSequenceType&_do ne=%2Fgroup%2Fcomp.lang.python%2Fbrowse_frm%2Fthread%2Fbd04db20cc1f23bb% 2F0454f5debc01c20d%3Fhl%3Den%26lnk%3Dgst%26q%3Dset%2BisSequenceType%26#d oc_0454f5debc01c20d Although there are suggestions that it means simply that you're headed in the wrong direction design wise: http://www.mail-archive.com/python-dev at python.org/msg11576.html but then why have isSequenceType at all ? Not particularly vital. Just implementing __str__ on some class and if one of the members was a sequence I was going to format that bit of data in brackets. Thanks, Mark ______________________________________________________________________ This email is intended only for the use of the individual(s) to whom it is addressed and may be privileged and confidential. Unauthorised use or disclosure is prohibited.If you receive This e-mail in error, please advise immediately and delete the original message. This message may have been altered without your or our knowledge and the sender does not accept any liability for any errors or omissions in the message. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bjourne at gmail.com Thu Dec 13 07:29:16 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Thu, 13 Dec 2007 13:29:16 +0100 Subject: "do" as a keyword In-Reply-To: References: Message-ID: <740c3aec0712130429o8106b4fye1e189dceca7bfc4@mail.gmail.com> On Dec 11, 2007 4:06 PM, Neil Cerutti wrote: > > However, did you have an specific need for a do-while construct? > Perhaps we could show you the alternatives. I have wanted do-while loops in exactly one kind of algorithms, when you generate something and you have to keep trying until it gets right. For example, generating random and non-overlapping points on a grid: import random grid = dict() for i in range(10): while True: x = random.randint(0, 4) y = random.randint(0, 4) if not (x, y) in grid: break grid[x, y] = 1 The loop runs one or more times until a vacant spot in the grid is found. This type problem would be better expressed using a do-while: import random grid = dict() for i in range(10): do: x = random.randint(0, 4) y = random.randint(0, 4) while (x, y) in grid grid[x, y] = 1 -- mvh Bj?rn From sgeiger at ncee.net Fri Dec 28 13:42:38 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Fri, 28 Dec 2007 12:42:38 -0600 Subject: SVGDraw is where? Message-ID: <4775439E.8090703@ncee.net> Does someone know where SVGDraw has gone? It used to be here: http://www2.sfk.nl/svg/ Googling hasn't helped me locate it. :-\ -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From asterix at lagaule.org Mon Dec 3 10:11:46 2007 From: asterix at lagaule.org (Yann Leboulanger) Date: Mon, 03 Dec 2007 16:11:46 +0100 Subject: os.access() under windows In-Reply-To: References: <47512df4$0$29713$426a74cc@news.free.fr> <475406CE.5060509@v.loewis.de> <47540a65$0$28941$426a74cc@news.free.fr> <47540F7D.6010900@timgolden.me.uk> Message-ID: <47541CB2.8030409@lagaule.org> Tim Golden a ?crit : > > I'm happy to contribute a doc patch if I can imagine what > exactly to write. > "Don't use it under windows, always consider it's True"? Maybe it would be a good idea to remove support for windows for this function, or make it always return True? Current behaviour is worth that nothing, access() return False but open() doesn't fail ... -- Yann From istvan.albert at gmail.com Sun Dec 30 09:07:09 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Sun, 30 Dec 2007 06:07:09 -0800 (PST) Subject: Bizarre behavior with mutable default arguments References: <47768DE0.5050406@v.loewis.de> <2541af1e-9167-4cee-b773-8f6ab0f23b8f@i12g2000prf.googlegroups.com> <13ndpflarf19i9c@corp.supernews.com> <041ea3ab-2d08-49b0-96db-c2ec7f0d7f8f@z26g2000pre.googlegroups.com> Message-ID: <0589e497-9857-44b3-be71-46318c5fb93c@e23g2000prf.googlegroups.com> On Dec 29, 11:21 pm, bukzor wrote: > The standard library is not affected because the people who wrote code into it know how python works. Programming abounds with cases that some people think should work differently: a = b = [] a.append(1) is b empty or not at this point? Get informed, remember the rules, be happy and move on to write some cool code. There is little new in what you say. Every so often someone is having a confusing time with a feature and therefore proposes that the language be changed to match his/her expectations. i. From petr.jakes.tpc at gmail.com Tue Dec 25 13:06:51 2007 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Tue, 25 Dec 2007 10:06:51 -0800 (PST) Subject: how to generate html table from "table" data? Message-ID: Hi group, I would like to convert the output of the SQL query, or more generally I would like to convert any "table" data to the html table. I would like to set some rules to format cells, columns or rows (font, colour etc.) of the html table, according to the values in the specific cells. Googling for a while I have found only this tool: http://pasko.net/PyHtmlTable/ Your tips to some other tools or/and your suggestion how to solve above mentioned will be very helpful. Thanks and regards Petr Jakes From sturlamolden at yahoo.no Thu Dec 13 16:35:24 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 13 Dec 2007 13:35:24 -0800 (PST) Subject: Is a "real" C-Python possible? References: <6949214e-8f23-431b-b24f-b8e50460f25a@i12g2000prf.googlegroups.com> <422a001f-09df-44d8-a7b2-f8423dccc48a@a35g2000prf.googlegroups.com> <0b099c51-b7f1-4d28-bda7-0352d7fa513d@s12g2000prg.googlegroups.com> <8209a914-e3ff-4af3-86f2-f4d2bdaa891d@c4g2000hsg.googlegroups.com> Message-ID: <974cf980-a8a0-4a58-9686-9a17f895d9df@i12g2000prf.googlegroups.com> On 13 Des, 19:16, "Chris Mellon" wrote: > I don't feel that it's especially inconsistent, and I like decorators. > Having to write foo everywhere isn't that nice, but it's only mildly > worse than C# to me - I find the extra block levels really atrocious. Personally I find properties atrocious and unsafe. One cannot distinguish between a function call and binding an attribute in a statement like: foo.bar = 2 # Does this call a function or bind an attribute? # Is this foo.setBar(2) or setattr(foo,'bar',2)? Even worse: if we make a typo, the error will not be detected as the syntax is still valid. Properties and dynamic binding do not mix. From rpdooling at gmail.com Mon Dec 10 23:44:13 2007 From: rpdooling at gmail.com (Rick Dooling) Date: Mon, 10 Dec 2007 20:44:13 -0800 (PST) Subject: newbie References: <475defe8$0$8799$4c368faf@roadrunner.com> Message-ID: <0631f13b-a916-4949-80b1-7466a592a137@w56g2000hsf.googlegroups.com> On Dec 10, 8:03 pm, "Whizzer" wrote: > Is OReilly's Learning Python a good place to start learning to program? > I've been told Python is a good first language. > > Thanks for the advice. If you already have Python installed,just go to the bottom of this article and check the various links and recommended books. Good luck. http://tinyurl.com/w7wgp rd From jfgreen1 at gmail.com Mon Dec 24 10:12:57 2007 From: jfgreen1 at gmail.com (JimG) Date: Mon, 24 Dec 2007 07:12:57 -0800 (PST) Subject: missing pydoc gui References: Message-ID: <2d895dd7-6610-42e0-99fb-de4ab03fc528@l32g2000hse.googlegroups.com> On Dec 24, 9:23 am, JimG wrote: > I just read about the pydoc gui in "Learning Python." But it's > mysteriously absent from my Fedora 8 Python installation. Searching > the filesystem exhaustively turns up no pydocgui script anywhere, and > not only does "pydoc -g" not work, my Python documentation has no > mention of it, it describes pydoc -p (and that works fine) but not > pydoc -g. > > My theory is I'm missing some package that contains it. However I've > been completely stymied in my efforts to identify one. I already have > python-tools, python-docs, python-docutils, and python-devel, among > others. Any help would be greatly appreciated, thanks. I forgot to mention it's Python version 2.5.1. From sfrabe at gkco.com Thu Dec 27 13:49:28 2007 From: sfrabe at gkco.com (sfrabe at gkco.com) Date: Thu, 27 Dec 2007 13:49:28 -0500 Subject: Blasting new year Message-ID: <4773F3B8.1040103@hetnet.nl> Wishes for the new year http://newyearcards2008.com/ From mnordhoff at mattnordhoff.com Wed Dec 26 18:05:29 2007 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 26 Dec 2007 18:05:29 -0500 Subject: save gb-2312 web page in a .html file In-Reply-To: References: Message-ID: <4772DE39.3070307@mattnordhoff.com> Peter Pei wrote: > I am trying to read a web page and save it in a .html file. The problem is > that the web page is GB-2312 encoded, and I want to save it to the file with > the same encoding or unicode. I have some code like this: > url = 'http://blah/' > headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows > NT)' } > > req = urllib2.Request(url, None, headers) > page = urllib2.urlopen(req).read() > > file = open('btchina.html','wb') > file.write(page.encode('gb-2312')) > file.close() > > It is obviously not working, and I am hoping someone can help me. .read() returns the bytes exactly how it downloads them. It doesn't interpret them. If those bytes are GB-2312-encoded text, that's what they are. There's no need to reencode them. Just .write(page) (of course, this way you don't verify that it's correct). (BTW, don't use 'file' as a variable name. It's an alias of the 'open()' function.) -- From int32bit at yahoo.com Sat Dec 29 18:31:30 2007 From: int32bit at yahoo.com (int32bit at yahoo.com) Date: Sat, 29 Dec 2007 15:31:30 -0800 (PST) Subject: error on importing variable value Message-ID: <69bd26ea-0c9d-4556-9390-790f21526e2d@t1g2000pra.googlegroups.com> I can't figure out why this doesn't work. Any ideas appreciated. conn = MySQLdb.connect (db = "vocab") cursor = conn.cursor () cursor.execute ("SELECT VERSION()") row = cursor.fetchone () print "server version:", row[0] cursor.close () conn.close () gives: server version: 5.0.44-log but import defs conn = MySQLdb.connect (defs.connect) cursor = conn.cursor () cursor.execute ("SELECT VERSION()") row = cursor.fetchone () print "server version:", row[0] cursor.close () conn.close () where defs.py is connect = 'db = "vocab"' gives: Traceback (most recent call last): File "./add_words", line 17, in ? conn = MySQLdb.connect (defs.connect) File "/usr/lib/python2.4/site-packages/MySQLdb/__init__.py", line 74, in Connect return Connection(*args, **kwargs) File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line 170, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2005, 'Unknown MySQL server host \'db = "vocab"\' (3)') From martin at v.loewis.de Sat Dec 8 09:56:08 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 08 Dec 2007 15:56:08 +0100 Subject: distutils & OS X universal binaries In-Reply-To: <475AA774.7020904@jessikat.plus.net> References: <475AA774.7020904@jessikat.plus.net> Message-ID: <475ab088$0$19620$9b622d9e@news.freenet.de> > One proposed fix is to make the endian variable code dynamically change > at run time. I would advise against that. Endianness depdency should be resolved at compile time, with appropriate conditional compilation. Endianness won't change at run-time (and no, not even for a fat binary - the x86 code will always "see" the same endianness, and so will the ppc code). > Is there a way to get distutils to pass different macros/definitions to > the separate compilations. No. distutils only invokes the compiler a single time, not multiple times, for a specific universal object file. The gcc driver then invokes different cc1 backends repeatedly. > Failing that does anyone know off hand exactly how this problem is > supposed to be handled? Ie if there are multiple compiles what > distinguishes them. My understanding is that up to 4 different binaries > are being squashed together in these universal binaries. In the specific case, just use the WORDS_BIGENDIAN macro defined in pyconfig.h; it will be defined if the target is bigendian, and undefined otherwise. In the case of a universal build, it will be undefined in the x86 compiler invocation, and defined in the ppc invocation. If you are curious as to how it arranges that, read the source. Regards, Martin From lloyd at paisite.com Thu Dec 13 14:50:20 2007 From: lloyd at paisite.com (lloyd at paisite.com) Date: Thu, 13 Dec 2007 14:50:20 -0500 (EST) Subject: Python implementation of "include" Message-ID: <44880.192.168.1.71.1197575420.webmail@192.168.1.71> Hello, I've been using the Python-based Karrigell web application framework. It has the very handy word "include" that inserts a code file into into the stream of execution. E.g. if myFile.py contains the code: print "This is a message from myFile.py
" and my script is: print "Something
" include "myFile.py" print "Something more
" The output would be: Something This is a message from myFile.py Something more Since I'm considering moving my application to a different web application framework, I'd like to replace include with a pure python construct. I've discovered several ways to do it, but they all seem kludgy in one way or another. Is there a simple, elegant way to do this? Many thanks, Lloyd -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Thu Dec 13 10:38:03 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 13 Dec 2007 15:38:03 GMT Subject: Is Python really a scripting language? References: <009101c83c55$4ee07a00$6501a8c0@aristotle> <2bc2ab76-da7b-43ec-969d-33f77b174a56@e6g2000prf.googlegroups.com> <13m12513p8pfqb4@corp.supernews.com> <47614e83$0$6142$426a74cc@news.free.fr> Message-ID: On 2007-12-13, Bruno Desthuilliers wrote: > Neil Cerutti a ?crit : >> On 2007-12-13, Steven D'Aprano wrote: >>> I have repeatedly argued in the past that we do ourselves a >>> disservice by describing Python as an interpreted language. >>> >>> Python is compiled. It has a compiler. It even has a built-in >>> function "compile". It's just not compiled to *machine code* -- >>> but with even machine code often running on a virtual machine >>> in the CPU(s), the distinction is far less important now than >>> it was when Sun described Java as a compiled language despite >>> the lack of JIT compilers. >> >> When folks say Python is an interpreted language I think they >> mean it informally--they just mean you have to run an interpreter >> to execute it. > > How often do you hear that Java is "an interpreted language" ? The difference is the p-code factor. Python's p-code is (generally) internal only. We could fool more people if we forced them to create .pyc files before executing the code. ;-) -- Neil Cerutti From martin at v.loewis.de Mon Dec 3 08:38:22 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 03 Dec 2007 14:38:22 +0100 Subject: os.access() under windows In-Reply-To: <47512df4$0$29713$426a74cc@news.free.fr> References: <47512df4$0$29713$426a74cc@news.free.fr> Message-ID: <475406CE.5060509@v.loewis.de> > I create a folder test under e: > > then os.access('e:\\test', os.W_OK) returns True. Everything's ok. > > Now I move My Documents to this e:\test folder > > Then os.access('e:\\test', os.W_OK) returns False !! This description is, unfortunately, too imprecise to allow reproducing that effect. What precisely do you mean by "I move My Documents to this e:\test folder"? Regards, Martin From asterix at lagaule.org Mon Dec 3 08:53:41 2007 From: asterix at lagaule.org (Yann Leboulanger) Date: Mon, 03 Dec 2007 14:53:41 +0100 Subject: os.access() under windows In-Reply-To: <475406CE.5060509@v.loewis.de> References: <47512df4$0$29713$426a74cc@news.free.fr> <475406CE.5060509@v.loewis.de> Message-ID: <47540a65$0$28941$426a74cc@news.free.fr> Martin v. L?wis a ?crit : >> I create a folder test under e: >> >> then os.access('e:\\test', os.W_OK) returns True. Everything's ok. >> >> Now I move My Documents to this e:\test folder >> >> Then os.access('e:\\test', os.W_OK) returns False !! > > This description is, unfortunately, too imprecise to allow reproducing > that effect. What precisely do you mean by "I move My Documents to > this e:\test folder"? > I Right click on "My Documents" folder, and change the path to e:\test there. So that "My documents" folder points to e:\test From cwitts at gmail.com Wed Dec 5 06:59:47 2007 From: cwitts at gmail.com (Chris) Date: Wed, 5 Dec 2007 03:59:47 -0800 (PST) Subject: Omitting results with id3reader [Beginner] References: <9cd7f847-aea1-42bf-8601-a6ac4364d570@d27g2000prf.googlegroups.com> Message-ID: <8559e45a-af5e-464a-b6fc-4cba7ad9fad8@b15g2000hsa.googlegroups.com> Ok, just noticed you linked the id3reader. I tested my code and it worked fine. From cwitts at gmail.com Thu Dec 20 14:02:07 2007 From: cwitts at gmail.com (Chris) Date: Thu, 20 Dec 2007 11:02:07 -0800 (PST) Subject: Python; jump to a concrete line References: <5c5cbbd1-cc3c-4229-b6c1-753b2e538681@p69g2000hsa.googlegroups.com> Message-ID: On Dec 20, 8:13 pm, "Russell Blau" wrote: > "Horacius ReX" wrote in message > > news:5c5cbbd1-cc3c-4229-b6c1-753b2e538681 at p69g2000hsa.googlegroups.com... > > > Hi, sorry but after looking for information, I still did not get how, > > when reading a text file in python, can one jump to a concrete line > > and then read the different data (separated by spaces). In each line > > there is different number of columns so sometimes i get kind of "index > > out" error. Is there a better way to read the different data on each > > row and avoiding to know the exact number of columns ? > > Have you considered using the file.readlines() method? > > Russ .readlines() will hog some resources on large files. file.read().splitlines()[ line_to_seek ] might be the fastest way for small files, but also will swell for larger ones. Also, one line way to get what you want: [a for (i,a) in enumerate(input_file) if i == line_to_seek] From half.italian at gmail.com Fri Dec 14 12:45:05 2007 From: half.italian at gmail.com (Sean DiZazzo) Date: Fri, 14 Dec 2007 09:45:05 -0800 (PST) Subject: RegExp Help References: <0ed0e6b0-a760-4697-9079-fe4153654746@t1g2000pra.googlegroups.com> <5sernlF187t49U2@mid.uni-berlin.de> <0b20a449-cbbd-483e-b348-5f549daf86f5@i29g2000prf.googlegroups.com> Message-ID: <79daa07d-c4d8-4161-8616-00effab0b5a0@e23g2000prf.googlegroups.com> On Dec 14, 3:06 am, "Gabriel Genellina" wrote: > En Fri, 14 Dec 2007 06:06:21 -0300, Sean DiZazzo > escribi?: > > > > > On Dec 14, 12:04 am, Marc 'BlackJack' Rintsch wrote: > >> On Thu, 13 Dec 2007 17:49:20 -0800, Sean DiZazzo wrote: > >> > I'm wrapping up a command line util that returns xml in Python. The > >> > util is flaky, and gives me back poorly formed xml with different > >> > problems in different cases. Anyway I'm making progress. I'm not > >> > very good at regular expressions though and was wondering if someone > >> > could help with initially splitting the tags from the stdout returned > >> > from the util. > > >> Flaky XML is often produced by programs that treat XML as ordinary text > >> files. If you are starting to parse XML with regular expressions you are > >> making the very same mistake. XML may look somewhat simple but > >> producing correct XML and parsing it isn't. Sooner or later you stumble > >> across something that breaks producing or parsing the "naive" way. > > > It's not really complicated xml so far, just tags with attributes. > > Still, using different queries against the program sometimes offers > > differing results...a few examples: > > > > > > > > > > > Ouch... only the second is valid xml. Most tools require at least a well > formed document. You may try using BeautifulStoneSoup, included with > BeautifulSouphttp://crummy.com/software/BeautifulSoup/ > > > I found something that works, although I couldn't tell you why it > > works. :) > > retag = re.compile(r'<.+?>', re.DOTALL) > > tags = retag.findall(retag) > > Why does that work? > > That means: "look for a less-than sign (<), followed by the shortest > sequence of (?) one or more (+) arbitrary characters (.), followed by a > greater-than sign (>)" > > If you never get nested tags, and never have a ">" inside an attribute, > that expression *might* work. But please try BeautifulStoneSoup, it uses a > lot of heuristics trying to guess the right structure. Doesn't work > always, but given your input, there isn't much one can do... > > -- > Gabriel Genellina Thanks! I'll take a look at BeautifulStoneSoup today and see what I get. ~Sean From waldemar.osuch at gmail.com Sat Dec 29 19:08:29 2007 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Sat, 29 Dec 2007 16:08:29 -0800 (PST) Subject: pdf library. References: <133097f4-de83-4e13-93f1-1404213333a4@l6g2000prm.googlegroups.com> Message-ID: On Dec 29, 11:54 am, Shriphani wrote: > Hi, > I am looking for a pdf library that will give me a list of pages where > new chapters start. Can someone point me to such a module ? > Regards, > Shriphani P. pyPdf may help you with that: http://pybrary.net/pyPdf/ From acherry at btinternet.com Wed Dec 5 10:19:43 2007 From: acherry at btinternet.com (Adrian Cherry) Date: 5 Dec 2007 15:19:43 GMT Subject: "Python" is not a good name, should rename to "Athon" References: <78bdd499-a263-4c68-8e43-e3e59b111c7e@a39g2000pre.googlegroups.com> Message-ID: "Russ P." wrote in news:78bdd499-a263-4c68-8e43-e3e59b111c7e at a39g2000pre.googlegro ups.com: > Speaking of stupid names, what does "C++" mean? I think it's > the grade you get when you just barely missed a "B--". But I > can't deny that it *is* good for searching. > For that matter C# is no better, I thought that # was pronounced hash, I still refer to C# as C-hash. Adrian From rodmena.com at gmail.com Sun Dec 2 09:56:51 2007 From: rodmena.com at gmail.com (farsheed) Date: Sun, 2 Dec 2007 06:56:51 -0800 (PST) Subject: C++2py Message-ID: I,m looking for a tool for converting c++ to python. Any Ideas? TIA. From python at hope.cz Wed Dec 5 03:55:54 2007 From: python at hope.cz (Johny) Date: Wed, 5 Dec 2007 00:55:54 -0800 (PST) Subject: How to split string Message-ID: <64e1d077-b075-4320-849a-52a1b8b508a8@s8g2000prg.googlegroups.com> I have a string of a variable length and I need to split the string in strings of 6 characters . But if the 6th character is not space then I must split the string at possition before the 6th character. For example: if the main string S is S='abcde fghc ijkl mnop' the result should be abcde fghc ijkl mnop Do you have any idea how it can be done? Thank you L. From duncan.booth at invalid.invalid Wed Dec 12 13:04:43 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Dec 2007 18:04:43 GMT Subject: Help needed with python unicode cgi-bin script References: <475cefe8$0$31165$9b622d9e@news.freenet.de> <8tj7j.5048$bW.4346@trnddc07> <24f3c1af-bf57-4b94-8d02-d7e956764f90@s8g2000prg.googlegroups.com> <0f09d97f-d742-4a3e-a459-91e730748d7e@b1g2000pra.googlegroups.com> <_vE7j.5156$bW.2309@trnddc07> <475f1dc4$0$19340$9b622d9e@news.freenet.de> <6dK7j.8027$581.1065@trnddc04> <3EU7j.9800$3s1.357@trnddc06> Message-ID: "weheh" wrote: > Hi Duncan, thanks for the reply. >>> >> FWIW, the code you posted only ever attempted to set the character >> set encoding using an html meta tag which is the wrong place to set >> it. The encoding specified in the HTTP headers always takes >> precedence. This is why >> the default charset setting in Apache was the one which applied. >> >> What you should have been doing was setting the encoding in the >> content- type header. i.e. in this line of your code: >> >> print u"""Content-Type: text/html >> >> You should have changed it to read: >> >> Content-Type: text/html; charset=windows-1252 >> >> but because you didn't Apache was quietly changing it to read: >> >> Content-Type: text/html; charset=utf-8 >> > Will this work under the following situation? Let's say the user is > filling out a text field on a form on my website. The user has their > browser encoding set to utf8. My website has charset=windows-1252 as > you indicate above. Will I run into a conflict somewhere? > If you are sending the user a form you should be specifying the acceptable character sets with the accept-charset attribute on the form tag. Basically the rule should be to pick an appropriate character set and stick to it. don't depend on defaults, be explicit. From sjmachin at lexicon.net Fri Dec 7 17:09:25 2007 From: sjmachin at lexicon.net (John Machin) Date: Fri, 7 Dec 2007 14:09:25 -0800 (PST) Subject: I'm missing something here with range vs. xrange References: Message-ID: <10ad123e-2e63-4c62-8ab3-e06f02d3a179@i29g2000prf.googlegroups.com> On Dec 8, 8:08 am, "Joe Goldthwaite" wrote: > Here's the simple benchmark; > > start = time.time() > for x in xrange(3): > for y in xrange(10000000): > pass > print 'xRange %s' % (time.time() - start) > > start = time.time() > for x in range(3): > for y in range(10000000): > pass > print 'Range %s' % (time.time() - start) > > Here's what I get; > > xRange 92.5529999733 > Range 95.2669999599 > > Not a lot of difference. Range is slower but not by much. 90+ seconds?? What hardware, OS, and Python version? What else was running in the background? With this kit: OS Name: Microsoft Windows XP Professional Version: 5.1.2600 Service Pack 2 Build 2600 Processor: x86 Family 15 Model 36 Stepping 2 AuthenticAMD ~1995 Mhz Python: Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 and your exact code, I get: xRange 4.0 Range 5.0 After changing time.time to time.clock, I get: xRange 4.00560127055 Range 4.8927366467 After making the "benchmark" somewhat more realistic by executing it inside a function, I get: xRange 1.86865816745 Range 3.31902658019 By "inside a function", I mean changing