From claird at lairds.us Thu Aug 23 11:28:28 2007 From: claird at lairds.us (Cameron Laird) Date: Thu, 23 Aug 2007 15:28:28 +0000 Subject: simple spider in python References: <1187876014.845912.236690@e9g2000prf.googlegroups.com> <1187879398.007797.128510@i13g2000prf.googlegroups.com> <1187880988.813113.20350@l22g2000prc.googlegroups.com> Message-ID: In article <1187880988.813113.20350 at l22g2000prc.googlegroups.com>, wrote: >thanks everybody, soooo kind. I'll take a look at booth. >have a nice day/night (depending on your latitude!) ^_^ > >ciao! > Somewhere in the middle between the two suggestions you've already received is . From hancock.robert at gmail.com Wed Aug 22 11:39:23 2007 From: hancock.robert at gmail.com (milan_sanremo) Date: Wed, 22 Aug 2007 15:39:23 -0000 Subject: chmod g+ Equivalent In-Reply-To: References: <1187042290.821786.178420@19g2000hsx.googlegroups.com> <1187094251.540591.308320@g4g2000hsf.googlegroups.com> Message-ID: <1187797163.590430.158330@r23g2000prd.googlegroups.com> On Aug 14, 7:30 pm, Steve Holden wrote: > milan_sanremo wrote: > > On Aug 13, 8:06 pm, Steve Holden wrote: > >> milan_sanremo wrote: > >>> I've read the documentation on os.chmod() and can implement all the > >>> standard commands, but what is the syntax for the equivalent of chmod g > >>> + to set the group id? > >> I assume when you say "to set the group id" you actually mean "to assert > >> the setgid bit"? I further presume that when you say "chmod g+" you > >> actually mean "chmod g+s". > > > The g+s was an omission on my part. I can see how it would confuse > > the issue. > > > I'm not sure if I mean "to assert the setgid bit". My SUN docs refer > > to it being 'on'. > >http://docs.sun.com/app/docs/doc/819-3321/6n5i4b767?l=en&a=view&q=set... > > >> You can't have read the documentation very thoroughly. It says right at > >> the top: > > >> S_ISUID > >> S_ISGID > > > I did see this in the documentation: > > > Change the mode of path to the numeric mode. mode may take one of the > > following values (as defined in the stat module) or bitwise or-ed > > combinations of them: > > > * S_ISUID > > * S_ISGID > > > Which refers to: > >http://docs.python.org/lib/module-stat.html > > > After which it was still unclear. > > > My question is in the command os.chmod(myDirectory, ?) what is the > > value for ? to turn on the setgid bit. > > > Contrary to your presumption, I did read the documentation > > thoroughly. It is inability to understand the concept which prompted > > me to post the question here. > > Well, you don't tell us what (if anything) you have tried so far. Python > has an interpreter that's very easy to use interactively. Why don't you try > > os.chmod(my_directory, os.S_ISGID) > > and see if it does what you want? You can often save time by trying such > things for yourself. Though it needn't be a substitute for asking > questions on this list, it can make your questions better-informed. > > In this particular case, now I understand your needs a little better, > since you want to *add* a bit setting you will likely have to use > something like > > current_permissions = os.fstat(my_directory).ST_MODE > > to read the directory's current permission bits. Then you will need to > execute > > os.chmod(my_directory, current_permissions | stat.S_ISGID) > > Please don't take this as gospel, though, as I am currently on the road > with only a Windows computer available, but I think it should get you > closer to where you want to be. > > regards > Steve > -- os.chmod(my_directory, cur_permissions | (stat.S_ISGID | 8)) gave the equivalent of chmod g+s. From mcfletch at vrplumber.com Mon Aug 20 10:44:22 2007 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Mon, 20 Aug 2007 10:44:22 -0400 Subject: Call for advice on how to start PyOpenGL! In-Reply-To: <1187589198.616866.280500@j4g2000prf.googlegroups.com> References: <1187589198.616866.280500@j4g2000prf.googlegroups.com> Message-ID: <46C9A8C6.9010402@vrplumber.com> math2life wrote: > I work with python for two years, are familiar with image processing, > but beginner on PyOpenGL and OpenGL. > > Any advice appreciated! > As has been mentioned, the NeHe tutorials[1] are a good starting point. There are (multiple) translations of the first 8 or so and then some cherry-picked translations further along the set. There is a set of OpenGL demo/sample code available[2] as a separate download from the 3.x series (these files are mostly included in the 2.x series, though there is new material in the 3.x set). OpenGLContext also has a large number of simple samples, though I've still got "release OpenGLContext" on my seemingly infinitely long and growing todo list, so that might not be the easiest way to start. The "Red Book" is an older standard manual for getting started with (C) OpenGL code, often you can find older editions online for free. There are hundreds of C tutorials hanging around the net that normally translate easily into Python/PyOpenGL. The PyOpenGL manual pages *try* to have links to source code, but unfortunately the (java, ick!) based system that generates the base files has been broken for a while and I haven't had time to fix it properly so I can re-run the generator to update the links. In the meantime, Google's code search helps a lot when you restrict to Python code.[3] HTH, Mike [1] http://nehe.gamedev.net [2] http://sourceforge.net/project/showfiles.php?group_id=5988&package_id=221827 [3] http://www.google.com/codesearch?q=lang%3Apython -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From linnewbie at gmail.com Sun Aug 12 13:50:06 2007 From: linnewbie at gmail.com (linnewbie at gmail.com) Date: Sun, 12 Aug 2007 17:50:06 -0000 Subject: Regular Expression Grouping In-Reply-To: <46bf43fe$0$10626$4fafbaef@reader2.news.tin.it> References: <1186939262.144073.182450@z24g2000prh.googlegroups.com> <46bf43fe$0$10626$4fafbaef@reader2.news.tin.it> Message-ID: <1186941006.758681.243340@q4g2000prc.googlegroups.com> On Aug 12, 1:31 pm, Fabio Z Tessitore wrote: > Il Sun, 12 Aug 2007 17:21:02 +0000, linnewbie ha scritto: > > > Fairly new to this regex thing, so this might be very juvenile but > > important. > > > I cannot understand and why 'c' constitutes a group here without being > > surrounded by "(" ,")" ? > > >>>>import re > >>>> m = re.match("([abc])+", "abc") > >>>> m.groups() > > ('c',) > > > Grateful for any clarity. > > thera are () outer [], maybe you don't know what do [] mean? or you want > to know why 'c' and not 'a' or 'b' > bye I sort of get what the metacharacters "(", ")" and "[" ,"]" , groups are marked by the "(", ")" no? So I get this: >>> import re >>> re.match("ab(c)d","abcd") <_sre.SRE_Match object at 0xb7d72c60> >>> m= re.match("ab(c)d","abcd") >>> m.groups() ('c',) I can see clearly here that 'c' is group(1), because of the "..(c).. ". I cannot see how 'c' is a inner group in the expressions "([abc]) +" above? From joesox at gmail.com Tue Aug 21 09:42:46 2007 From: joesox at gmail.com (JoeSox) Date: Tue, 21 Aug 2007 06:42:46 -0700 Subject: Python project solicitation In-Reply-To: <1187701752.661991.144690@q3g2000prf.googlegroups.com> References: <1187701752.661991.144690@q3g2000prf.googlegroups.com> Message-ID: <785694cd0708210642g736471f0kd3a761b12aba8ba5@mail.gmail.com> On 8/21/07, Greg Copeland wrote: > > On Aug 20, 9:35 pm, JoeSox wrote: > > I must say this thing is pretty cool. I had a coworker try it out and > > he ran into problems getting it to run on his Linux OS. So I am > > really looking for some non-Windows developers to take a look at it. > > All of the info is at the project site above. > > Thanks. > > > > I looked at it real quick. You need to use os.path.join for your file > paths. You also need to use sys.platform for windows specific > processing. For example: > > if sys.platform == 'Win32': > FS_ROOT = 'C:' > else: > FS_ROOT = '/' > > WORDNETPATH=os.path.join( FS_ROOT, 'WordNet', '2.1', 'dict' ) > > So on and so on. You wrote it very MSWin centric so it is not a > surprise it has trouble of on other platforms. All of your file > references need to be adjusted as above using os.path.join. > > Keep in mind I only looked at it real quick. Those appear to be the > cross platform deal killers. Short of something I missed (could > have), it should work find on most any other platform once you take > out the Windows-isms. Excellent. I will look at this. Being a hobbyist programmer, I am use to writing code just for a Windows environment. I've only been using Python for a year or so and I never could get into Java. -- Later, Joe From lasses_weil at klapptsowieso.net Thu Aug 30 20:12:36 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Fri, 31 Aug 2007 02:12:36 +0200 Subject: strings (dollar.cents) into floats In-Reply-To: <877incd20i.fsf@benfinney.id.au> References: <877incd20i.fsf@benfinney.id.au> Message-ID: <46d75cf3$0$7698$9b4e6d93@newsspool2.arcor-online.net> Ben Finney wrote: > You most likely do *not* want floating-point numbers for currency, > since they rely on the operating system's binary floating point > support which cannot accurately represent decimal fractions. > I've heard (ok, read) that several times now and I understand the argument. But what use is there for floats, then? When is it OK to use them? /W From tonylabarbara at aol.com Tue Aug 14 15:47:02 2007 From: tonylabarbara at aol.com (tonylabarbara at aol.com) Date: Tue, 14 Aug 2007 15:47:02 -0400 Subject: Form-Through-Script Nightmare Message-ID: <8C9ACC304FF3A9E-DD0-22B2@WEBMAIL-DC12.sysops.aol.com> Hi; I originally submitted this to the Zope list, but after no replies and realizing it's probably better suited for the python list, I'm submitting it here. I have a form where purchasers can deselect items they've added to their shopping cart. All the hidden fields have been numbered according to the items they *originally* selected. If they deselect an item, then it will probably necessitate a renumbering of all those hidden fields, since PayPal doesn't tolerate misnumbering: everything must be numbered "1" for all the hidden fields of the first product, "2" for the second, etc. If the customer selects 5 products and deletes the 3rd, then I need to renumber. I wrote a script that can do that. Now, I have to send the form to that script, with all its lovely hidden fields, then reproduce it somewhere so I can send it off to PP. That is, the form must return from the called script to a new page and deliver all the renumbered hidden fields. ? Let me summarize what I've written before to put in one post exactly what's going on: 1)?I have a form that I need to send to a script and then send off to a URL (PayPal). I need to process it through the script to renumber things for PP. How do I do this? I imagine I add an element to the PT like so:
but I need to pass a parameter "doc", which, of course, is the document I'm submitting. So I tried this:

which renders my page fine, but throws an error when I submit the form: Cannot locate object at: http://example.com/s/c/x/j/en-us/s/renumberTheCart%28here meaning, of course, that it didn't receive the required parameter. 2) I changed it to an absolute URL just to double-check, and got basically the same error: ? Invalid request The parameter, doc, was omitted from the request. How do I pass the parameter, which in my case is quite long and stashed neatly away in a PT macro? ?

? Now, Tom Von Lahndorff suggested the following: Sounds like the script should check to see if the user is removing something like: if remove remove the item redirect back to the udpated form page else send to PP this way once the item is removed and the same script is called, since there's no remove this time, it'll go to PP. I would LOVE to do that...if I knew how! Any ideas? TIA, Tony ? Invalid request The parameter, doc, was omitted from the request. How do I pass the parameter, which in my case is quite long and stashed neatly away in a PT macro? ?

? Now, Tom Von Lahndorff suggested the following: Sounds like the script should check to see if the user is removing something like: if remove remove the item redirect back to the udpated form page else send to PP this way once the item is removed and the same script is called, since there's no remove this time, it'll go to PP. I would LOVE to do that...if I knew how! Any ideas? TIA, Tony ________________________________________________________________________ AOL now offers free email to everyone. Find out more about what's free from AOL at AOL.com. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rcdailey at gmail.com Wed Aug 22 17:47:09 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 22 Aug 2007 16:47:09 -0500 Subject: Class destruction In-Reply-To: <46CC8482.9040100@gmx.de> References: <496954360708221117pd7465fr838a24b167a1dcdd@mail.gmail.com> <46CC8482.9040100@gmx.de> Message-ID: <496954360708221447l3c72e6dcqd82d46ecd64c9a38@mail.gmail.com> Thanks; I'll give it a try. On 8/22/07, Nils Oliver Kr?ger wrote: > > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Robert Dailey schrieb: > > Hi, > > > > I'm wondering where the most appropriate location is to cleanup class > > objects. For example, i have a file handle as an instance attribute in > one > > of my classes and I need to call f.close() on it when the class object > falls > > out of scope. Any ideas? I've tried __del__() but I don't remember this > > working for some reason. I might try it again later just to be positive. > > __del__(self) is the perfectly right place for such cleanup ... it gets > called once your instance is either deleted explicitly by you or it's > handled by the garbage collector when there are no more references. > > The possible problem why this did not work four you is, that the > destruction by the garbage collector cannot be predicted ... it may well > take some time. If you try to open the same file from another class > before yours gets cleaned you run into trouble. > > If you want to "reuse" the file, you will have to delete your classes > instance explicitly using the del statement ... this will also call the > destructor. > > The below code works fine: > > def __del__( self ): > self._file.close() > print "File closed" > > Hope that helps ... Nils > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (MingW32) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iD8DBQFGzISBzvGJy8WEGTcRAiOwAJ94fJza4/GVQsFmbXwsP8kdvQjV5wCfQktw > F/zPJAw0ayjYe5MGxPR1YqI= > =4Hl6 > -----END PGP SIGNATURE----- > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Mon Aug 6 08:07:45 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 06 Aug 2007 05:07:45 -0700 Subject: Misleading wikipedia article on Python 3? In-Reply-To: <7xzm15q8fy.fsf@ruckus.brouhaha.com> References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <7xzm15q8fy.fsf@ruckus.brouhaha.com> Message-ID: <1186402065.085131.66090@22g2000hsm.googlegroups.com> On 6 Aug, 12:11, Paul Rubin wrote: > Carsten Haese writes: > > For instance, if you never use print statements in your code, you won't > > notice that print is becoming a function. If you do, you'll have to make > > appropriate accommodations. > > Why on earth did they make this change? It just seems gratuitous. Is > the assert statement also being changed? Are they going to update all > the docs that say that the yield statement works like the print statement? Indeed: practicality beats purity [1]. Uh, wait a moment! Paul [1] http://www.python.org/dev/culture/ From gherzig at fmed.uba.ar Fri Aug 31 09:36:40 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Fri, 31 Aug 2007 10:36:40 -0300 Subject: pure python for sms In-Reply-To: References: Message-ID: <46D81968.60303@fmed.uba.ar> Neil Hodgson wrote: >Gerardo Herzig: > > > >>Hi dudes. Im looking for a python implementation for sending sms to a >>cell phone. I was try using some free pages, but i want to use a python. >>Do i need a cellphone conected to my machine? Or can i send sms to some >>cell via some python library? >> >> > > This is likely to cost some money similar to sending an SMS from a >'phone. There are several companies that provide SMS sending services >that can be accessed through HTTP. Have a look at www.clickatell.com and >www.aql.com . Here is a library based on Clickatell: >http://www.powertrip.co.za/code/python/clickatell.py > > Neil > > Well, im not triyng to send a SMS `FROM' a cellphone, im trying to send a SMS `TO' a cellphone. Here (in Argentina) are several sites who lets you send a sms for free. You also can receive SMS responses via this page http://sms.personal.com.ar/Mensajes/msn.htm While my tries using this page via urllib failed, i dont want to depend on an external page anyway. The python class you send to me looks like a pay site (if not, i dont see why the tokenpay() and getbalance() methods :) I was also avaiable to send a sms in the form of an plain email __cellphone_number at i_used_to_be_cool_smtp.com, but it not seems to work this way no longer. Again, i dont want to do it that way anyway. Thats why im looking for a python implementation of that funcionality. Thanks! Gerardo From nospam.themindstorm at gmail.com Thu Aug 2 04:10:49 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Thu, 2 Aug 2007 08:10:49 +0000 (UTC) Subject: a dict trick References: <1186036331.304916.304020@e9g2000prf.googlegroups.com> Message-ID: james_027 wrote in news:1186036331.304916.304020 @e9g2000prf.googlegroups.com: > hi > > for example I have this dictionary > > dict = {'name':'james', 'language':'english'} > > value = 'sex' in dict and dict['sex'] or 'unknown' > > is a right pythonic of doing this one? I am trying to get a value from > the dict, but if the key doesn't exist I will provide one. > > THanks > james > Same question discussed at large not far ago: subject: "Pythonic way of missing dict keys" [1] bests, ./alex -- .w( the_mindstorm )p. [1] http://groups.google.com/group/comp.lang.python/browse_thread/thread/175eb4 5909a05a18 From marduk at nbk.hopto.org Thu Aug 2 16:01:27 2007 From: marduk at nbk.hopto.org (marduk) Date: Thu, 02 Aug 2007 15:01:27 -0500 Subject: Berkely Db. How to iterate over large number of keys "quickly" In-Reply-To: <1186083838.318952.254370@q3g2000prf.googlegroups.com> References: <1186083838.318952.254370@q3g2000prf.googlegroups.com> Message-ID: <1186084887.23192.56.camel@blackwidow.nbk> On Thu, 2007-08-02 at 19:43 +0000, lazy wrote: > I have a berkely db and Im using the bsddb module to access it. The Db > is quite huge (anywhere from 2-30GB). I want to iterate over the keys > serially. > I tried using something basic like > > for key in db.keys() > > but this takes lot of time. I guess Python is trying to get the list > of all keys first and probbaly keep it in memory. Is there a way to > avoid this, since I just want to access keys serially. I mean is there > a way I can tell Python to not load all keys, but try to access it as > the loop progresses(like in a linked list). I could find any accessor > methonds on bsddb to this with my initial search. > I am guessing BTree might be a good choice here, but since while the > Dbs were written it was opened using hashopen, Im not able to use > btopen when I want to iterate over the db. > try instead key = db.firstkey() while key != None: # do something with db[key] key = db.nextkey(key) From jmtulloss at gmail.com Fri Aug 10 12:37:19 2007 From: jmtulloss at gmail.com (Justin T.) Date: Fri, 10 Aug 2007 16:37:19 -0000 Subject: The Future of Python Threading In-Reply-To: References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> Message-ID: <1186763839.203679.110810@z24g2000prh.googlegroups.com> On Aug 10, 3:52 am, Jean-Paul Calderone wrote: > On Fri, 10 Aug 2007 10:01:51 -0000, "Justin T." wrote: > >Hello, > > >While I don't pretend to be an authority on the subject, a few days of > >research has lead me to believe that a discussion needs to be started > >(or continued) on the state and direction of multi-threading python. > > > [snip - threading in Python doesn't exploit hardware level parallelism > > well, we should incorporate stackless and remove the GIL to fix this] > > I think you have a misunderstanding of what greenlets are. Greenlets are > essentially a non-preemptive user-space threading mechanism. They do not > allow hardware level parallelism to be exploited. I'm not an expert, but I understand that much. What greenlets do is force the programmer to think about concurrent programming. It doesn't force them to think about real threads, which is good, because a computer should take care of that for you.Greenlets are nice because they can run concurrently, but they don't have to. This means you can safely divide them up among many threads. You could not safely do this with just any old python program. > > >There has been much discussion on this in the past [2]. Those > >discussions, I feel, were premature. Now that stackless is mature (and > >continuation free!), Py3k is in full swing, and parallel programming > >has been fully realized as THE next big problem for computer science, > >the time is ripe for discussing how we will approach multi-threading > >in the future. > > Many of the discussions rehash the same issues as previous ones. Many > of them are started based on false assumptions or are discussions between > people who don't have a firm grasp of the relevant issues. That's true, but there are actually a lot of good ideas in there as well. > > I don't intend to suggest that no improvements can be made in this area of > Python interpreter development, but it is a complex issue and cheerleading > will only advance the cause so far. At some point, someone needs to write > some code. Stackless is great, but it's not the code that will solve this > problem. Why not? It doesn't solve it on its own, but its a pretty good start towards something that could. From monty.python at fastmail.fm Wed Aug 22 04:52:06 2007 From: monty.python at fastmail.fm (David N Montgomery) Date: Wed, 22 Aug 2007 09:52:06 +0100 Subject: How to optimise this code? In-Reply-To: <1187750385.511936.318560@i13g2000prf.googlegroups.com> References: <1187750385.511936.318560@i13g2000prf.googlegroups.com> Message-ID: <1187772726.2139.1206656721@webmail.messagingengine.com> On Wed, 22 Aug 2007 02:39:45 -0000, "Basilisk96" said: > David, > > If your true design intent is to run X number of test cases, unittest > is the biggest bang for your buck, like shown by Peter's example. You > just subclass unittest.TestCase, and def your test methods in the > class body; they will simply be executed in the order you list them. > It's just nice how it works that way. > > Otherwise, the function factory approach like Hrvoje's > functionToCall = getattr(self, "testCase%s" % tc) > is the best optimization. > > Cheers, > -Basilisk96 > > -- > http://mail.python.org/mailman/listinfo/python-list Thank you all - the assistance is much appreciated. unittest is the best choice for my needs and works perfectly in Eclipse. Unfortunately though it (and many other things) does not work under the application we have to use to run our python scripts. This leaves me with 'functionToCall = getattr(self, "testCase%s" % tc)'. This achieves the optimisation/simplification I had been looking for. Thank you once again. From rodrigo.cr at gmail.com Tue Aug 28 14:13:12 2007 From: rodrigo.cr at gmail.com (rodrigo) Date: Tue, 28 Aug 2007 18:13:12 -0000 Subject: Check for dict key existence, and modify it in one step. In-Reply-To: References: <1188311810.226363.295500@w3g2000hsg.googlegroups.com> Message-ID: <1188324792.670603.208980@r29g2000hsg.googlegroups.com> evan, yes, it does help. Works like it should: class CountingDictionary(dict): def increment(self, key, delta=1): self[key] = self.get(key, 0) + delta d = CountingDictionary() d.increment('cat') d.increment('dog',72) print d >>> {'dog': 72, 'cat': 1} Thanks! From wolf_tracks at invalid.com Wed Aug 22 15:32:38 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Wed, 22 Aug 2007 19:32:38 GMT Subject: What Are These Import/From Statements about? In-Reply-To: References: Message-ID: While that's an interesting link, I was thinking of the named items like: Numeric, (this one I know about.) Image ImageChops ImageTk time binascii tkMessageBox tkSimpleDialog ... For example, what is the Image module? MakeQTE? ospath? Robert Kern wrote: > W. Watson wrote: >> Is there a single source that explains these statements? > > http://docs.python.org/tut/node8.html > -- Wayne Watson (Nevada City, CA) Web Page: From floris.bruynooghe at gmail.com Tue Aug 21 08:48:59 2007 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Tue, 21 Aug 2007 05:48:59 -0700 Subject: Module level descriptors or properties Message-ID: <1187700539.312552.89340@w3g2000hsg.googlegroups.com> Hi When in a new-style class you can easily transform attributes into descriptors using the property() builtin. However there seems to be no way to achieve something similar on the module level, i.e. if there's a "version" attribute on the module, the only way to change that to some computation later is by using a getter from the start as your public API. This seems ugly to me. Does anyone know of a better way to handle this? Regards Floris From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Aug 11 17:35:50 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 11 Aug 2007 23:35:50 +0200 Subject: Who told str() to round my int()'s!!! References: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> Message-ID: <5i6odmF3mr9f4U1@mid.individual.net> Adam W. wrote: > Why in the world does str() have any business rounding my numbers, You are at the floating point numbers precision limit. Using str, numbers are rounded to your machine's float precision in decimal notation. Since floats are internally represented in binary notation of constant precision, the decimal precision expressed in number of places is not constant. Thus, safe rounding must be applied to get consistent results. > and how do I get around this? If you don't want this (and thus introduce random deviations if you assume greater precision than the number of places str gives you), use repr. You've been warned. >>> foonum = .0071299720384678782 >>> foonum 0.0071299720384678782 >>> str(foonum) '0.00712997203847' >>> repr(foonum) '0.0071299720384678782' Regards, Bj?rn -- BOFH excuse #5: static from plastic slide rules From bignose+hates-spam at benfinney.id.au Fri Aug 10 06:05:45 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 10 Aug 2007 20:05:45 +1000 Subject: beginner whitespace question References: <1186703261.136506.208660@x35g2000prf.googlegroups.com> <1186703525.591462.122140@m37g2000prh.googlegroups.com> <1186704161.334597.218750@z24g2000prh.googlegroups.com> <1186707164.095766.243480@q3g2000prf.googlegroups.com> <1186708404.901323.204730@g12g2000prg.googlegroups.com> <1186716319.025828.93780@g12g2000prg.googlegroups.com> Message-ID: <87tzr74scm.fsf@benfinney.id.au> James Stroud writes: > When you want to screw your whitespace--don't! > Take this little pledge and I know you won't: James, you're a poet And you don't even realise -- \ "[...] a Microsoft Certified System Engineer is to information | `\ technology as a McDonalds Certified Food Specialist is to the | _o__) culinary arts." ?Michael Bacarella | Ben Finney From jgardner.jonathangardner.net at gmail.com Thu Aug 16 21:28:34 2007 From: jgardner.jonathangardner.net at gmail.com (Jonathan Gardner) Date: Fri, 17 Aug 2007 01:28:34 -0000 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: <1187303750.590497.208060@x40g2000prg.googlegroups.com> References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> Message-ID: <1187314114.873306.187500@e9g2000prf.googlegroups.com> On Aug 16, 3:35 pm, beginner wrote: > > In perl it is just one line: $a=$b->{"A"} ||={}. > a = b.setdefault('A', {}) This combines all two actions together: - Sets b['A'] to {} if it is not already defined - Assigns b['A'] to a More info on dict methods here: http://docs.python.org/lib/typesmapping.html From laurent.pointal at limsi.fr Fri Aug 24 06:46:29 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 24 Aug 2007 12:46:29 +0200 Subject: How to minimize command window when running wxPython script In-Reply-To: <1187951532.156581.25680@e9g2000prf.googlegroups.com> References: <1187951532.156581.25680@e9g2000prf.googlegroups.com> Message-ID: care02 at gmail.com a ?crit : > Dear friends, > > I have almost completed my first wxPython application. The only thing > I need now is to minimize the command window. How is this accomplished > on Win32? Use a .pyw main module (eventually a wrapper calling your main .py module) - it is associated with pythonw.exe, which dont open a console. [note: this is in the FAQ] From db3l.net at gmail.com Thu Aug 30 17:07:40 2007 From: db3l.net at gmail.com (David Bolen) Date: Thu, 30 Aug 2007 17:07:40 -0400 Subject: Unzip: Memory Error References: <1188413939.834662.193180@y42g2000hsy.googlegroups.com> <1188472431.290871.103720@o80g2000hse.googlegroups.com> Message-ID: David Bolen writes: > If you are going to read the file data incrementally from the zip file > (which is what my other post provided) you'll prevent the huge memory > allocations and risk of running out of resource, but would have to > implement your own line ending support if you then needed to process > that data in a line-by-line mode. Not terribly hard, but more > complicated than my prior sample which just returned raw data chunks. Here's a small example of a ZipFile subclass (tested a bit this time) that implements two generator methods: read_generator Yields raw data from the file readline_generator Yields "lines" from the file (per splitlines) It also corrects my prior code posting which didn't really skip over the file header properly (due to the variable sized name/extra fields). Needs Python 2.3+ for generator support (or 2.2 with __future__ import) Peak memory use is set "roughly" by the optional chunk parameter. It's roughly since that's an uncompressed chunk so will grow in memory during decompression. And the readline generator adds further copies for the data split into lines. For your file processing by line, it could be used as in: zipf = ZipFileGen('somefile.zip') g = zipf.readline_generator('somefilename.txt') for line in g: dealwithline(line) zipf.close() Even if not a perfect match, it should point you further in the right direction. -- David - - - - - - - - - - - - - - - - - - - - - - - - - import zipfile import zlib import struct class ZipFileGen(zipfile.ZipFile): def read_generator(self, name, chunk=65536): """Return a generator that yields file bytes for name incrementally. The optional chunk parameter controls the chunk size read from the underlying zip file. For compressed files, the data length returned by the generator will be larger as the decompressed version of a chunk. Note that unlike read(), this method does not preserve the internal file pointer and should not be mixed with write operations. Nor does it verify that the ZipFile is still opened and for reading. Multiple generators returned by this function are not designed to be used simultaneously (they do not re-seek the underlying file for each request.""" zinfo = self.getinfo(name) compressed = (zinfo.compress_type == zipfile.ZIP_DEFLATED) if compressed: dc = zlib.decompressobj(-15) self.fp.seek(zinfo.header_offset) # Skip the file header (from zipfile.ZipFile.read()) fheader = self.fp.read(30) if fheader[0:4] != zipfile.stringFileHeader: raise zipfile.BadZipfile, "Bad magic number for file header" fheader = struct.unpack(zipfile.structFileHeader, fheader) fname = self.fp.read(fheader[zipfile._FH_FILENAME_LENGTH]) if fheader[zipfile._FH_EXTRA_FIELD_LENGTH]: self.fp.read(fheader[zipfile._FH_EXTRA_FIELD_LENGTH]) # Process the file incrementally remain = zinfo.compress_size while remain: bytes = self.fp.read(min(remain, chunk)) remain -= len(bytes) if compressed: bytes = dc.decompress(bytes) yield bytes if compressed: bytes = dc.decompress('Z') + dc.flush() if bytes: yield bytes def readline_generator(self, name, chunk=65536): """Return a generator that yields lines from a file within the zip incrementally. Line ending detection based on splitlines(), and like file.readline(), the returned line does not include the line ending. Efficiency not guaranteed if used with non-textual files. Uses a read_generator() generator to retrieve file data incrementally, so it inherits the limitations of that method as well, and the optional chunk parameter is passed to read_generator unchanged.""" partial = '' g = self.read_generator(name, chunk=chunk) for bytes in g: # Break current chunk into lines lines = bytes.splitlines() # Add any prior partial line to first line if partial: lines[0] = partial + lines[0] # If the current chunk didn't happen to break on a line ending, # save the partial line for next time if bytes[-1] not in ('\n', '\r'): partial = lines.pop() # Then yield the lines we've identified so far for curline in lines: yield curline # Return any trailing data (if file didn't end in a line ending) if partial: yield partial From ldo at geek-central.gen.new_zealand Fri Aug 31 23:37:51 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 01 Sep 2007 15:37:51 +1200 Subject: How to find out if the interpreter is a debug build? References: <1188609417.273513.74450@i13g2000prf.googlegroups.com> Message-ID: In message <1188609417.273513.74450 at i13g2000prf.googlegroups.com>, llothar wrote: > How can i find out if a selected python interpreter (i only know the > path name under which i should start it) is a debug build? What's the difference in their behaviour? From witham.ian at gmail.com Wed Aug 1 18:46:16 2007 From: witham.ian at gmail.com (Ian Witham) Date: Wed, 01 Aug 2007 22:46:16 -0000 Subject: Filemaker interactions In-Reply-To: References: <1186004514.108975.119380@e9g2000prf.googlegroups.com> Message-ID: <1186008376.850181.237250@d30g2000prg.googlegroups.com> On Aug 2, 10:13 am, Jay Loden wrote: > Ian Witham wrote: > > Hello, > > > I'm hoping someone here can put me on the right track with some broad > > concepts here. > > > What I am hoping to achieve is a simple HTML page to be served over > > our company LAN, into which the users (Real Estate Agents) can enter a > > property address or reference number. > > > My next thought was to have a Python CGI script query our filemaker > > database of property listings, construct a PDF from the relevant > > information, and finally return this PDF to the user. > > > At no stage do I want the user to have unfettered access to the > > database or the ability to alter/delete records. > > > My question is: what is the most appropriate way for my script to > > interact with Filemaker? Can this be done with Filemaker Pro 6? > > > According to the Filemaker Help, the "Local Data Access Companion" > > shares the FileMaker Pro database with ODBC-compliant applications on > > the same computer. Is this the right option? > > > Can my CGI script be an ODBC client? How? Would it need to be > > Filemaker specific code or does ODBC have a standardised format? > > > I'm grateful for any advice and a nudge in the right direction. > > > Ian. > > I don't know if this helps, but there is a PyFileMaker module for Python for interacting with FileMaker:http://www.sourcefiles.org/Programming/Development/Modules/Python/PyF... > > That seems to be the only still working link to the module I can find, so I'm guessing it's not in active development. > > -Jay Thanks for that. I've come across it before but never found a working link! I'll let you know how I get on. Ian. From http Fri Aug 31 05:46:44 2007 From: http (Paul Rubin) Date: 31 Aug 2007 02:46:44 -0700 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> Message-ID: <7xwsvcc9yz.fsf@ruckus.brouhaha.com> aleax at mac.com (Alex Martelli) writes: > Yeah, good question indeed, and I'm asking myself that -- somebody who > posts to this group in order to attack the reliability of the language > the group is about (and appears to be supremely ignorant about its use > in air-traffic control and for high-reliability mission-critical > applications such as Google's "Production Systems" software) might well > be considered not worth responding to. OTOH, you _did_ irritate me > enough that I feel happier for venting in response;-) Hi Alex, I'm a little confused: does Production Systems mean stuff like the Google search engine, which (as you described further up in your message) achieves its reliability at least partly by massive redundancy and failover when something breaks? In that case why is it so important that the software be highly reliable? Is a software fault really worse than a hardware fault, especially if it's permissible to sometimes let a transaction (like a search query) go uncompleted (e.g. by displaying a "try again later" message)? If you get 1 billion queries in a month and a half dozen of them don't complete (e.g. they give empty or incorrect results when there are some good hits they should display) but the server is never actually down, can you still claim 100% uptime? There's a philosophy in Erlang described as "let it crash", i.e. programmers are told NOT to program defensively such as by checking inputs for validity. Instead they should just rely on the fault tolerance and process restart stuff to get things going again if their process fails. Similarly if the Google search software hits some fatal condition once in a while, maybe it's enough to just treat it as a crashed box and let the failover mechanisms handle the problem. Of course then there's a second level system to manage the restarts that has to be very reliable, but it doesn't have to deal with much weird concocted input the way that a public-facing internet application has to. Therefore I think Russ's point stands, that we're talking about a different sort of reliability in these highly redundant systems, than in the systems Russ is describing. From newsreturns at biszumknie.de Tue Aug 28 08:36:06 2007 From: newsreturns at biszumknie.de (Andreas Lobinger) Date: Tue, 28 Aug 2007 14:36:06 +0200 Subject: expat error, help to debug? In-Reply-To: References: Message-ID: Aloha, Andreas Lobinger wrote: > Lawrence D'Oliveiro wrote: >> In message , Andreas Lobinger wrote: >>> Anyone any idea where the error is produced? ... to share my findings with you: def ex(self,context,baseid,n1,n2): print "x",context,n1,n2 return 1 The registered Handler has to return a (integer) value. Would have been nice if this had been mentioned in the documentation. Wishing a happy day, LOBI From countblabula at yahoo.com Mon Aug 6 02:50:24 2007 From: countblabula at yahoo.com (Lee Fleming) Date: Sun, 05 Aug 2007 23:50:24 -0700 Subject: Something in the function tutorial confused me. Message-ID: <1186383024.384152.87480@l70g2000hse.googlegroups.com> Hello, I have a simple question. Say you have the following function: def f(x, y = []): y.append(x) return y print f(23) # prints [23] print f(42) # prints [23, 42] As far as I understand, the default value y, an empty list, is created when the def statement evaluates. With this thought in mind, the above calls to f make sense. But this, the code that "fixes" the list accumulation confounds me: def f(x, y=None): if y is None: y = [] y.append(x) return y print f(23) # prints [23] print f(42) # prints [42] Why didn't the second call to f, f(42) return [23, 42]? As I understand it, y is only None at the beginning of f(23). Then y changes from None to 23. When f ends, doesn't y still have 23 in it, just as it did in the first function I discussed? And if y has 23 in it, won't the second call to f not execute what's in the if statement? In other words, what's going on here? How is it that y accumulates argument values between function calls in the first function, but doesn't in the second one? From ricaraoz at gmail.com Wed Aug 29 14:51:07 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 29 Aug 2007 15:51:07 -0300 Subject: copying files In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE30C@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE30C@efmailx> Message-ID: <46D5C01B.7080202@bigfoot.com> Brian McCann wrote: > Hi, > > with the code below I set a variable TEST_HOME to a path and the > variable m to a path > in my current dir. > I have a symbolic link setting m---->lib > when I run the script I get no errors and the lib dir with its 20 files > does not get copied to /v01/test_home > any help would be greatly appreciated > > --Brian > > #!/usr/bin/python > import string > import os > import sys > import errno > import shutil > import tarfile > > TEST_HOME = "/v01/test_home" > m = "./lib" > os.system("cp -r m TEST_HOME") > #os.system("tar -cvf viziant-ingestion.tar /v01/") > Sorry, meant : os.system("cp -r " + m + " " + TEST_HOME) From bscrivener42 at gmail.com Wed Aug 8 12:14:48 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Wed, 08 Aug 2007 16:14:48 -0000 Subject: 'Advanced' list comprehension? query In-Reply-To: <1186588812.006107.185570@o61g2000hsh.googlegroups.com> References: <1186588812.006107.185570@o61g2000hsh.googlegroups.com> Message-ID: <1186589688.673993.131930@q3g2000prf.googlegroups.com> On Aug 8, 11:00 am, pyscottish... at hotmail.com wrote: > Hi, > > I'm playing around with list comprehension, and I'm trying to find the > most aesthetic way to do the following: > > I have two lists: > > noShowList = ['one', 'two', 'three'] > > myList = ['item one', 'item four', 'three item'] > > I want to show all the items from 'myList' that do not contain any of > the strings in 'noShowList'. I'm still learning these myself, but I think what you want is itertools: http://docs.python.org/lib/module-itertools.html From gagsl-py2 at yahoo.com.ar Sun Aug 5 05:50:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 05 Aug 2007 06:50:06 -0300 Subject: Best way to capture output from an exec'ed (or such) script? References: <1186084086.212050.264270@q3g2000prf.googlegroups.com> <1186154066.529360.90260@q75g2000hsh.googlegroups.com> <1186264336.502429.232840@r34g2000hsd.googlegroups.com> Message-ID: En Sat, 04 Aug 2007 18:52:16 -0300, gregpinero at gmail.com escribi?: >> On Aug 2, 7:32 pm, "Gabriel Genellina" wrote:> >> If your web server is multithreaded (or you use some other way to >> process >> > many simultaneous requests) you have to be more careful - remember >> that >> > sys.stdout is global, you must find a way to distinguish between >> output >> > from different processes all going into the same collector. > > I'm actually worried about this now. Does anyone know of any > potential solutions? Anything to at least get me started? You can use threading.currentThread() to distinguish between threads, and a Lock (or RLock) to ensure the output doesn't get mixed: def write(msg): t = time.strftime("%x %X", time.localtime()) who = threading.currentThread().getName() line = "%s (%-15.15s) %s\n" % (t, who, msg) OutputDebugString("%s (%-15.15s) %s\n" % (t, who, msg)) loglock.acquire() try: with logfile() as f: f.write(line) finally: loglock.release() -- Gabriel Genellina From kcorbitt at api.com Wed Aug 15 13:20:26 2007 From: kcorbitt at api.com (Corbitt, Kyle) Date: Wed, 15 Aug 2007 10:20:26 -0700 Subject: Importing DLLs Message-ID: <7603657D433B034AB667802696450A3EAA6161@MAIL2.api.com> I'm running Linux with Python 2.3. I have a C shared object file (*.so) and I need to be able to call its functions from within Python. I have found a couple of Python modules that allow me to do this (dl, ctypes) but unfortunately I am only able to get them to return integers, even for function calls that I KNOW the library is supposed to return other types for. I need the library to be able to return doubles, 2D arrays and hopefully strings as well. I do have access to the C source code that the library was compiled from and can change it if necessary but I know even less about C than I do about Python so it'd be great if I could avoid that. Keep in mind that I am a python newbie (I only have a few weeks' experience) so the more detailed you can make your response, the better. Example code would be great. I'm sure there's a way to do this but I've been bashing my head against this problem for a couple days now and haven't made much progress. Thanks, Kyle -------------- next part -------------- An HTML attachment was scrubbed... URL: From vodela.sai at gmail.com Tue Aug 7 18:11:01 2007 From: vodela.sai at gmail.com (Rohan) Date: Tue, 07 Aug 2007 22:11:01 -0000 Subject: Email In-Reply-To: <1186194155.560881.183790@e16g2000pri.googlegroups.com> References: <1186076005.729346.327140@z24g2000prh.googlegroups.com> <46b2393f$0$27409$ba4acef3@news.orange.fr> <1186159660.264082.91830@j4g2000prf.googlegroups.com> <1186194155.560881.183790@e16g2000pri.googlegroups.com> Message-ID: <1186524661.611417.235280@e9g2000prf.googlegroups.com> On Aug 3, 7:22 pm, SMERSH009 wrote: > On Aug 3, 9:47 am,Rohan wrote: > > > > > On Aug 2, 1:06 pm, Laurent Pointal wrote: > > > >Rohanwrote: > > > > I was wondering if there could be an arrangement where a file could be > > > > attached and send as an email. > > > > For ex > > > > f = open(add.txt,w) > > > > f.write('python') > > > > f.close() > > > > > Now I would like to send an email with add.txt as an attachment, is it > > > > possible ? > > > > some one give me a pointer towards this. > > > > You can use iMailer as an example script to get parts: > > > >http://nojhan.free.fr/article.php3?id_article=22 > > > > A+ > > > > Laurent. > > > Laurent the link you gave me is in a language unknown to me if you > > have anything that expalains in english, then let me know. > > thanks > > Did you try Google translate? Here is the tiny url of the page you > wanted translatedhttp://tinyurl.com/3xlcmc Thanks everyone, I'm able to write a script which reads the file and puts it in the message. I would like to attach the file is it possible? From exarkun at divmod.com Mon Aug 6 10:32:53 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 6 Aug 2007 10:32:53 -0400 Subject: Importing * From a Package In-Reply-To: Message-ID: <20070806143253.4947.1097304571.divmod.quotient.19513@ohm> On Mon, 6 Aug 2007 10:06:51 -0400, Patrick Doyle wrote: >Reading through the Python tutorial, I got to section 6.4.1, >"Importing * From a Package", which states: > >"If __all__ is not defined, the statement from Sound.Effects import * >does not import all submodules from the package Sound.Effects into the >current namespace; ..." > >It then goes on to state: > >"[It] imports whatever names are defined in the package [including] >any submodules of the package that were explicitly loaded by previous >import statements." > >I am curious to learn the rationale for this behavior, since it just >caught me by surprise (hence the reason I was pouring over the >tutorial document in such detail :-)) There's no reliable way to differentiate between names which you defined using something other than an import statement, names you defined with an import statement with the intent of publishing them as part of your external API, and names you defined with an import statement which you only intended to use internally. So Python doesn't even try to differentiate betweem them. > >Thus far, everything in Python has seemed very intuitive to me, >however the behavior of "from package import *" baffles me. > >So I figured I'd ask -- why does Python behave this way. > >(And now, I'm going to do some code cleanup :-)) > You should probably remove all uses of "import *" from your code. It's only a very mild convenience at the time of initial use, and forever after that it is a maintenance burden, causing anyone who wants to read the code at any future point to have to dig through various layers of definitions before they can find out what any particular name is bound to, and potentially leading to bugs where names from one package accidentally obscure names from another package. Jean-Paul From ptmcg at austin.rr.com Mon Aug 27 20:06:31 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 27 Aug 2007 17:06:31 -0700 Subject: convert non-delimited to delimited In-Reply-To: <1188237563.889663.228970@o80g2000hse.googlegroups.com> References: <1188237563.889663.228970@o80g2000hse.googlegroups.com> Message-ID: <1188259591.299171.253740@r29g2000hsg.googlegroups.com> On Aug 27, 12:59 pm, RyanL wrote: > I'm a newbie! I have a non-delimited data file that I'd like to > convert to delimited. > > Example... > Line in non-delimited file: > 0139725635999992000010100534+42050-102800FM-15+1198KAIA > > Should be: > 0139,725635,99999,2000,01,01,00,53,4,+42050,-102800,FM-15,+1198,KAIA > > What is the best way to go about this? I've looked all over for > examples, help, suggestions, but have not found much. CSV module > doesn't seem to do exactly what I want. Maybe I'm just missing > something or not using the correct terminology in my searches. Any > assistance is greatly appreaciated! Using Python 2.4 I'm guessing that these lines *aren't* fixed-length, especially those signed integer fields. I used the patented Paul McGuire CrystalBall module to come up with this pyparsing rendition. (OP may adjust to suit.) -- Paul data = "0139725635999992000010100534+42050-102800FM-15+1198KAIA" """to be parsed as: 0139,725635,99999,2000,01,01,00,53,4,+42050,-102800,FM-15,+1198,KAIA""" from pyparsing import * import time def convertTimeStamp(t): t["date"] = map(int,t.date) t["time"] = map(int,t.time) return time.strftime("%Y-%m-%dT%H:%M", tuple(t.date)+tuple(t.time)+(0,0,0,0)) yearMonthDay = Word(nums,exact=4) + Word(nums,exact=2) + Word(nums,exact=2) hourMinuteSecond = Word(nums,exact=2) + Word(nums,exact=2) timestamp = ( yearMonthDay("date") + hourMinuteSecond("time") ) timestamp.setParseAction(convertTimeStamp) signedInteger = Word("+-",nums) fieldA = Word(nums,exact=4)("A") fieldB = Word(nums,exact=6)("B") fieldC = Word(nums,exact=5)("C") fieldD = timestamp("timestamp") fieldE = Word(nums)("E") fieldF = signedInteger("latitude").setParseAction(lambda t : int(t[0])/ 1000.0) fieldG = signedInteger("longitude").setParseAction(lambda t : int(t[0])/1000.0) fieldH = Combine(Word(alphas,exact=2) + "-" + Word(nums,exact=2))("H") fieldI = signedInteger("I") fieldJ = Word(alphas)("J") dataFields = fieldA + fieldB + fieldC + fieldD + fieldE + \ fieldF + fieldG + fieldH + fieldI + fieldJ res = dataFields.parseString(data) print res.dump() prints: ['0139', '725635', '99999', '2000-01-01T00:53', '4', 42.049999999999997, -102.8, 'FM-15', '+1198', 'KAIA'] - A: 0139 - B: 725635 - C: 99999 - E: 4 - H: FM-15 - I: +1198 - J: KAIA - latitude: 42.05 - longitude: -102.8 - timestamp: 2000-01-01T00:53 From evan at yelp.com Thu Aug 2 01:15:36 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 1 Aug 2007 22:15:36 -0700 Subject: calling superclass __init__ when superclass is object Message-ID: Hi list, I was reading this article: http://fuhm.net/super-harmful/ and didn't understand the comment about calling super(Foo, self).__init__() when Foo inherits only from object. Can someone on the list elaborate more on why one should do this? -- Evan Klitzke From p.lavarre at ieee.org Fri Aug 31 12:47:58 2007 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: Fri, 31 Aug 2007 09:47:58 -0700 Subject: platform system may be Windows or Microsoft since Vista Message-ID: <1188578878.264671.296440@k79g2000hse.googlegroups.com> Let's suppose you get Python for Vista Windows today from http://www.python.org/download/. Should you then conclude that the tests: if platform.system() in ('Windows', 'Microsoft'): if not (platform.system() in ('Windows', 'Microsoft')): are now exactly what you should write for that 2.5.1 Python, when you must resort to os-specific tools like DeviceIoControl, in place of the slightly simpler tests that worked before: if platform.system() == 'Windows': # Microsoft if platform.system() != 'Windows': # Microsoft ? Curiously yours, thanks in advance, P.S. Groups search assures me clp hasn't previously reviewed: platform system Windows Microsoft P.P.S. I ask because this August I rediscovered this 28 May Python uname vs. Win kernel32.getVersionEx issue indexed by Google as follows: http://mail.python.org/pipermail/patches/2007-June/022947.html ... Patches item #1726668, was opened at 2007-05-28 03:23 On Microsoft Vista platform.system() returns 'Microsoft' and platform.release() returns 'Windows' Under Microsoft Windows XP SP2 platform.system() returns 'Windows' and platform.release() returns 'XP'. This is problem was caused by a change in the output of the "ver" command. In Windows XP SP2 "ver" outputted 'Microsoft Windows XP [Version 5.1.2600]' In Microsoft Vista "ver" outputted 'Microsoft Windows [Version 6.0.6000]'. The lack of the 3rd word before version causes _syscmd_ver(...) in platform.py to return 'Microsoft' for system instead of 'Microsoft Windows'. This causes uname() to return the incorrect values. Both system() and release() call uname(). ... From greg at cosc.canterbury.ac.nz Wed Aug 8 20:31:57 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 09 Aug 2007 12:31:57 +1200 Subject: Issues of state In-Reply-To: <7x7io6dx3p.fsf@ruckus.brouhaha.com> References: <7x3aywr4tc.fsf@ruckus.brouhaha.com> <7x8x8mpn37.fsf@ruckus.brouhaha.com> <5htpcrF3lqmrnU1@mid.individual.net> <7x7io6dx3p.fsf@ruckus.brouhaha.com> Message-ID: <5hv5r0F3m4v9cU1@mid.individual.net> Paul Rubin wrote: > The high bandwidth and persistence is not needed for an http > connection, which just gets a form submission once in a while. Bandwidth isn't really the main issue. The point is that a lot of state is kept on both ends, making it much easier to implement a rich user interface. In fact, the more state is kept, the *less* bandwidth you need, because communication can make use of shared context to compress the messages. -- Greg From sjmachin at lexicon.net Thu Aug 2 19:22:59 2007 From: sjmachin at lexicon.net (John Machin) Date: Thu, 02 Aug 2007 16:22:59 -0700 Subject: (no) fast boolean evaluation ? In-Reply-To: References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> Message-ID: <1186096979.397596.36640@e16g2000pri.googlegroups.com> On Aug 3, 8:55 am, Ian Clark wrote: > Stef Mientki wrote: > > hello, > > > I discovered that boolean evaluation in Python is done "fast" > > (as soon as the condition is ok, the rest of the expression is ignored). > > > Is this standard behavior or is there a compiler switch to turn it on/off ? > > > thanks, > > Stef Mientki > > It's called short circuit evaluation and as far as I know it's standard > in most all languages. This only occurs if a conditional evaluates to > True and the only other operators that still need to be evaluated are > 'or's or the condition evaluates to False and all the other operators > are 'and's. The reason is those other operators will never change the > outcome: True or'd with any number of False's will still be True and > False and'ed to any number of Trues will still be False. > > My question would be why would you *not* want this? > > Why? Perhaps under some compound condition like this: (you_are_confused and/or function_returns_bool_but_has__side_effects()) From ricaraoz at gmail.com Fri Aug 31 06:38:43 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 31 Aug 2007 07:38:43 -0300 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188537516.622167.115080@z24g2000prh.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> <1188537516.622167.115080@z24g2000prh.googlegroups.com> Message-ID: <46D7EFB3.1030203@bigfoot.com> Russ wrote: >> I've always wondered... Are the compilers (or interpreters), which take >> these programs to machine code, also formally proven correct? > > No, they are not formally proven correct (too complicated for that), > but I believe they are certified to a higher level than your "typical" > compiler. I think that Ada compilers used for certain safety-critical > applications must meet higher standards than, say, GNU Ada, for > example. > > And the OS >> in which those programs operate, are they also formally proven correct? > > Same as above, if I am not mistaken. > >> And the hardware, microprocessor, electric supply, etc. are they also >> 'proven correct'? > > I think the microprocessors used for flight control, for example, are > certified to a higher level than standard microprocessors. > > How would you prove a power supply to be "correct"? I'm sure they meet > higher reliability standards too. > > In that case why don't we just 'certify to a higher level' the programs and get done with this formal proofs? We should remember that the level of security of a 'System' is the same as the level of security of it's weakest component, so either we formally prove all those other very important components (OS gets MUCH more use than the program (the program uses it for almost every other action)) or get done with the whole fuss. From joesox at gmail.com Sun Aug 19 23:00:07 2007 From: joesox at gmail.com (JoeSox) Date: Sun, 19 Aug 2007 20:00:07 -0700 Subject: How do I call anonymous classes from imported modules? Message-ID: <785694cd0708192000y618ecd54xcd960730a9229f4c@mail.gmail.com> I am importing 3rd party modules via a plugin script. I wish to iterate thru the modules and call a common method like .do_foobar() or something with all the imports. But I can't figure out how to do something like below without knowing the class name before hand. Is there a builtin that helps call classes anonymously? (Calling example.do_foobar() works because I manually enter the classes' name) >>> a=MyApp() >>> sensorsList = [] >>> for snames in a.pluginsDict["sensorsplugins"]: sensorsList.append(__import__(snames)) >>> sensorsList[0].example.do_foobar() but I need something like >>> sensorsList[0][0].do_foobar() because I will not know the plugin class names. -- Later, Joe From aleax at mac.com Sat Aug 11 01:10:57 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 10 Aug 2007 22:10:57 -0700 Subject: Help with Dictionaries and Classes requested please. References: <46bacae3$0$89254$7b0f0fd3@mistral.news.newnet.co.uk> <46bacf1b$0$54289$7b0f0fd3@mistral.news.newnet.co.uk> <87ejic6dkw.fsf@benfinney.id.au> <46bb19e2$0$9835$7b0f0fd3@mistral.news.newnet.co.uk> <59o*53SRr@news.chiark.greenend.org.uk> Message-ID: <1i2nhi1.1ks27gfhzvw3vN%aleax@mac.com> Sion Arrowsmith wrote: > special_dragonfly wrote: > > if key in FieldsDictionary: > > FieldsDictionary[key].append(FieldClass(*line.split(","))) > > else: > > FieldsDictionary[key]=[FieldClass(*line.split(","))] > > These four lines can be replaced by: > > FieldsDictionary.setdefault(key, []).append(FieldClass(*line.split(","))) Even better might be to let FieldsDictionary be an instance of collections.defaultdict(list) [[assuming Python 2.5 is in use]], in which case the simpler FieldsDictionary[key].append(FieldClass(*line.split(","))) will Just Work. setdefault was a valiant attempt at fixing this problem, but defaultdict is better. Alex From gagsl-py2 at yahoo.com.ar Mon Aug 20 04:39:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 20 Aug 2007 05:39:36 -0300 Subject: swapping References: Message-ID: En Sat, 18 Aug 2007 02:58:23 -0300, Beema shafreen escribi?: > result: > klp5 bub1 > > apn1 apn2 > > but i have do the same for the revere ,to check the result like this for > eg: > apn2 apn1 > what is the concept to do this I don't understand exactly what you want to do. If you want to transform "apn1 apn2" into "apn2 apn1", try this: col1, col2 = line.split() print col2," ",col1 -- Gabriel Genellina From fernandofariajunior at gmail.com Thu Aug 30 17:21:14 2007 From: fernandofariajunior at gmail.com (fernando) Date: Thu, 30 Aug 2007 21:21:14 -0000 Subject: Registering a python function in C Message-ID: <1188508874.879215.319400@i13g2000prf.googlegroups.com> Could someone post an example on how to register a python function as a callback in a C function? It expects a pointer to PyObject... how do I expose that? Basically, the signature of the function is foo(PyObject* obj), where obj is the callback function... It's not exactly extending or embedding, I've looked at those examples but they don't really show how to do this... Thanks for the help! From hejibo at gmail.com Tue Aug 28 12:55:42 2007 From: hejibo at gmail.com (He Jibo) Date: Tue, 28 Aug 2007 16:55:42 -0000 Subject: help needed on PyLink Message-ID: <1188320142.294269.316100@r29g2000hsg.googlegroups.com> Hi, Everyone, Is there anybody who know how to programming for eye-tracker with PyLink? I just started learning it and need some help. Your help will be appreciated from the bottom of my heart. My email is : hejibo at gmail.com, and my MSN is jibohepku at hotmail.com From paul.heslop at blueyonder.co.uk Wed Aug 15 10:38:35 2007 From: paul.heslop at blueyonder.co.uk (Paul Heslop) Date: Wed, 15 Aug 2007 14:38:35 GMT Subject: Free Air Conditioners!!!!! References: <1187188126.751546.129520@w3g2000hsg.googlegroups.com> Message-ID: <46C30FDE.B58264B9@blueyonder.co.uk> Lepi Duja wrote: > > Air conditioning > posting this crap under different names doesn't make it any more on topic or make it any more likely we'll follow the link -- Paul (We won't die of devotion) ------------------------------------------------------- Stop and Look http://www.geocities.com/dreamst8me/ From naga86 at gmail.com Thu Aug 23 00:39:20 2007 From: naga86 at gmail.com (Nagarajan) Date: Wed, 22 Aug 2007 21:39:20 -0700 Subject: Server-side scripting in python In-Reply-To: <0k2up4-lla.ln1@lairds.us> References: <1187614732.519547.296020@j4g2000prf.googlegroups.com> <1187755436.972359.293360@i13g2000prf.googlegroups.com> <0k2up4-lla.ln1@lairds.us> Message-ID: <1187843960.922925.127990@i13g2000prf.googlegroups.com> On Aug 22, 8:50 pm, cla... at lairds.us (Cameron Laird) wrote: > In article <1187755436.972359.293... at i13g2000prf.googlegroups.com>,Nagarajan wrote: > > >> . > >> . > >> . > >Let me phrase my problem in a finer way. > >I have done simple projects inpython. > >I wanted to explore web programming facet ofpython. The problem at my > >hand is to develop an email web client. I've developed web > >applications in PHP. I need to evaluatepython-based web frameworks to > >make a smart choice of the web framework or a language like PHP, Perl > >based on performance predominantly. Do I make myself clear now? > > . > . > . > In general, network latency is likely to dominate the performance > of a hobbyist-scale Webmail application coded in PHP, Perl, orPython; to base your decision predominantly on performance is ... > well, it's not what I'd recommend. You might as well flip a coin. > > Flipping a coin isn't such a bad idea; it's possible to write good > applications with any of PHP, Perl, andPython. Even if you restrict > yourself toPython, you can flip another coin and choose almost any > of its Web frameworks. > > I salute your intent to choose a Web framework wisely. In the ab- > sence of still more detail about your situation, requirements, > constraints, ..., I don't know how to do so beyond what I've already > written. Django is intuitive and handy. I think I would go with that. Any suggestions? Thanks. From http Fri Aug 24 03:09:55 2007 From: http (Paul Rubin) Date: 24 Aug 2007 00:09:55 -0700 Subject: Co-developers wanted: document markup language References: <87odgyyx9u.fsf@wilson.homeunix.com> <87tzqpew22.fsf@wilson.homeunix.com> <87tzqp77my.fsf@wilson.homeunix.com> Message-ID: <7xy7g1if24.fsf@ruckus.brouhaha.com> Torsten Bronger writes: > The differences to LaTeX are explained comprehensively on the > webpage, and actually LaTeX is the real competitor rather than > reStructuredText. TeX/LateX have been around forever and are well established standards, as awful as they are. Why do we want ANOTHER markup language? We need fewer, not more. From fakeaddress at nowhere.org Fri Aug 17 05:56:10 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 17 Aug 2007 09:56:10 GMT Subject: python socket usage In-Reply-To: References: <1187250839.541105.60900@r29g2000hsg.googlegroups.com> <46C408D6.8000907@islandtraining.com> Message-ID: <_gexi.33777$2v1.6997@newssvr14.news.prodigy.net> O?uz Yar?mtepe wrote: > As i read pickle module is Python-spesific. I need to talk with a Java > application and get the infortion that it will send. What i do right now is > listening a socket and reding the string that is sent by the java > application. So the java application is sending a string and i am reading and > parsing it and getting the related infortion i need. A more professional way > may be the reading the object itself. Is it possible to get the array for ex. > object that is sent from the Java application with sockets? No. Sockets send and receive byte. Any transfer of higher-level object values requires the sender to encode the values into bytes, and the receiver to parse the bytes to construct an object; even then the result is a value copy, not the object itself. For many kinds of objects, there are libraries available to do the encoding and parsing. If you need reference semantics, there are "object request brokers". Say more about your problem, and there's a good chance you'll get more useful answers. -- --Bryan From ca.allen at gmail.com Fri Aug 3 14:59:46 2007 From: ca.allen at gmail.com (Chris Allen) Date: Fri, 03 Aug 2007 11:59:46 -0700 Subject: Global package variable, is it possible? In-Reply-To: <1186166873.485756.290100@i13g2000prf.googlegroups.com> References: <1186160415.065108.139160@e9g2000prf.googlegroups.com> <46b36b31$0$10622$4fafbaef@reader2.news.tin.it> <1186166873.485756.290100@i13g2000prf.googlegroups.com> Message-ID: <1186167586.890782.298540@j4g2000prf.googlegroups.com> > Hmm. So maybe something like this makes sense: > > __init__py: > ####################### > _default_cfg_file = 'config.conf' > > import configure > def loadcfg(filename): > configure.cfgfile = filename > try: > reload(pkg_module1) > reload(pkg_module2) > except NameError: > pass > cfg = loadcfg(_default_cfg_file) > > import pkg_module1 > import pkg_module2 > # EOF > > confgure.py: > ####################### > cfgfile = None > def loadcfg() > global cfgfile > if not cfgfile: > return None > file = open(cfgfile) > cfg = SafeConfigParser() > cfg.readfp(file) > return cfg > # EOF > > pkg_module1: > ####################### > import configure > cfg = configure.loadcfg() > # EOF > > It's a little bit convoluted, but I think it solves most of my > gripes. Anybody have a better idea of how to do this? Thanks again > Fabio. Ugh... I wasn't thinking... Of course this won't work either for the same reasons above. changing configure.cfgfile from __init__.py will have no effect on the separate configure instances loaded in other modules. I still don't understand why python's __init__.py namespace isn't global to all modules in the package. Is this a feature, to prevent sloppy code? I think there are certain instances when it would make sense. From stephane at harobed.org Sun Aug 5 17:43:21 2007 From: stephane at harobed.org (KLEIN Stephane) Date: Sun, 5 Aug 2007 21:43:21 +0000 (UTC) Subject: Question about pychecker and pylint Message-ID: Hi, I wonder if pychecker projet is dead ? On pychecker home page (http://pychecker.sourceforge.net/), last version date from February 3, 2006 and their mailist contain spam messages only. Other tools like pychecker is pylint at (http://www.logilab.org/project/eid/857). This is a great tools and it's still active. However, it has issue : its web site, it is very incomprehensible. Do you have other pylint web site ? Thanks for your information. Stephane From cappy2112 at gmail.com Sat Aug 4 16:20:35 2007 From: cappy2112 at gmail.com (Cappy2112) Date: Sat, 04 Aug 2007 20:20:35 -0000 Subject: wxpython with python 2.5 In-Reply-To: References: <4a7f84ac0708020924v73dee05eq76d10507e3c2cad5@mail.gmail.com> Message-ID: <1186258835.749551.94100@q3g2000prf.googlegroups.com> On Aug 2, 9:34 am, "Chris Mellon" wrote: > On 8/2/07, G wrote: > > Any help in getting wxpython to run in 2.5 would be greatly appreciated. > Have you tried posting a request for help on the wx list? From ndbecker2 at gmail.com Thu Aug 9 08:10:51 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 09 Aug 2007 08:10:51 -0400 Subject: mmm-mode, python-mode and doctest-mode? References: <46BAA8D6.1050402@gradient.cis.upenn.edu> Message-ID: Edward Loper wrote: >> Anyone testing on xemacs? I tried it, and C-c C-c sent xemacs into an >> infinite loop (apparantly). > > It works fine for me in XEmacs 21.4 (patch 17) (i386-debian-linux, > Mule). If you could answer a few questions, it might help me track down > the problem: > > - What version of xemacs are you running? > - What version of doctest-mode are you running (0.4 or 0.5)? > - Are you using doctest-mode by itself, or in combination with another > mode (via mmm-mode)? > - Does pressing control-g (possibly repeatedly) cause it to become > unstuck? > - Does it always freeze when you hit C-c C-c? Or does it depend on the > contents of the buffer? Does it freeze if you run it in an empty > buffer? > > You could try changing the value of doctest-python-command, to see if > that helps -- "M-x customize-variable doctest-python-command". Set it > to the full path to a Python interpreter. > > Thanks, > -Edward Value: "21.5 (beta28) \"fuki\" XEmacs Lucid" I tested with 'hello.py', which is attached. Load hello.py. M-x mmm-mode. Then move cursor to the highlighted test region (the triple quoted doctest). C-h k C-c C-c says 'doctest-execute'. good. Now C-c C-c sends xemacs into an infinite loop. hello.py--------------- import math ''' >>> print 2 + 2 4 ''' def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test() From daniels at dsl-only.net Thu Aug 23 08:40:22 2007 From: daniels at dsl-only.net (Scott David Daniels) Date: Thu, 23 Aug 2007 05:40:22 -0700 Subject: beginner, idiomatic python In-Reply-To: <13cqlqbbpn0dmea@corp.supernews.com> References: <13cqlqbbpn0dmea@corp.supernews.com> Message-ID: <13cr00ujte4qs09@corp.supernews.com> bambam wrote: > Would someone like to suggest a replacement for this? It works ok, > but it doesn't look like any of the other code: > > tempList = ['1','2','3','4','5','6','7','8'] > sampleList=[] > for port in tempList: > pagefound = False > for i in range(self.parent.GetPageCount()): > page=self.parent.GetPage(i) > if hasattr(page, "port"): > if page.port == int(port): > pagefound=True > if not pagefound: > sampleList.append(port) > > Thanks! > > Look at good questions. This is a _very_ underspecified question. One stab at mindreading: def ported_pages(self): for i in range(self.parent.GetPageCount()): if hasattr(page, 'port'): yield page ... tempList = ['1','2','3','4','5','6','7','8'] missing = dict((int(v), v) for v in tempList) for page in self.ported_pages(): if page.port in missing: missing.pop(page.port) if not missing: break sampleList = missing.values() ... -Scott David Daniels From stefan.behnel-n05pAM at web.de Fri Aug 17 12:13:24 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 17 Aug 2007 18:13:24 +0200 Subject: Can python threads take advantage of use dual core ? In-Reply-To: <5ilvg4F3pqv6aU1@mid.uni-berlin.de> References: <1187366443.621295.97020@e9g2000prf.googlegroups.com> <5ilvg4F3pqv6aU1@mid.uni-berlin.de> Message-ID: <46c5c924$0$7688$9b4e6d93@newsspool2.arcor-online.net> Diez B. Roggisch wrote: > nikhilketkar schrieb: >> What are the implications of the Global Interpreter Lock in Python ? >> Does this mean that Python threads cannot exploit a dual core >> processor and the only advantage of using threads is in that >> computation and IO-bound operations can continue in parallel ? > > > Essentially, yes. That is unless the computation is done in C-code which > released the GIL beforehand. Which virtually all computation-intensive extensions do. Also, note the processing package, which allows you to use a separate process more or less like a thread, thus avoiding GIL issues completely. Stefan From koje_je_ono_bilo_pitanje at bla.bla Tue Aug 28 14:47:27 2007 From: koje_je_ono_bilo_pitanje at bla.bla (Boris Ozegovic) Date: Tue, 28 Aug 2007 20:47:27 +0200 Subject: localhost, ?! References: <46d46d38$0$37200$4fafbaef@reader3.news.tin.it> Message-ID: Fabio Z Tessitore wrote: > I think to have http://localhost working you need a web server (like > apache). maybe you have it at your home. I do have Apache. You can see that urllib, older module, works correctly. From horpner at yahoo.com Tue Aug 14 09:32:40 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 14 Aug 2007 13:32:40 GMT Subject: LEGB rule, totally confused ... References: Message-ID: On 2007-08-14, stef mientki wrote: > I've thought many times I finally understood the import / > namespace rules, but again I'm totally lost :-( > > This is my library file > > # Module lib_test.py > > X = 1 > > def Init(): > global X > X = 3 > print 'Init', X > > def Run (): > print X <=== UnboundLocalError: local variable > 'X' referenced before assignment > X = X + 1 > print ' Run', X >From _Python Language Reference Manual_ see: '4.1 Naming and Binding' and '6.13 The global statement'. If a name is bound [assigned] in a block, it is a local variable of that block. ... The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global. Since your Init and Run functions both assign (bind) a value to X, X is assumed to be a local variable unless you say otherwise with a global statement. Note that the global statement in Init applies only in Init's code block. Run must have it's own 'global X' statement, if applicable. -- Neil Cerutti From michael at jedimindworks.com Mon Aug 20 02:14:08 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 19 Aug 2007 23:14:08 -0700 Subject: popen4 not returning output In-Reply-To: <1187582318.054450.76960@z24g2000prh.googlegroups.com> References: <1187582318.054450.76960@z24g2000prh.googlegroups.com> Message-ID: On Aug 19, 2007, at 8:58 PM, hortitude at gmail.com wrote: > I am trying to run the following script: > > > #!/usr/bin/python > > import popen2 > > commandToRun = """scp scp_trial.py user at host:/targetDirectory""" > #commandToRun = "ls" > print commandToRun > p_out, p_in = popen2.popen4 (commandToRun) > > theOut = p_out.readlines () > print theOut > > > When I run this command with the "ls" command I see the output. > When I run this with the scp command I do not see the output of my > command -- however the file is successfully transfered. How can I see > the output? > scp will not produce output on stdout or stderr if stdout/stderr is redirected. I assume it uses an ioctl with TCGETA to determine the terminal characteristics of the device connected to stdout, and get either an EINVAL (for a pipe) or ENOTTY (for a file) failure when no terminal is attached. You can test whether it works the same on your system by running your scp from the command line and redirecting the output: scp scp_trial.py user at host:/targetDirectory >scp.stdout 2>scp.stderr Both files will exist (the shell does this before starting the scp command), but will (I think) be empty. hope this helps, Michael --- The Rules of Optimization are simple. Rule 1: Don't do it. Rule 2 (for experts only): Don't do it yet. -Michael A. Jackson From miki.tebeka at gmail.com Sat Aug 4 02:04:38 2007 From: miki.tebeka at gmail.com (Miki) Date: Sat, 04 Aug 2007 06:04:38 -0000 Subject: Website data-mining. In-Reply-To: References: Message-ID: <1186207478.055593.107110@z24g2000prh.googlegroups.com> Hello, > I'm using Python for the first time to make a plug-in for Firefox. > The goal of this plug-in is to take the source code from a website > and use the metadata and body text for different kinds of analysis. > My question is: How can I retrieve data from a website? I'm not even > sure if this is possible through Python. Any help? Have a look at http://www.myinterestingfiles.com/2007/03/playboy-germany-ads.html for getting the data and at http://www.crummy.com/software/BeautifulSoup/ for handling it. HTH. -- Miki Tebeka http://pythonwise.blogspot.com From tamim.shahriar at gmail.com Thu Aug 23 12:56:35 2007 From: tamim.shahriar at gmail.com (subeen) Date: Thu, 23 Aug 2007 16:56:35 -0000 Subject: C# and Python In-Reply-To: <46cac5ba$1_1@news.chariot.net.au> References: <1187690505.903506.79690@d55g2000hsg.googlegroups.com> <46cac5ba$1_1@news.chariot.net.au> Message-ID: <1187888195.101930.101050@r23g2000prd.googlegroups.com> On Aug 21, 5:00 pm, Bikal KC wrote: > subeenwrote: > > When the user clicks Quick Sort button, the quicksort.py will be > > called and it will sort the numbers. > > One way to do this: > In your C# app, have the mouse click event handler call python > interpreter "/path/to/python /path/to/quicksort.py". Make quicksort.py > write to a file the result. After the quicksort.py finishes, read the > file from your normal C# app. > > Cheers. Hi, what's the C# function to call python interpreter? regards, Subeen. From robert.kern at gmail.com Wed Aug 22 16:46:34 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 22 Aug 2007 15:46:34 -0500 Subject: What Are These Import/From Statements about? In-Reply-To: References: Message-ID: W. Watson wrote: > While that's an interesting link, I was thinking of the named items like: Okay, sorry. > Numeric, (this one I know about.) > Image > ImageChops > ImageTk The Image* modules are from PIL. http://www.pythonware.com/products/pil/ > time http://docs.python.org/lib/module-time.html > binascii http://docs.python.org/lib/module-binascii.html > tkMessageBox > tkSimpleDialog These are also from the standard library. See your lib-tk/ directory. http://effbot.org/tkinterbook/tkinter-standard-dialogs.htm http://effbot.org/tkinterbook/tkinter-dialog-windows.htm > ... > For example, what is the Image module? MakeQTE? MakeQTE is new to me. Google only brings up this thread. > ospath? os.path. It's a sub-module of the standard os module. http://docs.python.org/lib/module-os.path.html socket, struct, glob, bisect, and datetime are standard library modules. http://docs.python.org/modindex.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From __peter__ at web.de Thu Aug 23 07:57:30 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 23 Aug 2007 13:57:30 +0200 Subject: sentance containg the string or symbol =?UTF-8?B?zqk=?= References: <1187868007.012689.224290@z24g2000prh.googlegroups.com> Message-ID: Oops, forgot to switch the encoding to utf-8. >>> print u"? and also \N{GREEK CAPITAL LETTER LAMDA}" ? and also ? Peter From fabioztessitore at libero.it Wed Aug 15 13:56:42 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 15 Aug 2007 17:56:42 GMT Subject: All names in the current module References: <87d4xowymq.fsf@wilson.homeunix.com> <1i2whvw.1qje42i1bh18bkN%raims@dot.com> Message-ID: <46c33e5a$0$36450$4fafbaef@reader5.news.tin.it> Il Wed, 15 Aug 2007 19:01:17 +0200, Lawrence Oluyede ha scritto: > Torsten Bronger wrote: >> How can I get a list with all classes defined in the current module? >> Thank you! > > rhymes at groove ~ % cat > t.py > class A: pass > > rhymes at groove ~ % python > Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple > Computer, Inc. build 5367)] on darwin Type "help", "copyright", > "credits" or "license" for more information. >>>> import t >>>> print dir(t) > ['A', '__builtins__', '__doc__', '__file__', '__name__'] > > Now you have the list of names. To find out if they are actual classes > or not you can do this: to get names' list you can simply call globals() bye From db3l.net at gmail.com Thu Aug 30 15:43:41 2007 From: db3l.net at gmail.com (David Bolen) Date: Thu, 30 Aug 2007 15:43:41 -0400 Subject: Creating a multi-tier client/server application References: <1188360460.838635.186930@w3g2000hsg.googlegroups.com> <7xbqcqhqbw.fsf@ruckus.brouhaha.com> <46d54ed8$0$429$426a34cc@news.free.fr> <1188393925.007952.313110@r29g2000hsg.googlegroups.com> <7xy7ft4fqg.fsf@ruckus.brouhaha.com> <1188479584.073309.297770@x40g2000prg.googlegroups.com> <1188498543.184255.213940@i13g2000prf.googlegroups.com> Message-ID: Jeff writes: > David: Sounds like a pretty interesting app. Thanks for the in-depth > description. I went and checked out Twisted PB, and it seems > awesome. I may very well go with that. How was writing code with > it? I may also end up using py2app, but I'm also going to have to > support Windows, (p2exe, then), and possibly Linux. Well, maybe not > Linux, but I'll probably be doing most of the development in Linux, so > I guess that counts. I find PB very easy, but it's important to first become familiar with Twisted (in particular Deferred's), which can have a steep, but worth it IMO, learning curve. PB is a thin, transparent system, so it doesn't try to hide the fact that you are working remotely. Being thin, there also isn't very much to have to learn. For packaging, you don't have to use a single system if you are multi-platform. Your codebase can be common, and just have separate setup files using py2app on OS X and py2exe on Windows. A makefile or equivalent can handle final distribution packaging (e.g,. hdiutil for dmg on OS X, Inno Setup, NSIS, etc... on Windows). You'll spend some platform-specific time getting the initial stuff setup, but then new builds should be easy. For Linux, depending on the level of your users you can either just directly ship something like eggs (generated through a setup) or look into pyInstaller, which was the old Installer package that also supports single-exe generation for Linux. pyInstaller also does Windows, so if you have to support them both you could try using pyInstaller rather than both it and py2exe. But if you're just developing in Linux, final packaging probably isn't very important. -- David From avishorp at yahoo.com Tue Aug 21 18:09:26 2007 From: avishorp at yahoo.com (avishay) Date: Tue, 21 Aug 2007 15:09:26 -0700 Subject: Chaining programs with pipe Message-ID: <1187734166.384152.178040@o80g2000hse.googlegroups.com> Hello I'm trying to chain two programs with a pipe (the output of one feeding the input of the other). I managed to capture the output and feeding the input of each program independently with popen, but how do I tie them together? Is there a solution that works equally on all platforms? Thanks, Avishay From grante at visi.com Fri Aug 24 10:37:28 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 24 Aug 2007 14:37:28 -0000 Subject: Socket recv(1) seems to block instead of returning end of file. References: <13cr4u8mimniub4@corp.supernews.com> Message-ID: <13ctr98fjaobva8@corp.supernews.com> On 2007-08-24, Bryan Olson wrote: > Grant Edwards wrote: > [...] >> import socket,random >> >> HOST = '' # Symbolic name meaning the local host >> PORT = 8765 # Arbitrary non-privileged port >> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >> s.connect((HOST, PORT)) > > Actually the empty string passed for the host means INADDR_ANY, You're correct. I copied that code from the server example on the Python socket module doc page, and forgot to change the host. http://docs.python.org/lib/socket-example.html > which does not really make sense for the client. On my Win-XP > system, the client fails with > > socket.error: (10049, "Can't assign requested address") It's interesting that it works on Linux. > For the loop-back adapter, 'localhost' or '127.0.0.1' should > work. Yup. -- Grant Edwards grante Yow! YOU PICKED KARL at MALDEN'S NOSE!! visi.com From steveo at syslang.net Wed Aug 22 13:54:01 2007 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 22 Aug 2007 13:54:01 -0400 (EDT) Subject: Problems with dynamic function creation. Message-ID: I have some functions I need to create at runtime. The way I'm creating them is by calling a function which returns the string representation. Then I exec the string. Here's the code I use to gen the strings: mkfactfns.py ----------- import new def mkfactfns( cname ): def auxgen( name, params, dd ): v1 = ( """def mk%s%sdict(%s):\n"""%(name, cname, params) + """ print 'In mk%s%sdict'\n"""%(name, cname) + """ return %s\n"""%dd) v2 = ( """def mk%s%s(%s):\n"""%(name,cname,params) + """ print 'Calling mk%s%s'\n"""%(name,cname) + """ return %s%s( mk%s%sdict(%s) )\n"""%(name,cname, name, cname, params)) return v1, v2 return auxgen This is the caller of mkfactfns -------------------------------- import mkfactfns fbase = "ABC" # Factory BASEname auxfactgen = mkfactfns.mkfactfns(fbase) Then in the same module, I call auxfactgen via mkfactfns.AuxFnDefs( auxfndata, auxfactgen, globals(), "ABC" ) def AuxFnDefs(auxfndata, fnmaker, globs, cname ): dictsuff = ('dict','') for ii in auxfndata: rr = fnmaker( *ii ) for jj in range( 2 ): co = compile (rr[jj], '', 'exec') exec co name = 'mk%s%s%s'%(ii[0],cname,dictsuff[jj]) print 'co = ', co, 'name = ', name nfunc = new.function( co, globs, name ) print 'Just added mk%s%s%s'%(ii[0],cname,dictsuff[jj]) globs['mk%s%s%s'%(ii[0],cname,dictsuff[jj])] = nfunc print 'g = ', globs['mk%s%s%s'%(ii[0],cname,dictsuff[jj])] Everything works just fine (that I know of) except that when I run a function that takes 1 arg, I get the following message: TypeError: ?() takes no arguments (1 given) even though I know that I am passing one arg. I must be doing something wrong, I just don't know what. :-( -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From gggg.iiiii at gmail.com Thu Aug 2 12:24:53 2007 From: gggg.iiiii at gmail.com (G) Date: Thu, 2 Aug 2007 12:24:53 -0400 Subject: wxpython with python 2.5 Message-ID: <4a7f84ac0708020924v73dee05eq76d10507e3c2cad5@mail.gmail.com> Hello, I am trying to get wxpython to run with python 2.5 without any success. wx works prefectly in python 2.4. below is the error code i get when i try to run the code. File "demo.py", line 3, in import Main File "/tmp/wxPython/Main.py", line 32, in import wx # This module uses the new wx namespace ImportError: No module named wx Any help in getting wxpython to run in 2.5 would be greatly appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From vodela.sai at gmail.com Sun Aug 12 22:05:51 2007 From: vodela.sai at gmail.com (Rohan) Date: Mon, 13 Aug 2007 02:05:51 -0000 Subject: Colored text Message-ID: <1186970751.435970.189900@q3g2000prf.googlegroups.com> Hello, Can some one tell me how do I get colored text. Say when I want to write something in a text file , how do I get it colored. From tjreedy at udel.edu Mon Aug 20 23:37:00 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 20 Aug 2007 23:37:00 -0400 Subject: GeneratorExit should derive from BaseException, not Exception References: <46CA0EFE.6020103@imvu.com> Message-ID: "Chad Austin" wrote in message news:46CA0EFE.6020103 at imvu.com... || try: | result = yield chatGateway.checkForInvite({'userId': userId}) | logger.info('checkForInvite2 returned %s', result) would not except GeneratorExit: solve your problem? | except Exception: Such catchalls are known to be prone to catch too much and are therefore not encouraged ;-). As in 'use at your own risk'. Guido encourages specific catches just for the reasons you give here. | logger.exception('checkForInvite2 failed') | result = None | # ... | yield Sleep(10) | | This is real code that I wrote in the last week. The key portion is the | try: except: Basically, there are many reasons the checkForInvite2 call | can fail. Maybe a socket.error (connection timeout), maybe some kind of | httplib error, maybe an xmlrpclib.ProtocolError... I actually don't | care how it fails. If it fails at all, then sleep for a while and try | again. All fine and good. ... | So, my proposal is that GeneratorExit derive from BaseException instead | of Exception. | | p.s. Should I have sent this mail to python-dev directly? Does what I'm | saying make sense? Does this kind of thing need a PEP? There was a *long* discussion of the current 2.5 exception hierarchy on pydev. Search either python.org's or gmane's archive if you want to pursue this. But I expect the people involved would say much the same as above. Terry Jan Reedy From arkanes at gmail.com Wed Aug 8 10:09:46 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 8 Aug 2007 09:09:46 -0500 Subject: twisted - locking threads when deferToThread is used In-Reply-To: <46B99CCB.1070304@iptel.org> References: <46B99CCB.1070304@iptel.org> Message-ID: <4866bea60708080709v797c5a67w158f6f988ef5c304@mail.gmail.com> On 8/8/07, Ladislav Andel wrote: > Hi, > I'm writing an application which will be periodically testing servers. > I will have a global list of these servers(domain names) and need to do > few tasks. > 1) DNS checks - I will use asynchronous twisted-names for it > - in case there is a difference comparing to the list it should update > the list(then also in DB) > 2) ICMP pings - should be also possible to do it asynchronously > 3) Blocking function which will be pinging with SIP requests > - here I will use function deferToThread to make it non-blocking. > > Questions: > 1) How do I lock each thread when writing to a global list in twisted? > 2) How will I put together all three results mentioned above in the > global list > - is it by using function callLater ? > 3) Could you help me with a rough skeleton of this application, please? > > Thank you, > Lada > deferToThread returns the result of the passed function in a Deferred. Callbacks and errbacks will be run in the main event loop, so you don't need to worry about thread safety of the callbacks, just of the function itself. The basic model would look something like this: def querySIP(what): return sip.query(what) #native, *threadsafe*, blocking call sipquery = reactor.deferToThread(querySIP, what) sipquery.addCallback(lambda result: sip_results.append(result)) sipquery.addErrback(log.err) From chris at shenton.org Thu Aug 23 14:58:16 2007 From: chris at shenton.org (Chris Shenton) Date: Thu, 23 Aug 2007 14:58:16 -0400 Subject: python setup.py: how to override a setup.cfg value ? Message-ID: <86odgyxelz.fsf@PECTOPAH.shenton.org> I'm building python-ldap and need to change values of library and include paths that are in the setup.cfg file. This is an automated build (using "buildit") so I'd prefer not to have edit the .cfg by hand, with sed, or even with buildit's Substitute(). I'd like to be able to do something like I'd do with "make", specify a value on the command line like: make -Dprefix=/usr/local or in this case python setup.py -Dlibs="ldap lber" build [Does NOT work] I cannot see how to do this from the --help or from googling. The closest I've gotten is to do: python setup.py setopt --command=_ldap --option=libs --set-value="ldap lber" but that overwrites the python.cfg, a bit rude it seems to me. Am I missing something? is there a way to override a .cfg value on the command line while running a setup.py command like "build" or "install"? Thanks. From patelkundan at gmail.com Sat Aug 4 08:19:46 2007 From: patelkundan at gmail.com (Sonu) Date: Sat, 04 Aug 2007 05:19:46 -0700 Subject: how to run os.execv() to run command pslq dbname < gen.command Message-ID: <1186229986.707259.323130@19g2000hsx.googlegroups.com> hello all , i need to run psql from my py file,, for that i am using : os.execv(path for psql ,['psql dbname < gen.command']) but its not working .......... the command wht i want to run from this py file is :>>>psql dbname < gen.command where gen.command file contain some command to create csv file from database \o temp.csv \a \f , select * from temp if u have any idea plz help me,, From deets at nospam.web.de Thu Aug 16 12:25:18 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 16 Aug 2007 18:25:18 +0200 Subject: Who told str() to round my int()'s!!! In-Reply-To: References: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> <9qmvi.47364$s5.1537219@phobos.telenet-ops.be> <3ZudnUuJ68lcxl7bnZ2dnUVZ_t_inZ2d@comcast.com> Message-ID: <5ijc3lF3ne7ddU1@mid.uni-berlin.de> John Nagle schrieb: > A.T.Hofkamp wrote: >> On 2007-08-15, Larry Bates wrote: >> >>> or the mildy >>> amusing "how do I write bytes not characters to a file" questions at >>> least once >>> a week on this forum. > > Actually, that's a reasonable question, and one that Python didn't do > quite right. > > Remember, in the beginning, Python had only ASCII strings, which > were equivalent to arrays of bytes. Then came Unicode strings. Then > came the restriction of ASCII chars to 0..127. Except that you can > still store binary bytes in ASCII strings, subject to some limitations. Sorry, but that's bogus. Python had byte-strings from the beginning. Nothing to do with ASCII. Which is an encoding-standard that has ALWAYS been limited to the numbers 0..127. All that changed was the introduction of unicode-objects and due to the fact that these need to be serialized to/from bytestrings the introduction of ASCII as default-encoding. So no "still storing" or anything such. Diez From spam at chezmarshall.freeserve.co.uk Wed Aug 29 12:49:05 2007 From: spam at chezmarshall.freeserve.co.uk (Robert Marshall) Date: Wed, 29 Aug 2007 16:49:05 GMT Subject: Gmane's been quiet ... References: <1i3l2k9.1j3tdgr1iz19yeN%raims@dot.com> <13d9l0f1i2erdc6@corp.supernews.com> <1i3lsqu.10ti61g1fs47osN%raims@dot.com> Message-ID: On Wed, 29 Aug 2007, Steve Holden wrote: > > Lawrence Oluyede wrote: >> Grant Edwards wrote: >>> Posting that were made to mailing lists via gmane? >> >> That, I do not know >> > Given that I have now read a reply to my post-via-gmane on gmane > before seeing the original post appear there I shall assume they've > been having some sort of issue. > See http://news.gmane.org/gmane.discuss for some discussion of this... Robert -- La grenouille songe..dans son ch?teau d'eau Links and things http://rmstar.blogspot.com/ From david at nospam.spam Mon Aug 13 20:52:59 2007 From: david at nospam.spam (david) Date: Tue, 14 Aug 2007 10:52:59 +1000 Subject: wxPython before MainLoop In-Reply-To: <5i3b1jF3n5bdtU1@mid.individual.net> References: <13bl9a75laqcm70@corp.supernews.com> <13bnh5bs4b9h427@corp.supernews.com> <5i3b1jF3n5bdtU1@mid.individual.net> Message-ID: <13c1v79hs0dob3@corp.supernews.com> Well yes, I have tried this app with native windows, and I know how to do it. But if all wxPython can offer is a poor imitation of MFC, I'm better off using MFC aren't I? And too all those people who wrote back to insist that users MUST explicitly build a multi-threaded framework for wxPython: It's supposed to already be a framework :~) (david) Bjoern Schliessmann wrote: > [david] wrote: > >> I'm disappointed that I didn't get a wxPython solution. >> >> If the only way to get wxPython to correctly handle >> this simple task is to code around it, > > LOL -- did you try coding this app with native windows means, like > MFC? You will have *exactly* the same problem, and *exactly* for > the same reason. The organisation of wxWidgets (and thus, wxPython) > is very near to Windows GUI coding philosophy. > >> I don't think wxPython is really ready for Windows. > > I suggest you first went getting experience with other GUI libraries > before you make such statements. > > Also, wxPython is a thin wrapper around wxWidgets C++ library which > is widely used for Windows apps. And with wxWidgets, you'd *also* > have the same problem. > >> Bjoern, you're wrong. The GUI needs to be displayed >> for the user to analyse. A delay between display and >> readiness is much better than a delay before display >> or a delay with the GUI half-drawn. > > This may be, but it strongly depends on the application itself. > >> Mike, the screen does display correctly, it's just >> that in Windows, screen updates are not processed >> while the application is busy. > > That's the matter in just about *every* GUI framework using an event > loop. And I don't know any that doesn't. Thus, there are two widely > used standard solutions: > > * use a worker thread, or > > * call a "process all pending events now" function repeatedly during > the work (here: wx.Yield, wx.SafeYield, wx.YieldIfNeeded). > > Regards, > > > Bj?rn > From kkuang at torreyhillstech.com Sun Aug 19 13:49:11 2007 From: kkuang at torreyhillstech.com (Torrey Hills) Date: Sun, 19 Aug 2007 17:49:11 -0000 Subject: A/C Systems! In-Reply-To: <1187545327.963222.223220@w3g2000hsg.googlegroups.com> References: <1187545194.099278.217330@w3g2000hsg.googlegroups.com> <1187545327.963222.223220@w3g2000hsg.googlegroups.com> Message-ID: <1187545751.122168.89790@i38g2000prf.googlegroups.com> On Aug 19, 10:42 am, carairconditionersm... at gmail.com wrote: > On Aug 19, 7:39 pm, Cartun... at gmail.com wrote: > > > Everything you need to know about car air conditioners... > > >http://car-air-conditioning.blogspot.com/ > > Great website man, I found everything I need A lot of wonderful tips. Thanks. Ken Opportunities are never lost. The other fellow takes those you miss. | Torrey Hills Technologies, LLC | | www.threerollmill.com | | www.torreyhillstech.com | From yan.python at gmail.com Tue Aug 14 10:59:42 2007 From: yan.python at gmail.com (yan.python at gmail.com) Date: Tue, 14 Aug 2007 14:59:42 -0000 Subject: how to move cursor in Interactive Interpreter In-Reply-To: References: <1187072484.626674.157200@x40g2000prg.googlegroups.com> <1187090548.811916.124450@x40g2000prg.googlegroups.com> Message-ID: <1187103582.015207.128020@g12g2000prg.googlegroups.com> On 8 14 , 9 20 , Peter Otten <__pete... at web.de> wrote: > yan.pyt... at gmail.com wrote: > > what am i supposed to do to install the module GNU readline correctly > > then? > > by the way,my linux is Mandriva 10 > > Use the package manager of your distribution to install the readline > development package -- after some struggle with Mandriva's website I came > to suppose that it's libreadline5-devel for you: > > urpmi libreadline5-devel.rpm > > After you have successfully installed that package unpack the python archive > into a fresh directory and do the configure/make/install dance. No manual > changes should be necessary. > > Peter i've re-install python as you said,and it works now i really appreciate your help thanks! From xah at xahlee.org Fri Aug 24 23:55:59 2007 From: xah at xahlee.org (Xah Lee) Date: Fri, 24 Aug 2007 20:55:59 -0700 Subject: Xah's Edu Corner: Under the spell of Leibniz's dream In-Reply-To: References: <1187567809.896668.228650@z24g2000prh.googlegroups.com> <1187598193.118227.270460@19g2000hsx.googlegroups.com> <46ca1e65$1_3@news.chariot.net.au> <5j4rrfF3s3h2rU1@mid.dfncis.de> <1187908258.609624.321990@m37g2000prh.googlegroups.com> Message-ID: <1188014159.445663.17500@m37g2000prh.googlegroups.com> 2007-08-24 Steve Holden wrote: ?It's already well-established that there's no point flamingXahLee, as he's pretty much an output-only source. See any responses from him on this thread?? Hum? so you want to dance? FYI, i have made a second post to this thread. See: http://groups.google.com/group/comp.lang.functional/msg/973fe835bd0ad230?dmode=source The content is too abstruse for general imperative programers to understand, so i limited it to only the functional programing groups. But frankly, even there, very few are capable of appreciating it. To be more frank, the majority of math PHD holders in this world today, do not have sufficient knowledge about the subject to appreciate what i wrote. Xah xah at xahlee.org ? http://xahlee.org/ From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Aug 29 12:32:46 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 29 Aug 2007 18:32:46 +0200 Subject: Creating a multi-tier client/server application In-Reply-To: <1188398008.538820.21960@d55g2000hsg.googlegroups.com> References: <1188360460.838635.186930@w3g2000hsg.googlegroups.com> <7xbqcqhqbw.fsf@ruckus.brouhaha.com> <46d54ed8$0$429$426a34cc@news.free.fr> <1188393925.007952.313110@r29g2000hsg.googlegroups.com> <46d57888$0$295$426a74cc@news.free.fr> <1188398008.538820.21960@d55g2000hsg.googlegroups.com> Message-ID: <46d59fa8$0$278$426a74cc@news.free.fr> Jeff a ?crit : >> You could explore something like a custom-made GUI client app >> communicating thru the http protocol with a web-server app. http is just >> a protocol, and it doesn't necessarily imply using html and a browser... >> IIRC, some GUI toolkits uses XML description files for the UI. > > That, or something similar, may be what I do. It would mean, however, > developing my own method for transferring objects across the network, Why transfering "objects" ? You only need to transfer data. (snip) From steve at holdenweb.com Mon Aug 6 19:22:12 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 06 Aug 2007 19:22:12 -0400 Subject: maybe a popen question... or something else? In-Reply-To: <1186441210.383700.301790@i13g2000prf.googlegroups.com> References: <1186441210.383700.301790@i13g2000prf.googlegroups.com> Message-ID: <46B7AD24.4010305@holdenweb.com> dude wrote: > Working on Windows XP > Say I have a Windows executable, foo.exe. > foo.exe is a command line tool that can take a number of different > arguments and perform corresponding actions. > > I want to invoke foo.exe from a Python script (using whatever will > work best). I want to continuously pass arguments to foo.exe in > between doing other stuff from within my Python script. > > Some pseudo code: > > processHandle = invoke("foo.exe") # what python module should "invoke" > be here? > > doUnrelatedStuff() > > processHandle.passArgs("arg1 arg2") # The same foo.exe I invoked above > gets these args for processing > > doMoreUnrelatedStuff() > > processHandle.passArgs("arg3 arg4") # The same foo.exe I invoked above > gets these args for processing > > processHandle.close() # "foo.exe is destroyed" > > Thanks for any help. > When you say "pass arguments", the methodology you outline definitely isn't going to fly with argument passing. When a command is invoked the arguments are taken from the command line, so it isn't possible to pass further arguments at a later time. You probably need to write to you sub-process's standard input stream. which you can do whit the subprocess module (the modern way to do it) or one of the various popen() functions. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From mtobis at gmail.com Sat Aug 4 11:10:49 2007 From: mtobis at gmail.com (Michael Tobis) Date: Sat, 04 Aug 2007 15:10:49 -0000 Subject: the one python book In-Reply-To: References: Message-ID: <1186240249.433185.291390@r34g2000hsd.googlegroups.com> On Aug 4, 9:32 am, Neil Cerutti wrot > With Python, you won't find anything like that. Python is too > huge. That's silly. Python is small in the sense that C is small. The Python standard library is probably much bigger than the C standard library, but Kernghan and Richie don't cover it. K&R is a unique book. I have never seen anything comparable for any language. The closest Python equivalent is the official docs: http://docs.python.org/ I think the core Python bookshelf is: Learning Python (Lutxz & Ascher) and/or Dive Into Python (Pilgrim) for tutorial Python in a Nutshell (Martelli) AND Python Essential Reference (Beazley) for reference The latter two books are not perfect (both indexes are infuriating) but I usually find that I can find what I am looking for in one or the other. Like most people I eventually plan to read Moby Dick, War and Peace, and Lutz's Programming Python. Maybe when I retire. mt From AWasilenko at gmail.com Sat Aug 11 12:40:02 2007 From: AWasilenko at gmail.com (Adam W.) Date: Sat, 11 Aug 2007 16:40:02 -0000 Subject: Who told str() to round my int()'s!!! Message-ID: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> After a fair amount of troubleshooting of why my lists were coming back a handful of digits short, and the last digit rounded off, I determined the str() function was to blame: >>> foonum 0.0071299720384678782 >>> str(foonum) '0.00712997203847' >>> Why in the world does str() have any business rounding my numbers, and how do I get around this? From joesox at gmail.com Mon Aug 20 22:35:21 2007 From: joesox at gmail.com (JoeSox) Date: Mon, 20 Aug 2007 19:35:21 -0700 Subject: Python project solicitation Message-ID: <785694cd0708201935s7472a658u1f507776dfcb8e1e@mail.gmail.com> Hello All, I was wondering if anyone would be interested in improving a module I quickly hacked together this past Sunday: pswrdgen.py It is a semantic password generator that uses WordNet 2.1, random capitalization, and character swapping. http://code.google.com/p/pswrdgen/ I must say this thing is pretty cool. I had a coworker try it out and he ran into problems getting it to run on his Linux OS. So I am really looking for some non-Windows developers to take a look at it. All of the info is at the project site above. Thanks. And on a side note, I see a bunch of Python newbies here. I really recommend "Python Phrasebook" by Brad Dayley. This thing is small enough to fit in your back pocket and lots of basic code phrases. -- Later, Joe From __peter__ at web.de Sun Aug 12 06:18:39 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 12 Aug 2007 12:18:39 +0200 Subject: Fatest standard way to sum bytes (and their squares)? References: Message-ID: Peter Otten wrote: > lookup = [i**2 for i in range(256)] > >> def summit_str(data=data): >> return sum(ord(x) for x in data), sum(ord(x)**2 for x in data) >> >> def summit_array(data=data, lookup=lookup): >> a = array.array("B") >> a.fromstring(data) >> return sum(a), sum(lookup[x] for x in a) > $ python -m timeit -s'from summit import summit_array as summit' > 'summit()' 100 loops, best of 3: 12.9 msec per loop from itertools import imap def summit_array(data=data, lookup=lookup): a = array.array("B") a.fromstring(data) return sum(a), sum(imap(lookup.__getitem__, a)) $ python -m timeit -s'from summit import summit_array as summit' 'summit()' 100 loops, best of 3: 9.15 msec per loop I think I'll stop here... Peter From arkanes at gmail.com Wed Aug 15 20:37:04 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 15 Aug 2007 19:37:04 -0500 Subject: Move files/directories to Recycle Bin using standard Python libs In-Reply-To: <1187211948.913922.197830@m37g2000prh.googlegroups.com> References: <1187211948.913922.197830@m37g2000prh.googlegroups.com> Message-ID: <4866bea60708151737p4d8bb3b7q54b675da636050a4@mail.gmail.com> On 8/15/07, kyosohma at gmail.com wrote: > On Aug 15, 2:55 pm, Kevin D. Smith wrote: > > On 2007-08-15 13:02:24 -0600, "Chris Mellon" said: > > > > > Not easily. The recycle bin is part of the shell, and the shell api > > > calls have very complicated struct parameters that are cumbersome to > > > use correctly from ctypes. If you do the work to map the fileop > > > structs to ctypes you can call the shell API file operation functions > > > in shell32.dll. This assumes that "standard" for you is Python 2.5, > > > which has ctypes. Otherwise you are out of luck. > > > > Unfortunately, I need this to work on Python 2.4 as well... > > > > -- > > Kevin D. Smith > > As I mentioned in my previous post, you can download ctypes from > sourceforge for 2.4. > > Mike > If you're going to install a third party lib, install pywin32 and do it the easy way. OP said he wanted to it with standard library only. From wgwigw at gmail.com Wed Aug 1 03:11:07 2007 From: wgwigw at gmail.com (momobear) Date: Wed, 01 Aug 2007 07:11:07 -0000 Subject: Any way to monitor windows network connection? In-Reply-To: <_ICdnc3T261KgC3bnZ2dnUVZ_oHinZ2d@comcast.com> References: <1185939997.135825.310080@z24g2000prh.googlegroups.com> <_ICdnc3T261KgC3bnZ2dnUVZ_oHinZ2d@comcast.com> Message-ID: <1185952267.173790.279900@j4g2000prf.googlegroups.com> On Aug 1, 1:47 pm, Gordon Airporte wrote: > momobear wrote: > > hi, Is there any way to show me detailed listings of all TCP and UDP > > endpoints in my microsoft windows XP in python way? > > thanks. > > Unless you're looking for a programming exercise:http://www.microsoft.com/technet/sysinternals/Utilities/TcpView.mspx Ok, It works, but there're no source code of it. I wish to build a tools to show all the network endpoints, cpu usage and top ten processes in a dockapp like application. From jstroud at mbi.ucla.edu Thu Aug 30 15:49:42 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 30 Aug 2007 12:49:42 -0700 Subject: Important Research Project In-Reply-To: <1188482087.098419.56490@k79g2000hse.googlegroups.com> References: <13ddcvm1bsu3s94@corp.supernews.com> <1188482087.098419.56490@k79g2000hse.googlegroups.com> Message-ID: Paul McGuire wrote: > GTFA, Very funny. I'm sure it would have been funnier if I had the patience to read the original posting. I'm guessing you paraphrased the content sufficiently well in your reply. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From fakeaddress at nowhere.org Sun Aug 19 09:10:31 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 19 Aug 2007 06:10:31 -0700 Subject: Development for dual core machine In-Reply-To: <1187515287.226791.186700@j4g2000prf.googlegroups.com> References: <1187515287.226791.186700@j4g2000prf.googlegroups.com> Message-ID: <6jXxi.1074$vU4.15@nlpi068.nbdc.sbc.com> Andy wrote: > I'm going to develop a software package that includes a web server > (and PHP code) , a database, and some Python code of course. I am > being strongly suggested to make it to work on a dual- or multi-core > computer, but I'm confused on how to take advantage of the multiple > CPUs. > > From what I read, I think that simply by making the package run in > several separate processes (web server, database server, Python > interpreter, etc.), and/or using multiple threads (which I will > anyway) the package should be able to use multiple CPUs. Right. There is a theoretical possibility that Python's GIL could limit thread parallelism, but in this kind of application it should not matter in the least. Either you're I/O bound, or there are plenty of tasks the operating system could schedule. If you have the option to run the Python interpreter within a web-server process, that's usually a performance winner. > Is my understanding correct? So actually, all I have to do is just > write my multi-threaded Python code as usual? And how is it decided > which process and which threads go to CPU 1, CPU 2, etc.? Perhaps the > BIOS? The O.S. actually. A lot of really smart people have put a whole lot of work into making the O.S. do that well. If you usually write your Python apps multi-threaded, as I do, that's fine. Multi-core efficiency has only a little to do with it. Web service are, for the most part, intrinsically parallelizable: run multiple web servers, and multiple Python interpreters serving multiple connections. The only hard part is shared data. Scalability is all about the database. -- --Bryan From python at jayloden.com Mon Aug 20 17:31:00 2007 From: python at jayloden.com (Jay Loden) Date: Mon, 20 Aug 2007 17:31:00 -0400 Subject: optparse - required options In-Reply-To: <496954360708201353v19ea266cr50f144d1d71d5912@mail.gmail.com> References: <496954360708201251r137dfaedqe632361891eae343@mail.gmail.com> <46C9F7D1.9040506@jayloden.com> <496954360708201353v19ea266cr50f144d1d71d5912@mail.gmail.com> Message-ID: <46CA0814.6050200@jayloden.com> Robert Dailey wrote: > Well, I don't know what is wrong with people then. I don't see how > required arguments are of bad design. Some command-line applications are > built around performing tasks based on information received. Compilers, > for example. A compiler can't do much of anything unless you give it at > the very least a filename. So, a --file command would most definitely be > one required argument. Anyway, I'm not trying to start a debate on this > issue. I have my own implementation for required arguments at the > moment, I am just a little bit surprised that this module doesn't make > it convenient. It would definitely help on code duplication. > > Thanks for your response. I tend to agree...while "required option" may be an oxymoron in English, I can think of quite a few scripts I've written myself (in various languages) that needed at least some kind of user input to operate. At least the documentation points to some examples for helpful hints, example code is a lot better than nothing ;) -Jay From uymqlp502 at sneakemail.com Fri Aug 31 04:02:49 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Fri, 31 Aug 2007 01:02:49 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1i3o9kr.2gmni61g62moaN%aleax@mac.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> Message-ID: <1188547369.428712.194430@x35g2000prf.googlegroups.com> On Aug 30, 7:20 pm, al... at mac.com (Alex Martelli) wrote: > Russ wrote: > > ... > > > programs." Any idea how much Python is used for flight control systems > > in commercial > > transport aircraft or jet fighters? Hi Alex. I've always enjoyed your Piggies talks at Google (although I missed he last one because I was out of town). I'm disappointed to see that you seem to have taken personal offense from remarks I made to someone else who attacked me first. I will take issue with some of your remarks, bit none of it is intended to be personal, and I sincerely hope you don't take it that way. > Are there differences in reliability requirements between the parts of > such control systems that run on aircraft themselves, and those that run > in airports' control towers? Because Python *IS* used in the latter > case, cfr ... if > on-plane control SW requires hard-real-time response, that might be a > more credible reason why Python would be inappropriate (any garbage > collected language is NOT a candidate for hard-real-time SW!) than your > implied aspersions against Python's reliability. I've seen that site before. They have a nice product that was developed in Python, but it is not clear to me that is actually safety-critical. It appears to be a GUI designer for displays at air traffic control towers. I can't tell if this is "just" a development tool, or if it the python-based product is actually used directly by controllers. Also, this product does not seem to actually display aircraft to controllers. It seems to be more of a semi-static display of runway conditions. Not to minimize its importance, but I don't know if this product actually qualifies as safety critical, and if it does, it probably does so only marginally. > According to > , > Google's current uptime is around 99.99%, with many months at 100% and a > few at 99.98% -- and that's on *cheap*, not-that-reliable commodity HW, > and in real-world conditions where power can go away, network cables can > accidentally get cut, etc. I'm Uber Tech Lead for Production Systems at > Google -- i.e., the groups I uber-lead are responsible for some software > which (partly by automating things as much as possible) empowers our > wondrous Site Reliability Engineers and network specialists to achieve > that uptime in face of all the Bad Stuff the world can and does throw at > us. Guess what programming language I'm a well-known expert of...? I certainly cannot deny the success of Google, but I don't think that a high uptime with thousands of servers is comparable to reliable safety-critical software. You can't put thousands of flight management computers on an airplane and just switch over to another as they go fail. And if a web server gives bogus results nobody worries much, but if a flight computer gives bogus outputs, some people worry a lot. By the way, I use Google Groups, and it has a few annoying glitches. For example, I couldn't read your post without scrolling horizontally. With all the money and manpower at Google's disposal, couldn't you fix that problem? Another problem I have had for months is that when I write a message to post, I get no auto scrolling, so I have to add manual line breaks to keep the text from running out of the window -- then the reader sees all those ugly misplaced line breaks in the output. These are just annoyances, but why hasn't Google fixed them yet? The point I am trying to make is that, while Google does great things, and is very successful commercially, the quality of its code could certainly use some improvement. Microsoft is also very successful commercially, but certainly you wouldn't argue that is is a result of the quality of its software, I hope. I may have a simplistic view, but I have always thought that the requirements of most Google code are the very antithesis of the requirements of safety critical code. When I do a search, I fully expect most of the results to be crap. It's a scattershot approach. If I get one good result, I am usually happy. Safety critical software is exactly the opposite: if you get one *bad* result, you could be in a heap of something nasty. > > The important question is this: why do I waste my time with bozos like > > you? > > Yeah, good question indeed, and I'm asking myself that -- somebody who > posts to this group in order to attack the reliability of the language > the group is about (and appears to be supremely ignorant about its use I am sorry that you took offense at my pointing out the weaknesses of Python. It's a great language for certain kinds of applications, but it is not necessarily appropriate for everything. I am personally using it for prototyping a safety critical system that, if it is ultimately fielded, will affect the safety of millions of people, including you. However, my Python prototype is for research and design purposes. The ultimate implementation is very unlikely to be in Python. Even so, I would like to make my prototype as reliable as possible, and that is why I am interested in the idea of self-testing code or "programming by contract." > in air-traffic control and for high-reliability mission-critical > applications such as Google's "Production Systems" software) might well > be considered not worth responding to. OTOH, you _did_ irritate me > enough that I feel happier for venting in response;-) > > Oh, FYI -- among the many tasks I undertook in my quarter-century long > career was leading and coordinating pilot projects in Eiffel for one > employer, many years ago. The result of the pilot was that Eiffel and > its DbC features didn't really let us save any of the extensive testing > we performed for C++-coded components, and the overall reliability of > such extensively tested components was not different in a statistically > significant way whether they were coded in C++ or Eiffel; Eiffel did let > us catch a few bugs marginally earlier (but then, I'm now convinced > that, at that distant time, we used by far too few unit-tests for early > bug catching and relied too much on regression and acceptance tests), > but that definitely was _not_ enough to pay for itself. DbC and > allegedly rigorous compile-time typechecking (regularly too weak due to > Eiffel's covariant vs countervariant approach, btw...), based on those > empirical results, appear to be way overhyped. First of all, I am having a hard time reading your post because Google is forcing me to scroll horizontally to read each line. But all I can say is that your experience with self-testing code doesn't seem to be consistent with the experience of many others who have used it. Is it possible that you didn't use it to its fullest extent? > A small decorator library supporting DbC would probably be a nice > addition to Python, but it should first prove itself in the field by > being released and supported as an add-on and gaining wide acceptance: > "arguments" such as yours are definitely NOT going to change that. I'm sorry to see that you are so closed-minded about the idea. I get the impression that you are close to the Benevelent Dictator, but I can only hope that he remains more open minded than you. I already explained why I don't like the "decorator" approach (it puts the conditions outside of the body of the function, for one thing). I can only say that I am happy that I can always use the implementation described in PEP 316. That's the beauty of open source, isn't it. From zyzhu2000 at gmail.com Sat Aug 18 20:45:34 2007 From: zyzhu2000 at gmail.com (beginner) Date: Sun, 19 Aug 2007 00:45:34 -0000 Subject: How to make a module function visible only inside the module? Message-ID: <1187484334.091530.90420@m37g2000prh.googlegroups.com> Hi Everyone, Is there any equivalent version of C's static function in Python. I know I can make a class function private by starting a function name with two underscores, but it does not work with module functions. For exmaple, __func1 is still visible outside the module. mymodule.py """my module"" def __func1(): print "Hello" main.py import mymodule mymodule.__func1() Thanks, Geoffrey From ricaraoz at gmail.com Mon Aug 13 15:22:06 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 13 Aug 2007 16:22:06 -0300 Subject: Finding gurus (was Re: Something in the function tutorial confused me.) In-Reply-To: References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <5hv705F3mk67nU1@mid.individual.net> <1i2nhnv.2y00l5173lfbbN%aleax@mac.com> Message-ID: <46C0AF5E.3060701@bigfoot.com> Aahz wrote: > In article <1i2nhnv.2y00l5173lfbbN%aleax at mac.com>, > Alex Martelli wrote: >> Because of this, a Google search for >> >> " " python >> >> may sometimes help; when you get 116,000 hits, as for "Steve Holden" >> python, that may be a reasonable indication that the poster is one of >> the world's Python Gurus (in fact, the winner of the 2007 Frank WIllison >> Award -- congratulations, Steve!!!). > > Sometimes that precise search pattern isn't appropriate, of course. ;-) Sorry, will answer as soon as I read the 52000 hits for "Aahz python". Be patient ;c) From timr at probo.com Sat Aug 4 21:46:51 2007 From: timr at probo.com (Tim Roberts) Date: Sun, 05 Aug 2007 01:46:51 GMT Subject: os.listdir path error References: <1186170609.001778.15230@l70g2000hse.googlegroups.com> <1186171610.333624.103640@e9g2000prf.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > >I get "SyntaxError: EOL while scanning single-quoted string", which is >what should happen when you escape the double-quotes at the end. Not >sure how you're getting that WindowsErrors. > >If I do os.listdir('c:\python24') instead, it works fine. Yes, but only by accident. It will fail again if you try to do os.listdir('c:\tmp'). You need to use the right quoting. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From attn.steven.kuo at gmail.com Wed Aug 1 15:57:20 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Wed, 01 Aug 2007 12:57:20 -0700 Subject: Awkward format string In-Reply-To: <1185986578.527619.314310@e9g2000prf.googlegroups.com> References: <1185984697.605529.157110@g12g2000prg.googlegroups.com> <1185986578.527619.314310@e9g2000prf.googlegroups.com> Message-ID: <1185998240.878225.286520@e9g2000prf.googlegroups.com> On Aug 1, 9:42 am, beginner wrote: (snipped) > > e is not complicated. It is a record that have 7 fields. In my program > a function outputs a list of tuples, each is of type e, and now I just > need to send them to a text file. > > I have no problem using classes and I do use them everywhere. But > using classes does not solve my problem here. I will probably find > myself doing: > > print >>f, "%s\t%s\t%d\t%f\t%f\t%f\t%d" % (x.field1..strftime("%Y-%m- > %d"), x.field2..strftime("%Y-%m-%d"), x.field3, x.field4, x.field5, > x.field.6, x.field7) > > This is also tedious and error-prone. You can implement a __str__ special method in a class. You can use 'type' to examine, well, the type of an object. So: from datetime import datetime class PrettyDT(datetime): def __str__(self): return self.strftime('%Y-%m-%d') e = (PrettyDT(2007, 8, 1), PrettyDT(2007, 8, 2), 1, 2.0, 3.0, 4) print '\t'.join(str(each) for each in e) # Or even format = { int: '%d', float: '%f', PrettyDT: '%s' } format_string = '\t'.join(format[type(each)] for each in e) print format_string % e; -- Hope this helps, Steven From jjl at pobox.com Sat Aug 11 07:25:01 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 11 Aug 2007 11:25:01 GMT Subject: cookielib References: Message-ID: <87bqdeuxde.fsf@pobox.com> Boris Ozegovic writes: > Hi > > I have HTTP client which accepts cookies. If client allready has cookie, > but that cookie has expired, server sends him new cookie, and in response > object Set-Cookie: header everything is fine, but if I reload request, > client sends expired cookie, and not the new one. In cookiejar there is > only new and valid cookie, and if I use regular browser everything is fine. > The code is following: > > urlopen = urllib2.urlopen > Request = urllib2.Request > cj = cookielib.LWPCookieJar() > COOKIEFILE = 'cookies.lwp' > > if os.path.isfile(COOKIEFILE): > # if we have a cookie file already saved > # then load the cookies into the Cookie Jar > cj.load(COOKIEFILE) > > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > urllib2.install_opener(opener) > url = "http://localhost:8000/files/index.html" > params = {'question':question} > data = urllib.urlencode(params) > Request(url, data) > try: > response = urlopen(Request) > etc. > > Only if I create new request object the new cookie is send, but I don't > want to create new object. And idea? You seem to suggest in your first paragraph that you call urlopen more than once, but in the code you show, you call it only once. This is the way HTTP cookies work: you can't send back a cookie before you've received it. So, you need two HTTP requests: one to get the cookie, and a second to send it back again. However, some websites arrange things so that a single attempt to load a URL results in multiple HTTP requests. One common way to do that is by using an "HTTP Refresh" -- look at the top of the HTML to see if there's a META tag something like this: This means that the browser should reload the page after a pause of one second. Often, the reloaded page then does not contain another meta refresh tag, so that the page does not reload every second forever (the server knows not to include the tag because it received the cookie). This tag can be supported by appropriate Python code. So, two HTTP requests needn't necessarily mean two urlopen calls. This library handles refresh redirections, and supports essentially the same interface as urllib2 and cookielib (the union of the two interfaces): http://wwwsearch.sourceforge.net/mechanize/ John From sbellon at sbellon.de Sat Aug 11 08:50:33 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Sat, 11 Aug 2007 14:50:33 +0200 Subject: Destruction of generator objects References: <20070808002852.6228ae91@cube.tz.axivion.com> <1186613044.494852.306970@q75g2000hsh.googlegroups.com> <20070809011441.05d7dfb6@cube.tz.axivion.com> <1186819365.988117.232230@g4g2000hsf.googlegroups.com> <20070811121630.1b010eab@cube.tz.axivion.com> <1186831173.814193.235420@o61g2000hsh.googlegroups.com> <20070811140017.22a11f82@cube.tz.axivion.com> <1186834823.389706.137980@r34g2000hsd.googlegroups.com> Message-ID: <20070811145033.18c70c0c@cube.tz.axivion.com> On Sat, 11 Aug, Kay Schluehr wrote: > But why shall the destructor be called? Your example does not indicate > that a ListGenerator object is somewhere destroyed neither explicitely > using del nor implicitely by destroying the scope it is living in. After having constructed the list itself, the generator is exhausted and not iterated or referenced anymore, so the generator should be destroyed, shouldn't it? Ok, let's make the example easier and take out the external iterator resource and just concentrate on the Python part: class ListGenerator(object): def __init__(self): print "gen init" self.gen = self._value() def __del__(self): print "gen del" def _value(self): print "gen value" for i in xrange(4): yield i def __iter__(self): print "gen iter" return self def next(self): print "gen next" return self.gen.next() Now, doing the following: >>> a = ListGenerator() gen init >>> a <__main__.ListGenerator object at 0x4020c3ec> >>> for i in a: print i ... gen iter gen next gen value 0 gen next 1 gen next 2 gen next 3 gen next >>> del a >>> So why is the destructor not called when the generator is even explicitly 'del'ed? Does somebody else still hold a reference on it? But then, even when terminating the interpreter, __del__ is not called. When taking out the yield statement, __del__ is called again. It looks to me that as soon as a generator function is involved in the class, the __del__ is not called anymore. -- Stefan Bellon From llasram at gmail.com Thu Aug 16 07:37:07 2007 From: llasram at gmail.com (Marshall T. Vandegrift) Date: Thu, 16 Aug 2007 07:37:07 -0400 Subject: Coroutines and argument tupling References: <5ih63mF3pvnt7U1@mid.individual.net> <87k5rwo24e.fsf@seneca.iss.local> <5iikd6F3pfrhrU1@mid.individual.net> Message-ID: <87absrogm4.fsf@seneca.iss.local> Bjoern Schliessmann writes: > The solution I'd use is a decorator that calls next automatically one > time after instantiation. Then you can use send normally, and don't > have to care about any initial parameters, which makes the code > clearer (initial parameters should be used for setup purposes, but not > for the first iteration, IMHO). It'd look like this (from PEP 342, > http://www.python.org/dev/peps/pep-0342/): I'd seen the consumer decorator, and it certainly is cleaner than just using a generator. I don't like how it hides the parameter signature in the middle of the consumer function though, and it also doesn't provide for argument default values. It's the difference between: ... def __init__(self, ...): ... self.consumer = self._function(value) ... def function(self, first, second=3, *args, **kwargs): self.consumer.send((first, second, args, kwargs)) @consumer def _function(self, setup): ... first, second, args, kwargs = yield # initial 'next' while condition: ... first, second, args, kwargs = yield retval Versus just: @coroutine def function(self, first, second=3, *args, **kwargs): ... while condition: ... first, second, args, kwargs = yield retval Thanks in any case for the replies! Since I've apparently decided my ArgPacker is worth it, the complete code for my coroutine decorator follows. -Marshall import inspect import types import functools from itertools import izip __all__ = [ 'coroutine' ] class ArgPacker(object): def __init__(self, function): args, varargs, varkw, defaults = inspect.getargspec(function) self.args = args or [] self.varargs = (varargs is not None) and 1 or 0 self.varkw = (varkw is not None) and 1 or 0 self.nargs = len(self.args) + self.varargs + self.varkw defaults = defaults or [] defargs = self.args[len(self.args) - len(defaults):] self.defaults = dict([(k, v) for k, v in izip(defargs, defaults)]) def pack(self, *args, **kwargs): args = list(args) result = [None] * self.nargs for i, arg in izip(xrange(len(self.args)), self.args): if args: result[i] = args.pop(0) elif arg in kwargs: result[i] = kwargs[arg] del kwargs[arg] elif arg in self.defaults: result[i] = self.defaults[arg] else: return None if self.varargs: result[len(self.args)] = args elif args: return None if self.varkw: result[-1] = kwargs elif kwargs: return None return tuple(result) class coroutine(object): """Convert a function to be a simple coroutine. A simple coroutine is a generator bound to act as much as possible like a normal function. Callers call the function as usual while the coroutine produces new return values and receives new arguments with `yield'. """ def __init__(self, function): self.function = function self.gname = ''.join(['__', function.__name__, '_generator']) self.packer = ArgPacker(function) coroutine = self def method(self, *args, **kwargs): return coroutine.generate(self, self, *args, **kwargs) self.method = method functools.update_wrapper(self, function) functools.update_wrapper(method, function) def __get__(self, obj, objtype=None): return types.MethodType(self.method, obj, objtype) def __call__(self, *args, **kwargs): return self.generate(self, *args, **kwargs) def generate(self, obj, *args, **kwargs): try: generator = getattr(obj, self.gname) except AttributeError: generator = self.function(*args, **kwargs) setattr(obj, self.gname, generator) retval = generator.next() else: packed = self.packer.pack(*args, **kwargs) if packed is None: self.function(*args, **kwargs) # Should raise TypeError raise RuntimeError("ArgPacker reported spurious error") retval = generator.send(packed) return retval From dzjoost at gmail.com Thu Aug 16 10:38:19 2007 From: dzjoost at gmail.com (Joost Molenaar) Date: Thu, 16 Aug 2007 16:38:19 +0200 Subject: FM synthesis using Numpy In-Reply-To: <1187189638.121287.311030@k79g2000hse.googlegroups.com> References: <1187189638.121287.311030@k79g2000hse.googlegroups.com> Message-ID: <3657a8860708160738i6c1b1caan8e0e9402d0d77232@mail.gmail.com> Thanks/bedankt Bas for the educative reply. I think I got misleaded by Max/MSP's tutorial[1], because MSP seems to automatically adjust the phase when you combine two oscillators in the way that I did. Joost [1] page 112 of http://www.cycling74.com/download/MSP45TutorialsAndTopics.pdf From joesox at gmail.com Mon Aug 20 00:04:53 2007 From: joesox at gmail.com (JoeSox) Date: Sun, 19 Aug 2007 21:04:53 -0700 Subject: How do I call anonymous classes from imported modules? In-Reply-To: References: Message-ID: <785694cd0708192104x3865c75fx73697da92dcb1ff5@mail.gmail.com> On 8/19/07, James Stroud wrote: > Quick and dirty (you could also use a try: except:): > > f = __import__(module_name) > for anobj in f.__dict__.values(): > if hasattr(anobj, 'do_foobar'): > anobj.do_foobar() > > Note that this does not test whether anobj is a class as this would > entail a type-check, which hints to poor design. Thanks for the help. The __dict__.values() is something I have not previously looked into but it does not work as desired because python wants an instance of the class. How can I cast an object if I don't know what type of object it is (example.ticker, in this debug)? >>> modname = sensorsList[0].__name__ >>> m = __import__(modname) >>> for anobj in m.__dict__.values(): if hasattr(anobj, 'do_foobar'): anobj.do_foobar() Traceback (most recent call last): File "", line 3, in ? anobj.do_foobar() TypeError: unbound method do_foobar() must be called with ticker instance as first argument (got nothing instead) From gherzig at fmed.uba.ar Fri Aug 17 12:14:13 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Fri, 17 Aug 2007 13:14:13 -0300 Subject: advice about `correct' use of decorator In-Reply-To: <46C590FB.9090403@shopzeus.com> References: <46C4B097.4080309@fmed.uba.ar> <46C4B81A.8000304@shopzeus.com> <46C4C1B4.6050605@fmed.uba.ar> <46C590FB.9090403@shopzeus.com> Message-ID: <46C5C955.1020004@fmed.uba.ar> Laszlo Nagy wrote: > >>> >>> Are you developing a website or a GUI program? >>> >>> >> It will be used in a web development. It is an important point? > > Yes, I think. Unless you use AJAX. :-) Most web sites work this way: > > user clicks -> request to server -> process on server -> response > > I would rather enclose the whole handler in try/except and raise a > custom PermissionDenied exception when the user has inscuficient > permissions. There are problems with a decorator used for > authorization. The context needs to be determined. E.g. which user is > accessing the method? (It can be hard to tell if the method is part of > a thread object that lies in a thread pool and is shared between > simultaneous clients...) Also it might be that the method's purpose is > to change objects of the same class, and the user has permission to > modify one object but not the other. In this case, authorization must > be done inside the function call... How do you express this with a > decorator? > > These are just ideas. You should analyze your problem and make your > decision. If you only want to restrict access to functions, then > probably using decorators is perfect. > > Best, > > Laszlo > > I post the change_pass() function as an example, there is a buch of other functions (the whole site actually) that will require a logged user. May the change_pass() function have additional control, shure, but it will be not part of the `global' requirement. Thank you very much for your time, Laszlo Gerardo From no at spam.com Thu Aug 23 13:57:55 2007 From: no at spam.com (Farshid Lashkari) Date: Thu, 23 Aug 2007 10:57:55 -0700 Subject: Question about embedding python in C++ In-Reply-To: <1187891085.147246.19380@i38g2000prf.googlegroups.com> References: <1187891085.147246.19380@i38g2000prf.googlegroups.com> Message-ID: TheShadow wrote: > When extending python in c/c++ after you register a module is there a > way in c/c++ to check if they were correctly registered? > > Cause I'm having the problem where when I execute the the python > script it finds the module but none of the functions. > Are you calling Py_InitModule(...) in your initmodule function? If so, Py_InitModule(...) returns a reference to the module object. You can use this object to double check that your function names exist in the modules dictionary. Most likely, there is an error in your code. If you post it, it would be easier to tell what the problem is. -Farshid From zzbbaadd at aol.com Thu Aug 30 23:17:00 2007 From: zzbbaadd at aol.com (zzbbaadd at aol.com) Date: Thu, 30 Aug 2007 20:17:00 -0700 Subject: list index() In-Reply-To: References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188495863.242815.236900@o80g2000hse.googlegroups.com> <87bqcod2gq.fsf@benfinney.id.au> <1188517370.998114.119940@q4g2000prc.googlegroups.com> Message-ID: <1188530220.815429.281380@i38g2000prf.googlegroups.com> > Either I'm misunderstanding what you mean or you need to get a clue > about what Python can already do before you go around making suggestions > for what Python needs. Lists have supported "in" tests since at least > version 1.5.2: > Well IN was what I was looking for and would have saved this thread. However I don't believe IN showed up on the doc web page that has list methods, where I found index(). From http Wed Aug 8 02:35:20 2007 From: http (Paul Rubin) Date: 07 Aug 2007 23:35:20 -0700 Subject: Seek the one billionth line in a file containing 3 billion lines. References: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> Message-ID: <7xzm12o7o7.fsf@ruckus.brouhaha.com> Sullivan WxPyQtKinter writes: > This program: > for i in range(1000000000): > f.readline() > is absolutely every slow.... There are two problems: 1) range(1000000000) builds a list of a billion elements in memory, which is many gigabytes and probably thrashing your machine. You want to use xrange instead of range, which builds an iterator (i.e. something that uses just a small amount of memory, and generates the values on the fly instead of precomputing a list). 2) f.readline() reads an entire line of input which (depending on the nature of the log file) could also be of very large size. If you're sure the log file contents are sensible (lines up to several megabytes shouldn't cause a problem) then you can do it that way, but otherwise you want to read fixed size units. From aboudouvas at panafonet.gr Fri Aug 3 11:05:03 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Fri, 03 Aug 2007 08:05:03 -0700 Subject: Eclipse/PyDev question. In-Reply-To: <1186153259.372809.230110@d30g2000prg.googlegroups.com> References: <1186153119.391091.275860@r34g2000hsd.googlegroups.com> <1186153259.372809.230110@d30g2000prg.googlegroups.com> Message-ID: <1186153503.806195.225560@g4g2000hsf.googlegroups.com> On Aug 3, 5:00 pm, gregarican wrote: > On Aug 3, 10:58 am, king kikapu wrote: > > > Hi, > > this is actually a question to those of us who use Eclipse and Pydev > > as their main Python developing environment. As i use Eclipse (3.3 > > Europa) only for Python and i have nothing to do with Java, is there a > > way to disable/uninstall some Java-specific stuff and make the > > environment actually more snappy ?? > > > thanks for any help > > I've used Eclipse for Java, Python, and Ruby development and can say > that AFAIK "Eclipse" and "snappy" are contradictions. Like "jumbo" > "shrimp" :-/ xexexe...I am sure about that :) I was wondering if we can throw away some java-stuff and make our life easier (or, snappier)... From zhushenli at gmail.com Mon Aug 27 23:00:13 2007 From: zhushenli at gmail.com (Davy) Date: Mon, 27 Aug 2007 20:00:13 -0700 Subject: How to parse this line of code manually Message-ID: <1188270013.785762.9360@z24g2000prh.googlegroups.com> Hi all, It is well known that Python is appreciated for its merit of concise. However, I found the over concise code is too hard to understand for me. Consider, for instance, def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) Shall I understand the code in set() as for e2 in edits1(e1) { if e2 in NWORDS { for e1 in edits1(word) { e2 } } } And a general question is: Is there any tip available to understand the code in one line, or what's the parsing priority (left to right, right to left, or other possibilities) Any suggestions are welcome! The code is a simple spell checker from http://www.norvig.com/spell-correct.html Best regards, Davy From faulkner891 at gmail.com Wed Aug 8 22:43:20 2007 From: faulkner891 at gmail.com (faulkner) Date: Wed, 08 Aug 2007 19:43:20 -0700 Subject: How can I programmatically find the name of a method from within that method? In-Reply-To: <1186548312.672360.259100@q3g2000prf.googlegroups.com> References: <1186548312.672360.259100@q3g2000prf.googlegroups.com> Message-ID: <1186627400.727353.317750@d55g2000hsg.googlegroups.com> On Aug 8, 12:45 am, kj7ny wrote: > Is there a way that I can programmatically find the name of a method I > have created from within that method? I would like to be able to log > a message from within that method (def) and I would like to include > the name of the method from which it was written without having to > hard-code that value in every message string. While we're at it, is > there a way to programmatically get the name of the class and the > module while I'm at it? > > Thanks, def foo(): print sys._getframe(0).f_code.co_name most of the darkest magic of python is in the frames returned by sys._getframe. From bscrivener42 at gmail.com Thu Aug 16 13:28:10 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Thu, 16 Aug 2007 17:28:10 -0000 Subject: A problem with Time In-Reply-To: <5ija9dF3pjmsqU1@mid.uni-berlin.de> References: <46c469be$0$66145$7b0f0fd3@mistral.news.newnet.co.uk> <5ija9dF3pjmsqU1@mid.uni-berlin.de> Message-ID: <1187285290.931900.190830@m37g2000prh.googlegroups.com> On Aug 16, 10:54 am, "Diez B. Roggisch" wrote: > RTFM is the answer... I don't know. I remember scratching my head for a day or two over the module explanations and instructions until I found a little howto with a lot of explicite examples. http://pleac.sourceforge.net/pleac_python/datesandtimes.html rd From kw at codebykevin.com Mon Aug 6 13:49:37 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 06 Aug 2007 13:49:37 -0400 Subject: Tkinter or wxpython? In-Reply-To: <1186421115.402000.88080@x35g2000prf.googlegroups.com> References: <1186410331.905174.21370@q3g2000prf.googlegroups.com> <7xps204tin.fsf@ruckus.brouhaha.com> <46B73DE4.6040405@codebykevin.com> <1186421115.402000.88080@x35g2000prf.googlegroups.com> Message-ID: <46B75F31.9070208@codebykevin.com> kyosohma at gmail.com wrote: > > I tried the PMW widget toolkit. It was ok, but it seemed kind of > buggy. I found out about Tix on a forum of some sort. When I tried to > find out how to get it and use it, all I found was conflicting > information. I finally got it downloaded only to find I had to compile > it and I didn't have the right version of TCL. So I switched to > wxPython then. Months later I found out that Tix is now included with > Python. > > I still don't know how to use it though. As with most external Tkinter > widget sets, Tix doesn't have examples. The docs look less inviting > than man pages...but I realize that's probably just me. I just don't > like man pages much. Tkinter comes more naturally to me than other toolkits because I'm also a Tcl developer. I just haven't felt the need to learn wxPython because I can get what I need from Tkinter, even the more complicated GUI layouts. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From deets at nospam.web.de Tue Aug 14 09:23:36 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 14 Aug 2007 15:23:36 +0200 Subject: Class problems. References: <46c1a34a$0$54289$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <5idompF3o0crkU1@mid.uni-berlin.de> special_dragonfly wrote: > Hello, > I'm having problems retrieving data I think I've put into my program. I > have a class and a function. I'm reading in from a personally made text > file of the data needed for the class. The FieldsDictionary needs to be > accesable outside the function, but my problem is this: > the print FieldsDictionary[key].Fieldname (which I should have just > created because of the line above), returns: > AttributeError: 'list' object has no attribute 'Fieldname' > am I just accessing it wrongly? > I was under the impression that Fields Dictionary should contain a key > referencing to a list of instances of the class. i.e. > FieldsDictionary{key:[instance1, instance2, instance 3]} > Is this not what I've programmed? > > class FieldClass(object): > def > __init__(self,Fieldname="",Fieldlength=0,Type=["A","S","N"],Location=["D","C","L","H","TBA"]): > self.Fieldname=Fieldname > self.Fieldlength=Fieldlength > self.Type=Type > self.Location=Location > > def > EnterDictionary(FieldsDictionary,key,myfile,FIELD_QUANTITY_OFFSET,LINE_START,LINE_END): > data=myfile.readline().strip() > for i in range(int(data[FIELD_QUANTITY_OFFSET:])): > args =myfile.readline().strip()[LINE_START:LINE_END].split(",") > print args > FieldsDictionary.setdefault(key, []).append(FieldClass(*args)) Here you create a list or expect one, and append a new FieldClass-object to it. > print FieldsDictionary[key].Fieldname Here you access the LIST, but then expect it to be a FieldClass-object?!? print FieldsDictionary[key][-1].Fieldname will work. Diez From kbk at shore.net Sat Aug 4 01:26:32 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Sat, 4 Aug 2007 01:26:32 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200708040526.l745QWEW014541@hampton.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 404 open ( +5) / 3847 closed (+11) / 4251 total (+16) Bugs : 1059 open ( +3) / 6784 closed ( +8) / 7843 total (+11) RFE : 263 open ( +0) / 295 closed ( +1) / 558 total ( +1) New / Reopened Patches ______________________ struni: Fix test_aepack by converting 4cc's to bytes (2007-07-26) CLOSED http://python.org/sf/1761465 reopened by gvanrossum distutils.util.get_platform() return value on 64bit Windows (2007-07-27) http://python.org/sf/1761786 opened by Mark Hammond Some fix abount _WIN32_WINNT (2007-07-27) CLOSED http://python.org/sf/1761803 opened by Hirokazu Yamamoto struni: test_xml_etree.py (2007-07-27) CLOSED http://python.org/sf/1762412 opened by Joe Gregorio unable to serialize Infinity or NaN on ARM using marshal (2007-07-28) http://python.org/sf/1762561 opened by Matthias Klose struni: test_urllib2, test_cookielib (2007-07-29) CLOSED http://python.org/sf/1762940 opened by Joe Gregorio socket close fixed (2007-07-29) CLOSED http://python.org/sf/1763387 opened by Hasan Diwan tiny addition to peephole optimizer (2007-07-31) http://python.org/sf/1764087 opened by Paul Pogonyshev Fix for test_socketserver for Py3k (2007-07-31) CLOSED http://python.org/sf/1764815 opened by ??PC?? generic and more efficient removal of unreachable code (2007-08-01) http://python.org/sf/1764986 opened by Paul Pogonyshev logging: delay_fh option and configuration kwargs (2007-08-01) http://python.org/sf/1765140 opened by Chris Leary small improvement for peephole conditional jump optimizer (2007-08-01) http://python.org/sf/1765558 opened by Paul Pogonyshev urllib2-howto - correction (2007-08-02) http://python.org/sf/1765839 opened by O.R.Senthil Kumaran improve xrange.__contains__ (2007-08-02) http://python.org/sf/1766304 opened by Stargaming Fix for test_zipimport (2007-08-03) CLOSED http://python.org/sf/1766592 opened by ??PC?? Make xmlrpc use HTTP/1.1 and keepalive (2007-08-04) http://python.org/sf/1767370 opened by Donovan Baarda test_csv struni fixes + unicode support in _csv (2007-08-03) http://python.org/sf/1767398 opened by Adam Hupp Patches Closed ______________ struni: Fix test_aepack by converting 4cc's to bytes (2007-07-26) http://python.org/sf/1761465 closed by gvanrossum struni: Fix test_aepack by converting 4cc's to bytes (2007-07-26) http://python.org/sf/1761465 closed by gvanrossum Some fix abount _WIN32_WINNT (2007-07-27) http://python.org/sf/1761803 closed by mhammond struni pulldom: Don't use 'types' to check strings (2007-07-24) http://python.org/sf/1759922 closed by gvanrossum struni: test_xml_etree.py (2007-07-27) http://python.org/sf/1762412 closed by loewis struni: test_urllib2, test_cookielib (2007-07-28) http://python.org/sf/1762940 closed by gvanrossum socket close fixed (2007-07-30) http://python.org/sf/1763387 closed by facundobatista itertools.getitem() (2007-07-08) http://python.org/sf/1749857 closed by rhettinger Fix for test_socketserver for Py3k (2007-07-31) http://python.org/sf/1764815 closed by gvanrossum Fix Decimal.sqrt bugs described in #1725899 (2007-06-22) http://python.org/sf/1741308 closed by facundobatista Fix for test_zipimport (2007-08-03) http://python.org/sf/1766592 closed by gvanrossum urllib2 tests pass (2007-07-16) http://python.org/sf/1755133 closed by gvanrossum New / Reopened Bugs ___________________ 'exec' does not accept what 'open' returns (2007-07-28) http://python.org/sf/1762972 opened by Brett Cannon S.find documentation uses s[start, end] vs. s[start:end] (2007-07-29) CLOSED http://python.org/sf/1763149 opened by Rob copy 2 (2007-07-30) http://python.org/sf/1764044 opened by robs pythonid _RLock.__repr__ throws exception (2007-07-30) CLOSED http://python.org/sf/1764059 opened by Greg Kochanski The -m switch does not use the builtin __main__ module (2007-07-31) http://python.org/sf/1764407 opened by Nick Coghlan Decimal comparison with None fails in Windows (2007-07-31) CLOSED http://python.org/sf/1764761 opened by pablohoffman.com setup.py trashes LDFLAGS (2007-08-01) http://python.org/sf/1765375 opened by Harald Koenig poll() returns "status code", not "return code" (2007-08-02) http://python.org/sf/1766421 opened by sjbrown os.chmod failure (2007-08-03) http://python.org/sf/1767242 reopened by rgheck os.chmod failure (2007-08-03) http://python.org/sf/1767242 opened by Richard Heck String.capwords() does not capitalize first word (2007-08-03) http://python.org/sf/1767363 opened by Saatvik Agarwal Bugs Closed ___________ No docs for list comparison (2007-07-25) http://python.org/sf/1760423 closed by gbrandl SSL-ed sockets don't close correct? (2004-06-24) http://python.org/sf/978833 closed by loewis incorrect return value of unicodedata.lookup() - beoynd BMP (2007-04-21) http://python.org/sf/1704793 closed by loewis Thread.join() fails to release Lock on KeyboardInterrupt (2005-03-26) http://python.org/sf/1171023 closed by phansen S.find documentation uses s[start, end] vs. s[start:end] (2007-07-29) http://python.org/sf/1763149 closed by gbrandl _RLock.__repr__ throws exception (2007-07-31) http://python.org/sf/1764059 closed by ncoghlan Decimal comparison with None fails in Windows (2007-07-31) http://python.org/sf/1764761 closed by facundobatista decimal sqrt method doesn't use round-half-even (2007-05-25) http://python.org/sf/1725899 closed by facundobatista New / Reopened RFE __________________ add new bytecodes: JUMP_IF_{FALSE|TRUE}_AND_POP (2007-07-31) http://python.org/sf/1764638 opened by Paul Pogonyshev RFE Closed __________ add operator.fst and snd functions (2007-05-27) http://python.org/sf/1726697 closed by rhettinger From Jiandong.Ge at gmail.com Thu Aug 2 13:10:47 2007 From: Jiandong.Ge at gmail.com (JD) Date: Thu, 02 Aug 2007 17:10:47 -0000 Subject: File access In-Reply-To: <1186074042.024080.159420@e16g2000pri.googlegroups.com> References: <1186072898.405831.105670@e16g2000pri.googlegroups.com> <1186074042.024080.159420@e16g2000pri.googlegroups.com> Message-ID: <1186074647.074918.274820@z24g2000prh.googlegroups.com> Thanks for answering, No, the data was writing into the file when the subprocess was runing. For example, every second it will write something into the file. I tried to run another python program aside and it sucessfully read the file when the subprocess was runing. JD On Aug 2, 11:00 am, Adrian Petrescu wrote: > On Aug 2, 12:41 pm, JD wrote: > > > > > Hi, > > > What I am trying to do is to run a subprocess on another machine using > > subprocess.Popen, this subprocess contuinue writing something into a > > file when it is runing. > > > After submit this subprocess, I tried to open the file and readlines() > > in the loop (with a delay) in the loop) when the subprocess was > > runing. > > > The problem is I could not get anything untill the subprocess > > finished. > > > I also tried to run another python programm when the subprocess is > > runing, I could get what I want. > > > Does anyone know why? Thanks! > > > JD > > Could the problem be that the subprocess only flushes the output > buffer when it terminates, and so until the subprocess "finishes", as > you say, the file is empty because the data is still in the buffer? > Trying throwing some flushes into the code and see if it helps. > > Or am I misunderstanding your question? From evan at yelp.com Fri Aug 24 03:39:04 2007 From: evan at yelp.com (Evan Klitzke) Date: Fri, 24 Aug 2007 00:39:04 -0700 Subject: Co-developers wanted: document markup language In-Reply-To: <87odgyyx9u.fsf@wilson.homeunix.com> References: <87odgyyx9u.fsf@wilson.homeunix.com> Message-ID: On 8/23/07, Torsten Bronger wrote: > Hall?chen! > > Some LaTeX users in Aachen thought about a general-use markup > language this spring. I wrote some code and a rough project > description, however, we could need some help. > > If you are interested, visit the provisional project page at > http://latex-bronger.sourceforge.net/gummi/ > > Tsch?, > Torsten. I briefly looked over the specification, and it looks like you're targeting a LaTeX backend. Are you planning on outputting to LaTeX and using that to generate e.g. PDF versions of documents, or do you plan to have a real PDF/Postscript backend? -- Evan Klitzke From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Aug 28 10:59:44 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 28 Aug 2007 16:59:44 +0200 Subject: Check for dict key existence, and modify it in one step. In-Reply-To: <1188311810.226363.295500@w3g2000hsg.googlegroups.com> References: <1188311810.226363.295500@w3g2000hsg.googlegroups.com> Message-ID: <46d43860$0$428$426a74cc@news.free.fr> rodrigo a ?crit : > Im using this construct a lot: > > if dict.has_key(whatever): Avoid using builtin names as identifiers (it shadows the builtin name). Unless you're using an old Python version, you'd be better using if whatever in my_dict: # do something here > dict[whatever] += delta > else: > dict[whatever] = 1 > > sometimes even nested: > > if dict.has_key(whatever): > if dict[whatever].has_key(someother): > dict[whatever][someother] += delta > else: > dict[whatever][someother] = 1 > else: > dict[whatever]={} > dict[whatever][someother] = 1 > > there must be a more compact, readable and less redundant way to do > this, no? There are other ways, yes. With Python <= 2.4.x, you can use dict.setdefault, with Python 2.5.x you can use a defaultdict (cf http://docs.python.org/whatsnew/modules.html). HTH From jeff at jmcneil.net Mon Aug 13 06:49:26 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Mon, 13 Aug 2007 06:49:26 -0400 Subject: check if var is dict In-Reply-To: <46C02BFA.10703@al.com.au> References: <46C02BFA.10703@al.com.au> Message-ID: <82d28c40708130349h47792d52kdd6e23e9522c05f3@mail.gmail.com> You could use 'isinstance' to determine whether or not your object is an instance of a particular class. >>> isinstance({}, dict) True >>> isinstance("", basestring) True >>> Note the use of 'basestring', which will catch unicode as well. -Jeff On 8/13/07, Astan Chee wrote: > Hi, > I have a variable, I want to check if it is a dictionary or a string. > Is there any better way to do this than I've done. How I did it is by > doing a .items() and catching a AttributeError that it raises if its not > a dictionary. > How do i properly do it? > Thanks > Astan > -- > http://mail.python.org/mailman/listinfo/python-list > From python at jayloden.com Fri Aug 10 11:43:33 2007 From: python at jayloden.com (Jay Loden) Date: Fri, 10 Aug 2007 11:43:33 -0400 Subject: Issues of state In-Reply-To: References: <7x8x8mpn37.fsf@ruckus.brouhaha.com> <7xfy2t8l5n.fsf@ruckus.brouhaha.com> <5uhro4-st8.ln1@lairds.us> <5i2lk3F3m8h60U1@mid.individual.net> Message-ID: <46BC87A5.50405@jayloden.com> Steve Holden wrote: > greg wrote: >> Jay Loden wrote: >>> Like most things involving dynamic client side-javascript code and AJAX >>> technology, it's a lot harder than you'd like it to be to solve the problem, but >>> in cases where the Back button is really an issue, it's worth the effort. >> So if you're willing to put in a huge amount of time, >> effort and ingenuity, it's possible to overcome a >> problem that only existed in the first place because >> you chose an inappropriate technique for implementing >> a user interface... >> > Exactly my point. Once you start to involve a complex framework to > handle state and interactions you see less and less advantage to > "desktop web" applications, since it's hard to match the directness and > simplicity of a native GUI. This is true, you certainly won't get an argument from me! I've spent a lot of time explaining to people why a real-time GUI and the HTTP protocol don't get along. Event-driven programming using a request/response framework == square peg, round hole. But, it seems like the benefits of a web-based GUI make for a big hammer, so people keep pounding away at that square peg ;) On the negative side, developing any sort of non-trivial web application is fraught with problems: * language limitations of javascript/(X)HTML * highly varied implementations of CSS, HTML, js * browser-specific bugs (and features) * no real IDE to speak of * no way to receive events without some very ugly hacks or polling However, there are also major benefits, which is why you see so many companies and individuals jumping on the Web 2.0 train: * lower barrier of entry to creating a GUI (compare how quickly most people can turn out a form in HTML versus creating a GUI with the same entry fields) * cross-platform (yes, you have to support multiple browsers, but once you do, it works on the majority of platforms. For instance, support Firefox means OS X, Linux, Windows, etc all supported at once * Convenience for the end user - no need to install anything to use your software, which entices a lot more people to use it. This is less of a valid concern in an enterprise environment, but it still attracts people to feel they don't need to install something locally * available from multiple machines without extra effort for the user * Familiar interface (in most cases at least) to the user; more comfortable for them, less they need to learn. * Potentially available on many new platforms such as the iPhone, with some presentation tweaks. Good luck writing a cross-platform GUI app that runs on all the major OSes and mobile devices using a standard GUI toolkit etc. (or shipping the Python interpreter with an app intended for a Windows Mobile device, for instance) Your point is absolutely valid, though. I think the web 2.0 craze has people doing some things that just don't really make sense (like implementing Photoshop in a browser - what's next, AutoCAD?). The bottom line is that there are many many things that a native GUI is much better at and more than likely always will be. If you're developing an application, it's important to stop and ask yourself why it needs to be a web-based application, and unless you've got compelling reasons, the native GUI should win out. -Jay From aisaac at american.edu Thu Aug 30 17:29:59 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 30 Aug 2007 21:29:59 GMT Subject: create Powerpoint via com In-Reply-To: <1188500822.869925.194430@e9g2000prf.googlegroups.com> References: <1188500822.869925.194430@e9g2000prf.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > Hope that helps! Yes indeed. Thanks! Alan From wildemar at freakmail.de Fri Aug 24 06:14:09 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 24 Aug 2007 12:14:09 +0200 Subject: Co-developers wanted: document markup language In-Reply-To: <87mywh717i.fsf@wilson.homeunix.com> References: <87odgyyx9u.fsf@wilson.homeunix.com> <87tzqpew22.fsf@wilson.homeunix.com> <87tzqp77my.fsf@wilson.homeunix.com> <7xy7g1if24.fsf@ruckus.brouhaha.com> <87mywh717i.fsf@wilson.homeunix.com> Message-ID: <46CEAF71.3050900@freakmail.de> Torsten Bronger wrote: > Hall?chen! > > Yes, you're German. Have you ever noticed that (we) Germans are virtually the only ones that feel the need to rub our nationality into everyones faces? ;) > Paul Rubin writes > >> TeX/LateX have been around forever and are well established >> standards, as awful as they are. Why do we want ANOTHER markup >> language? >> > Well, because they are awful. ;-) I don't see that there is a > bunch of already existing projects, in fact, I don't see anyone > challenging LaTeX at all. However, competition is a good thing, and > I think there are enough aspects about LaTeX that can be done better > so that this project is worth being done. > Well there is ConTeXt . I've never actually used it, but from reading the docs I deem it a very attractive alternative to LaTeX. /W From slava.shklyar at gmail.com Tue Aug 28 15:12:42 2007 From: slava.shklyar at gmail.com (Slava) Date: Tue, 28 Aug 2007 19:12:42 -0000 Subject: Image manipulation Message-ID: <1188328362.992426.275780@19g2000hsx.googlegroups.com> I need to add dynamic text to animated GIF images. What is a best way to do it? Thanks. From greg at cosc.canterbury.ac.nz Fri Aug 10 05:14:23 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 10 Aug 2007 21:14:23 +1200 Subject: tempfile behavior In-Reply-To: <5i1b15F3kuhitU3@mid.uni-berlin.de> References: <1186683707.869668.316360@g4g2000hsf.googlegroups.com> <1186684291.629191.185070@z24g2000prh.googlegroups.com> <1186688830.051531.13560@z24g2000prh.googlegroups.com> <5i1b15F3kuhitU3@mid.uni-berlin.de> Message-ID: <5i2oqkF3mpgh8U1@mid.individual.net> Marc 'BlackJack' Rintsch wrote: > File descriptors are integers. It's a low level C thing. Either use the > low level functions in `os` or open the file with the `filename`. In particular, os.fdopen(fd) will give you a file object. -- Greg From ladynikon at gmail.com Fri Aug 3 23:08:42 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Fri, 3 Aug 2007 23:08:42 -0400 Subject: I am giving up perl because of assholes on clpm -- switching to Python In-Reply-To: <46aa1986$0$31715$db0fefd9@news.zen.co.uk> References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> <7x4pjq7v69.fsf@ruckus.brouhaha.com> <46aa1986$0$31715$db0fefd9@news.zen.co.uk> Message-ID: <59f9c5160708032008o664def93jefa2186f1111ce2c@mail.gmail.com> In most of the technical computer newsgroups which I frequent, there is a handful of knowledgeable and helpful but irritable regulars, and often one or two saints who contribute usefully, ignore rudeness and almost never post off topic. Ain't that the truth!! You will find rudeness everywhere you go. If you really like the language. Don't let party poopers spoil your fun. Always demand respect. But if you don't get it.. it is not the end of the world. I have also learned that text has little emotion. I have actually had to pull some people aside as ask them about a post directed towards me. From mccredie at gmail.com Fri Aug 10 16:52:32 2007 From: mccredie at gmail.com (Matt McCredie) Date: Fri, 10 Aug 2007 13:52:32 -0700 Subject: Fwd: AttributeError: 'module' object has no attribute 'HTTPSHandler' In-Reply-To: <9e95df10708101153j74eb6431kd216503ab6c770ae@mail.gmail.com> References: <9e95df10708101153j74eb6431kd216503ab6c770ae@mail.gmail.com> Message-ID: <9e95df10708101352h45076f1cm36550126b1b548e3@mail.gmail.com> > I built and installed python 2.5 from source and when I do this: > > opener = urllib2.build_opener(SmartRedirectHandler(), > DefaultErrorHandler(), urllib2.HTTPSHandler()) > > I get this error. > AttributeError: 'module' object has no attribute 'HTTPSHandler' > > What should I do? You need `_ssl.pyd' for HTTPSHandler to work. I guess, try to figure out why that wasn't built, then build it. I suppose I _might_ be able to give a little more help, but you haven't mentioned what platform you are using. Even then, I'm not an expert on building Python. Matt From steve at REMOVE.THIS.cybersource.com.au Fri Aug 3 10:24:24 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 04 Aug 2007 00:24:24 +1000 Subject: (no) fast boolean evaluation ? References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> <46b2e56b$0$18879$426a74cc@news.free.fr> Message-ID: On Fri, 03 Aug 2007 10:20:59 +0200, Bruno Desthuilliers wrote: > Joshua J. Kugler a ?crit : >> On Thursday 02 August 2007 15:19, Evan Klitzke wrote: >>>> I discovered that boolean evaluation in Python is done "fast" >>>> (as soon as the condition is ok, the rest of the expression is ignored). >>> This is standard behavior in every language I've ever encountered. >> >> Then you've never programmed in VB (at least 6, don't know if .net still >> does this). Nested IF statements. AAAAAAAAAAAAAAAAAAAACK! > > I do remember an even brain-deadiest language that not only didn't > short-circuit boolean operators but also didn't have an "elif" statement... Is it a secret? I'm a little perplexed at why you say a language without "elif" is a good sign of brain-death in a programming language. I understand that, given the parsing rules of Python, it is better to use elif than the equivalent: if condition: pass else: if another_condition: pass But that's specific to the syntax of the language. You could, if you choose, design a language where elif was unnecessary: if condition: pass else if another_condition: pass What advantage is there to "elif", apart from it needing three fewer characters to type? -- Steven. From bj_666 at gmx.net Thu Aug 9 16:16:38 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Aug 2007 20:16:38 GMT Subject: tempfile behavior References: <1186683707.869668.316360@g4g2000hsf.googlegroups.com> <1186684291.629191.185070@z24g2000prh.googlegroups.com> <1186688830.051531.13560@z24g2000prh.googlegroups.com> Message-ID: <5i1b15F3kuhitU3@mid.uni-berlin.de> On Thu, 09 Aug 2007 12:47:10 -0700, billiejoex wrote: >>>> fd, filename = tempfile.mkstemp() >>>> type(fd) > > > I would expect a file descriptor, not and integer. > How do I have to use it? File descriptors are integers. It's a low level C thing. Either use the low level functions in `os` or open the file with the `filename`. Ciao, Marc 'BlackJack' Rintsch From hat at se-162.se.wtb.tue.nl Thu Aug 16 02:47:57 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 16 Aug 2007 08:47:57 +0200 Subject: Who told str() to round my int()'s!!! References: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> <9qmvi.47364$s5.1537219@phobos.telenet-ops.be> <3ZudnUuJ68lcxl7bnZ2dnUVZ_t_inZ2d@comcast.com> Message-ID: On 2007-08-15, Larry Bates wrote: > > What are they teaching in schools these days? I see questions like this and the > equally perplexing "why don't floats represent numbers exactly?" or the mildy > amusing "how do I write bytes not characters to a file" questions at least once > a week on this forum. Who says that schools teach that to every body? Python is a popular language, so there are a lot non-cs people here. I can imagine that eg a user with a background in history or geography has never encountered these things before. (Python got to start programming, and now they suddenly have to deal with inaccurate floats of the otherwise so precise computer :-) ) Albert From michele.petrazzo at TOGLIunipex.it Wed Aug 1 13:48:09 2007 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Wed, 01 Aug 2007 19:48:09 +0200 Subject: Strange problems with subprocess In-Reply-To: <1185973082.899736.247300@i13g2000prf.googlegroups.com> References: <1185973082.899736.247300@i13g2000prf.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > This doesn't look like a complete traceback. It doesn't give what the > error was. > Forgot a line, sorry! exceptions.OSError: [Errno 4] Interrupted system call > Mike > Michele From byte8bits at gmail.com Mon Aug 13 13:00:42 2007 From: byte8bits at gmail.com (brad) Date: Mon, 13 Aug 2007 13:00:42 -0400 Subject: Assignments and Variable Substitution Message-ID: I'd like to do something like this: var = '123' %s = [], %var So that, in the end, var is '123' and an empty list is named '123' as well. The list assignments are created during a loop. Thanks, Brad From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Aug 14 16:21:49 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 14 Aug 2007 22:21:49 +0200 Subject: wxPython before MainLoop References: <13bl9a75laqcm70@corp.supernews.com> <13bnh5bs4b9h427@corp.supernews.com> <5i3b1jF3n5bdtU1@mid.individual.net> <13c1v79hs0dob3@corp.supernews.com> Message-ID: <5ieh6uF3oc4jqU1@mid.individual.net> [david] wrote: > Well yes, I have tried this app with native windows, > and I know how to do it. Then I wonder why you complained about concurrency problems (solved by using a worker thread, or using wx.Yield) in the first place. Windows has the same solutions, just as about every GUI framework. http://msdn2.microsoft.com/en-us/library/69644x60(VS.80).aspx > But if all wxPython can offer is a poor imitation of MFC, >From what did you conclude this? As already stated, almost ALL GUI toolkits available function in a similar way (using an event loop). To say that every such toolkit was just an imitation of MFC is quite childish, IMHO. Same niveau would be to say that all other cars are poor imitations of Ford cars because they all have four wheels. > I'm better off using MFC aren't I? That depends on your demands. If you don't want it cross platform you may be right, especially if you require very special Windows features. > And too all those people who wrote back to insist > that users MUST explicitly build a multi-threaded > framework for wxPython: Could you please cite one posting where this is claimed? I can't find this claim. > It's supposed to already be a framework :~) wxWidgets _has_ cross-platform threads implemented on its own: http://www.wxwidgets.org/manuals/stable/wx_wxthread.html#wxthread It has just been dropped from wxPython because cross-platform threads are already part of the Python library. C++, the basis for wxWidgets, has no multithreading support in STL. Regards, Bj?rn -- BOFH excuse #61: not approved by the FCC From bdesth.quelquechose at free.quelquepart.fr Mon Aug 6 02:26:49 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 06 Aug 2007 08:26:49 +0200 Subject: Adding a list of descriptors to a class In-Reply-To: <1186503932.110835.293640@x40g2000prg.googlegroups.com> References: <1186503932.110835.293640@x40g2000prg.googlegroups.com> Message-ID: <46b8d2f3$0$25354$426a74cc@news.free.fr> Bob B. a ?crit : > I've been playing with descriptors lately. I'm having one problem I > can't seem to find the answer to. I want to assign a descriptor to a > list of attributes. I know I should be able to add these somewhere in > the class's __dict__, but I can't figure out where. Here's some code: > > class MyDesc(object): > def __init__(self, name=None, initVal=None): > self.name = name > self.value = initVal > > def __get__(self, obj, objtype): > // Do some stuff > self.value = "blah" > return self.value > > class MyClass(object): > attributes = ('attr1', 'attr2') > for attr in attributes: > exec ("%s=MyDesc('%s')") % (attr, attr) > > // More stuff in the class > > Ok, that "exec" is an ugly hack. There's gotta be someway to plop > this straight into the class's __dict__ without doing that, but when I > try adding self.__class__.__dict__[attr] = MyDesc(attr) in MyClass's > __init__ method, I get the error: "TypeError: 'dictproxy' object does > not support item assignment" > > Any ideas? Steven already show you the simplest solution. Now if you want something "cleaner" (or at least more transparent to persons subclassing MyClass - which may or may not be a concern), you can use metaclasses too: class MyDesc(object): def __init__(self, name=None, initVal=None): self.name = name self.value = initVal def __get__(self, obj, objtype): # Do some stuff #self.value = "blah" if obj is None: return self return self.value class MyType(type): def __init__(cls, name, bases, dic): attributes = dic.get('attributes', None) if attributes is not None: for attrname, initval in attributes.iteritems(): setattr(cls, attrname, MyDesc(attrname, initval)) class MyClass(object): __metaclass__ = MyType attributes = dict(attr1="attr1", attr2="attr2") class MySubclass(MyClass): # let you override parent's attributes... attributes = dict(attr1="otherattr1", attr3="a new one") HTH From almadhu at gmail.com Sat Aug 11 23:59:54 2007 From: almadhu at gmail.com (Madhu Alagu) Date: Sun, 12 Aug 2007 03:59:54 -0000 Subject: Web based Reporting tool for Python In-Reply-To: <2007080808575016807-jon@turnthepageorg> References: <1186460956.945148.162610@k79g2000hse.googlegroups.com> <1186547726.383996.291360@d55g2000hsg.googlegroups.com> <2007080808575016807-jon@turnthepageorg> Message-ID: <1186891194.582444.222010@r34g2000hsd.googlegroups.com> On Aug 8, 4:57 pm, Jon Rosebaugh wrote: > On 2007-08-07 23:35:26 -0500, Madhu Alagu said: > > > Thanking so much for all the informations and links.I would like to > > use Mako Templates(www.makotemplates.org).Ilike to use simple and > > python default module... > > Mako is an excellent template system, but you'll have a lot of work to > do making it into a reporting system. Any reporting template in python ? From horpner at yahoo.com Thu Aug 16 11:59:33 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 16 Aug 2007 15:59:33 GMT Subject: A problem with Time References: <46c469be$0$66145$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: On 2007-08-16, Shawn Milochik wrote: > import time > > > oneDay = 60 * 60 * 24 #seconds in one day > > date = time.time() > > yesterday = date - oneDay Or use a timedelta. >>> import datetime >>> yesterday = datetime.datetime.today() - datetime.timedelta(days=1) >>> yesterday.strftime('%m%d%Y') '08152007' -- Neil Cerutti It might take a season, it might take half a season, it might take a year. --Elgin Baylor From http Wed Aug 8 02:17:00 2007 From: http (Paul Rubin) Date: 07 Aug 2007 23:17:00 -0700 Subject: Issues of state (was: Tkinter or wxpython?) References: <7x3aywr4tc.fsf@ruckus.brouhaha.com> Message-ID: <7x8x8mpn37.fsf@ruckus.brouhaha.com> claird at lairds.us (Cameron Laird) writes: > >application in the web app model (I haven't even touched on the whole > >stateless HTTP being mapped to a stateful environment issue, or the > >need to manage the local web server) actually buys you anything. I > . > Go ahead: touch on statefulness. I've been pondering the topic > lately, and wonder what's new on the subject. I find it plenty > difficult to cast this as anything but a big liability for the > Web app team. I'm not sure what you're getting at in this context. You can write a desktop app where the window system communicates with a gui toolkit through a socket (at least that's how X windows works), or you can write a web app where a browser communicates with an http listener through a socket. What's the difference, as far as application state is concerned? I haven't used wxpython but for tkinter you'd typically have a gui event loop in its own thread, communicating with the application through queues. Similarly you can use BaseHTTPServer to collect browser hits and get the data out of them with the cgi module functions before passing them to the app. If you want to handle multiple concurrent users you get into the usual issues of web servers, but if you're just doing a single user web implementation as an alternative to a desktop gui, some rudimentary locking is probably enough to stop accidental simultaneous connections. If the application is simple enough, you can just write it as a cgi and keep the state in disk files. From askme at ask.me Wed Aug 8 18:34:14 2007 From: askme at ask.me (Bill Sornson) Date: Wed, 8 Aug 2007 15:34:14 -0700 Subject: Google Conspiracy Revealed! References: <1186600125.435154.68910@m37g2000prh.googlegroups.com> Message-ID: <46ba44e6$0$28622$4c368faf@roadrunner.com> conspiracy.black3 at gmail.com wrote: > http://www.nasaconspiracy.net/2007/06/content-generator-recognizing-generated.html > - Amazing Google Conspiracies Revealed from CIA, NSA and Government > conspiracies and Dr.Kevorkians magic pills. Ironically, forwarded to Gmail Abuse -- E-mail Address(es): abuse at gmail.com. Tasty... From http Thu Aug 16 04:37:22 2007 From: http (Paul Rubin) Date: 16 Aug 2007 01:37:22 -0700 Subject: python socket usage References: <1187250839.541105.60900@r29g2000hsg.googlegroups.com> Message-ID: <7xabsrnad9.fsf@ruckus.brouhaha.com> Gary Herron writes: > be able to recover the original object accurately. Worse yet, an eval > of an arbitrary string is a HUGE security hole. > > If you really want to send any Python object through a socket, look up > the Pickle and cPickle modules. These are also security holes. From SMERSH009X at gmail.com Sat Aug 4 19:35:55 2007 From: SMERSH009X at gmail.com (SMERSH009) Date: Sat, 04 Aug 2007 23:35:55 -0000 Subject: Formatting Results so that They Can be Nicely Imported into a Spreadsheet. Message-ID: <1186270555.514649.311280@d30g2000prg.googlegroups.com> Hi All. Let's say I have some badly formatted text called doc: doc= """ friendid Female 23 years old Los Gatos United States friendid Male 24 years old San Francisco, California United States """ How would I get these results to be displayed in a format similar to: friendid;Female;23 years old;Los Gatos;United States friendid;Male; 24 years old;San Francisco, California;United States The latter is a lot easier to organize and can be quickly imported into Excel's column format. Thanks Much, Sam From zyzhu2000 at gmail.com Thu Aug 16 20:53:19 2007 From: zyzhu2000 at gmail.com (beginner) Date: Fri, 17 Aug 2007 00:53:19 -0000 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> Message-ID: <1187311999.880853.135780@j4g2000prf.googlegroups.com> On Aug 16, 6:21 pm, James Stroud wrote: > beginner wrote: > > Hi All. > > > I'd like to do the following in more succint code: > > > if k in b: > > a=b[k] > > else: > > a={} > > b[k]=a > > > a['A']=1 > > > In perl it is just one line: $a=$b->{"A"} ||={}. > > I'm afraid you've asked a non sequiter: > > euler 40% cat test.pl > > $a=$b->{"A"} ||={} ; > print "$a\n" ; > > $b->{"B"} = 0 ; > $a=$b->{"B"} ||={} ; > print "$a\n" ; > > $b->{"X"} = 15 ; > $a=$b->{"X"} ||={} ; > print "$a\n" ; > > euler 41% perl test.pl > HASH(0x92662a0) > HASH(0x926609c) > 15 > > James > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ It is not supposed to be used this way. $b is supposed to be a hash-table of hash-table. If a key exists in $b, it points to another hash table. The $a=$b->{"A"} ||={} pattern is useful when you want to add records to the double hash table. For example, if you have a series of records in the format of (K1, K2, V), and you want to add them to the double hash-table, you can do $a=$b->{K1} || ={} $a->{K2}=V From conra2004 at yahoo.com Tue Aug 14 12:05:13 2007 From: conra2004 at yahoo.com (yadin) Date: Tue, 14 Aug 2007 09:05:13 -0700 Subject: negative values on polar plot (decibels polar plots ) Message-ID: <1187107513.354637.228830@w3g2000hsg.googlegroups.com> hi every one can you please can you help me to fix these polar plot in db's so that the center is at the minimun negative number in voltagedb about [-50] and the maximun is at zero how can i see values on the axies like showing that the axes start at -40 -30 .....0 than you import wx import os from wx.lib.colourdb import * from pylab import* angteta = [ 4.36332313e-003, 3.18522588e-001, 6.32681854e-001, 9.46841119e-001, 1.26100038e+000, 1.57515965e+000, 1.88931892e+000, 2.20347818e+000, 2.51763745e+000, 2.83179671e+000, 3.14595598e+000, 3.46011524e+000, 3.77427451e+000, 4.08843377e+000, 4.40259304e+000, 4.71675230e+000, 5.03091157e+000, 5.34507083e+000, 5.65923010e+000, 5.97338936e+000,] voltage = [ 0.00363471, 0.26569155, 0.52562334, 0.76330428, 0.93673361, 1. , 0.93321713, 0.75733232, 0.5185449 , 0.25840091, 0.00363471, 0.26569155, 0.52562334, 0.76330428, 0.93673361, 1. , 0.93321713, 0.75733232, 0.5185449 , 0.25840091,] #voltagedb = 20*log10(voltage) voltagedb = [-48.7906044 ,-11.51244516, -5.58650713, -2.34604603, -0.56767793, 0. , -0.60034598, -2.41427014, -5.7042726 ,-11.75411924,-48.7906044 , -11.51244516, -5.58650713, -2.34604603, -0.56767793, 0. , -0.60034598, -2.41427014, -5.7042726 ,-11.75411924,] polar(angteta,voltagedb) show() From gtcopeland at gmail.com Tue Aug 21 09:09:12 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: Tue, 21 Aug 2007 06:09:12 -0700 Subject: Python project solicitation In-Reply-To: References: Message-ID: <1187701752.661991.144690@q3g2000prf.googlegroups.com> On Aug 20, 9:35 pm, JoeSox wrote: > I must say this thing is pretty cool. I had a coworker try it out and > he ran into problems getting it to run on his Linux OS. So I am > really looking for some non-Windows developers to take a look at it. > All of the info is at the project site above. > Thanks. > I looked at it real quick. You need to use os.path.join for your file paths. You also need to use sys.platform for windows specific processing. For example: if sys.platform == 'Win32': FS_ROOT = 'C:' else: FS_ROOT = '/' WORDNETPATH=os.path.join( FS_ROOT, 'WordNet', '2.1', 'dict' ) So on and so on. You wrote it very MSWin centric so it is not a surprise it has trouble of on other platforms. All of your file references need to be adjusted as above using os.path.join. Keep in mind I only looked at it real quick. Those appear to be the cross platform deal killers. Short of something I missed (could have), it should work find on most any other platform once you take out the Windows-isms. Greg From gslindstrom at gmail.com Wed Aug 15 08:03:11 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Wed, 15 Aug 2007 07:03:11 -0500 Subject: PyCon 2008 - Call for Tutorial Ideas Message-ID: It's hard to believe, but the planning for PyCon 2008 is underway. PyCon, an annual gathering of Python enthusiasts -- nearly 600 in Dallas last year -- will be held in Chicago next March 14-16, with one full "pre-conference" day, March 13, set aside for tutorials; classes given by Python honchos on various topics. These sessions last 3 hours (plus a break) and in general are more detailed than the talks given during the actual conference. Right now, we need to know what YOU want to see covered in these sessions. Testing, GUI, web-apps, database, basic Python, advanced Python, objects, anything and everything Python is on the table at this point. We have to narrow the field down to 10 or 15 and then find qualified presenters, so now is the time to start gathering ideas. What tutorials would you like to see offered? Please response to: pycon-tutorials at python.org Thanks, Greg Lindstrom Tutorial Coordinator, PyCon 2008 -------------- next part -------------- An HTML attachment was scrubbed... URL: From rcdailey at gmail.com Mon Aug 20 17:01:12 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 20 Aug 2007 16:01:12 -0500 Subject: datetime in microseconds In-Reply-To: <1187621922.387688.77090@50g2000hsm.googlegroups.com> References: <1187610776.755796.170990@r29g2000hsg.googlegroups.com> <1187615746.655162.295570@z24g2000prh.googlegroups.com> <1187619423.715120.293660@o80g2000hse.googlegroups.com> <1187621922.387688.77090@50g2000hsm.googlegroups.com> Message-ID: <496954360708201401p2ffcc37fjc24aabfb95224ec2@mail.gmail.com> A small off topic question. Why use divmod() instead of the modulus operator? On 8/20/07, mroeloffs at gmail.com wrote: > > On Aug 20, 4:17 pm, mroelo... at gmail.com wrote: > > On Aug 20, 3:15 pm, John Machin wrote: > > > > > > > > > On Aug 20, 9:52 pm, mroelo... at gmail.com wrote: > > > > > > Hi I have a time in microseconds, for example 0x8C905CBA7F84AF4. I > > > > want this to a normal view in hh:mm:ss DD:MM:YYYY. I tried with > > > > datetime, but it only takes a max of 1000000 microseconds is there > > > > another solution? > > > > > Your question can be interpreted in two possible ways: > > > > > 1. You have an interval or duration (independent of a calendar point) > > > and you want to express it in years, months, days, hours, etc. This is > > > not possible, due to the variable number of days in a month. The best > > > that you can do is express it as days, hours, etc. > > > > > >>> microsecs = 0x8C905CBA7F84AF4 > > > >>> secs = microsecs // 1000000 # or round to nearest if you prefer > > > >>> mins, secs = divmod(secs, 60) > > > >>> hrs, mins = divmod(mins, 60) > > > >>> days, hrs = divmod(hrs, 24) > > > >>> days, hrs, mins, secs > > > > > (7326893L, 11L, 1L, 16L) > > > > > 2. You want to know the (Gregorian) calendar point that is > > > 0x8C905CBA7F84AF4 microseconds after some epoch. In this case you need > > > to specify what the epoch is. Then you can try something like: > > > > > >>> datetime.datetime.fromordinal(1) + datetime.timedelta > (microseconds=microsecs > > > > > ) > > > Traceback (most recent call last): > > > File "", line 1, in > > > OverflowError: date value out of range > > > > > >>> # Whoops! > > > >>> years_approx = days / 365.25 > > > >>> years_approx > > > 20059.939767282682 > > > > > Hmmm, one of us seems to be missing something ... > > > > Sorry, sorry, sorry it was the wrong value, it should be > > 0xE0E6FAC3FF3AB2. > > The solution I made, with thanks to John. Maybe someone a better one?? > def DecodeDateTime(self,dateTime): > dateTime = self.Rotate(dateTime) > microsecs = int(hexlify(dateTime),16) > microsecs -= 31536000000000 # -1 Year > microsecs -= 1123200000000 # -13 Days (magic?) > secs = microsecs // 1000000 > mins, secs = divmod(secs, 60) > hrs, mins = divmod(mins, 60) > days, hrs = divmod(hrs, 24) > timed = datetime.datetime.fromordinal(1) + > datetime.timedelta(days) > return "%02d-%02d-%02d %02d:%02d:%02d"%(timed.day, > timed.month, timed.year, hrs, mins, secs) > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cool.vimalsmail at gmail.com Thu Aug 2 05:31:43 2007 From: cool.vimalsmail at gmail.com (cool.vimalsmail at gmail.com) Date: Thu, 02 Aug 2007 09:31:43 -0000 Subject: i am new to python-Please somebody help Message-ID: <1186047103.673871.150460@z24g2000prh.googlegroups.com> i dont know how to convert a txt file into a zip file (i.e.,)i have a file named packages and i want the packages file with a ".gz" extension by implementing a python program From http Mon Aug 20 11:18:03 2007 From: http (Paul Rubin) Date: 20 Aug 2007 08:18:03 -0700 Subject: clarification References: <13cb7frnqs8f6d9@corp.supernews.com> <1i31aop.2ing3h1hcfz0dN%aleax@mac.com> <1i332et.1rcnw4e1f97a5kN%aleax@mac.com> Message-ID: <7xk5rq9qvo.fsf@ruckus.brouhaha.com> aleax at mac.com (Alex Martelli) writes: > > turn indicates that both implementations actually work about same and > > your "O(n squared)" argument is irrelevant. > > It's indeed irrelevant when the behavior _isn't_ quadratic (as in the > case of intersections) -- but unfortunately it _is_ needlessly quadratic > in most interesting cases involving containers (catenation of sequences, > union of sets, merging of dictionaries, merging of priority-queues, > ...), because in those cases the intermediate temporary values tend to > grow, as I tried to explain in more detail above. Mostly directed to samwyse: Alex is correct here and I'd add that Python and its libraries are written for an imperative, mutating approach though there are some situations in which you can write in functional style without a big efficiency hit. In particular, the quadratic behavior Alex points out is because of Python's hash-based implementation of sets, so you can't make a new set that adds or removes one element from the old set, without copying all the elements around. A more purist functional approach would probably implement sets with some other data structure such as AVL trees, so you can make a new one that adds or deletes some node in O(log n) time (it would share almost all of its structure with the old one). So instead of O(n) for the hash-based mutating implementation or O(n**2) for the hash/copying based functional implementation, you get O(n log n) for the functional tree implementation. Haskell's Data.Map module does something like this. There's a book "Purely Functional Data Structures" by Chris Okasaki that shows how to implement dicts, priority queues, and fancier objects in functional style based on similar principles. If you want to try out functional programming in a lightweight language (much easier to grok than Haskell) you might look at Hedgehog Lisp: http://hedgehog.oliotalo.fi/ It includes a functional dictionary implementation based on AVL trees but with a Python dictionary-like API. From llasram at gmail.com Thu Aug 30 09:53:53 2007 From: llasram at gmail.com (Marshall T. Vandegrift) Date: Thu, 30 Aug 2007 09:53:53 -0400 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> Message-ID: <87bqcp2kni.fsf@seneca.iss.local> zzbbaadd at aol.com writes: > What's with the index() function of lists throwing an exception on not > found? Let's hope this is rectified in Python 3. If nothing else, add > a function that doesn't throw an exception. There are a million > situations where you can have an item not be in a list and it is not > an exception situation. The Python string types have both the method `index()` which throws an exception and the method `find()` which implements the same behavior but returns -1 for not-found substrings. I would naively have assumed the `list` type to provide both as well, but it provides only `index()`. Anyone know the reason for this lack of parallelism? -Marshall From gherron at islandtraining.com Sun Aug 19 13:10:07 2007 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 19 Aug 2007 10:10:07 -0700 Subject: "Variable variable name" or "variable lvalue" In-Reply-To: <1187541583.607550.107230@57g2000hsv.googlegroups.com> References: <1187199722.618893.281170@r29g2000hsg.googlegroups.com> <1187541583.607550.107230@57g2000hsv.googlegroups.com> Message-ID: <46C8796F.8090505@islandtraining.com> inmmike at gmail.com wrote: > On Aug 15, 1:42 pm, mfglinux wrote: > >> Hello to everybody >> >> I would like to know how to declare in python a "variable name" that >> it is in turn a variable >> In bash shell I would wrote sthg like: >> >> for x in `seq 1 3` >> do >> M$i=Material(x) #Material is a python class >> done >> >> Why I need this? Cause I have a python module that obliges me to build >> a variable called Period, which should have a variable name of >> summands (depends on the value of x) >> >> #Let's say x=3, then Period definition is >> Period=Slab(Material1(12.5)+Material2(25)+Material3(12.5)) #Slab is a >> python class >> >> I dont know how to automatize last piece of code for any x >> >> thank you >> >> Marcos >> > > Regardless of whether or not this is a "best practice" sometimes it is > necessary. For example, I am looping through a dictionary to set some > class properties. Anyway, here is what I finally came up with: > > exec "self.%s = '%s'" % (item, plist[item]) > Yuck! Not at all necessary. Use setattr instead: setattr(self, item, plist[item]) That's much cleaner then an exec or eval. You may also find getattr and hasattr useful. Gary Herron > A more simple example for setting a variable outside of a class... > > exec '%s = '%s'" % ('variableName', 'variable value') > > Cheers! > Mike > > From kevin.t.ryan at gmail.com Tue Aug 28 14:09:58 2007 From: kevin.t.ryan at gmail.com (Kevin T. Ryan) Date: Tue, 28 Aug 2007 18:09:58 -0000 Subject: Compiling Source with alternate Openssl lib Message-ID: <1188324598.687927.169350@d55g2000hsg.googlegroups.com> Hi All - I'm trying to compile Python on a Centos machine (RHEL) 3.8 for a hosting account that I just set up and I'm having 2 issues: 1. I ran into an issue with the "hashlib" module [I think] because it bumps it up against an *OLD* openssl lib (like, Feb. 2003). So I installed a newer openssl lib, but when I recompiled python it still used the old library. So I tried ./configure again with the flag: "- with-openssl-libs=/new/directory" but it still didn't work. Any idea how I might be able to remedy this? I have a working solution right now: I've commented out the last 2 lines of hashlib.py, but I'd rather not do that if I didn't have to. 2. As part of this process, I installed "easy_install" and I was trying to download psycopg2 but I got the error: "PyDateTimeAPI defined but not used" when trying to compile. I've had this problem before when trying to compile psycopg2 and it was because I didn't have the postgres header libs installed (libpq-dev) ... but that's on a debian box, and I can't figure out how to fix it on the RHEL one. I know the 2nd question might not belong in this group, but I thought I'd ask just in case someone ran into this before or might have any suggestions. Thanks in advance (as always!) for your help! Kevin From ldo at geek-central.gen.new_zealand Mon Aug 27 05:27:56 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 27 Aug 2007 21:27:56 +1200 Subject: pySerial in a daemon process References: <1188158581.316824.89360@k79g2000hse.googlegroups.com> <5je954F3s0nilU1@mid.individual.net> <1188166098.738058.182580@w3g2000hsg.googlegroups.com> Message-ID: In message <1188166098.738058.182580 at w3g2000hsg.googlegroups.com>, paul wrote: > Before I had posted this question first thing I did was to look at / > dev/ttyS0, and indeed the group is dialout (gid=20)... What are the full protections on the serial port? That is, can you post the output of ls -l /dev/ttyS0 please? From semanticist at gmail.com Wed Aug 15 10:35:16 2007 From: semanticist at gmail.com (Miles) Date: Wed, 15 Aug 2007 10:35:16 -0400 Subject: What order does info get returned in by os.listdir() In-Reply-To: References: <5igd1gF3mc1akU1@mid.uni-berlin.de> Message-ID: On 8/15/07, Jeremy C B Nicoll wrote: > Marc 'BlackJack' Rintsch wrote: > > > How would I sort leaflist in a way that mimics the sort order that XP > > > shows me things under? > > > > This depends on what XP is. Which program? Which locale? How does the > > locale influence that programs sorting? > > Well... XP is Windows XP (Pro as I think I said earlier), and I'm in the UK. > I explained earlier how XP shows me stuff in order when I tell it to sort by > name. Case insensitive sort with ~ coming before all other characters: some_list.sort(key=lambda k: k.lower().split("~")) From arkanes at gmail.com Wed Aug 1 10:40:28 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 1 Aug 2007 09:40:28 -0500 Subject: zip() function troubles In-Reply-To: <7xps28s5wm.fsf@ruckus.brouhaha.com> References: <1185492336.850090.279190@b79g2000hse.googlegroups.com> <7xfy3ae4lb.fsf@ruckus.brouhaha.com> <7xps28s5wm.fsf@ruckus.brouhaha.com> Message-ID: <4866bea60708010740l1d005751h38564463d30d9dd3@mail.gmail.com> On 31 Jul 2007 12:57:13 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > "Chris Mellon" writes: > > Better hand in your computer, then. You're never going to find a > > situation where the environment won't affect the running time of your > > algorithms. > > The environment may affect the running time by an additive or linear > multiplicative constant but it should never turn an O(n) algorithm > into an O(n**2) one. > Hardly true. When you start to factor real world issues like memory allocations (and all the complexities thereof) and cache misses into algorithmic performance an algorithm certainly can change from O(n) to O(n**2). This is one reason why real world performance is tested and compared using benchmarks and not Big O notation. > > For the record, the python GC is generational. This is a case of a > > default heuristic giving pathological behavior in a corner case, not > > anything broken about the design of the python GC. > > No, it is broken, per discussion on a > comp.compilers/comp.lang.functional thread this week. The notion of > using a generational collector was to collect less and less frequently > for older and older generations (e.g. doubling the amount of > allocation between generations) but the usual solution is apparently > to increase the heap size by some multiplicative factor when GC fails > to free enough memory. > -- The issue at hand has nothing to do with the generational nature of the Python GC. It's caused by a heuristic that aggressively attempts to reclaim objects when there are large numbers of allocations without releases. This is a tuneable GC parameter. From kalita at poczta.onet.pl Fri Aug 17 18:27:06 2007 From: kalita at poczta.onet.pl (Marcin Kalicinski) Date: Fri, 17 Aug 2007 23:27:06 +0100 Subject: wxPython in C++ app using wxWidgets Message-ID: I have an application written in C++ that uses wxWidgets for GUI. I use embedded Python for scripting inside of this application. I want to use wxPython to add GUI to my scripts - because my C++ App uses wxWidgets I thought it to be easy. The problem is that wxPython knows nothing about wxApp/wxFrame objects created in my C++ application, and insists (by giving me asserts) that I create another wxApp object for wxPython inside my scripts. Obviously, this is not what I want. I want the scripts to use the same wxApp/wxFrame object that my C++ application already created. More specifically, I want to create dialogs in wxPython that will have my application wxFrame as parent. I'm stuck. Any help appreciated. Thanks, M. From jcarlson at uci.edu Sun Aug 26 12:25:35 2007 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 26 Aug 2007 09:25:35 -0700 Subject: ANN: PyPE 2.8.6 Message-ID: <20070826092322.850A.JCARLSON@uci.edu> === What is PyPE? === PyPE (Python Programmers' Editor) was written in order to offer a lightweight but powerful editor for those who think emacs is too much and idle is too little. Syntax highlighting is included out of the box, as is multiple open documents via tabs. Beyond the basic functionality, PyPE offers an expandable source tree, filesystem browser, draggable document list, todo list, filterable function list, find and replace bars (no dialog to find or replace simple strings), recordable and programmable macros, spell checker, reconfigurable menu hotkeys, triggers, find in files, external process shells, and much more. === More Information === If you would like more information about PyPE, including screenshots, where to download the source or windows binaries, bug tracker, contact information, or a somewhat complete listing of PyPE's features, visit PyPE's home on the web: http://pype.sf.net/index.shtml If you have any questions about PyPE, please contact me, Josiah Carlson, aka the author of PyPE, at jcarlson at uci.edu (remember to include "PyPE" in the subject). PyPE 2.8.6 includes the following changes and bugfixes since release 2.8.5: (fixed) a bug with "Wrap Try/Except" as per emailed bug report from Ian York. (added) ability to choose what port PyPE will listen on via --port= . (fixed) workspaces in wxPython 2.8+, patch thanks to Craig Mahaney. (added) explicit exclude dirs for find in files, patch thanks to Craig Mahaney. (added) paste and down mechanism to paste and move the cursor down, patch thanks to Craig Mahaney. (added) delete right mechanism to delete everything from the cursor to the end of the line, patch thanks to Craig Mahaney. (added) delete line mechanism to delete the current line, patch thanks to Craig Mahaney. (added) paste rectangle command for rectangular pasting, patch thanks to Craig Mahaney. (fixed) support for alternate background colors thanks to bug report from Craig Mahaney. (added) macro support to Craig Mahaney's added functionality. (added) implementation for regular expression replacements, possibly to be integrated as part of a 'replace in all open documents' in the future. (added) automatic spellcheck for text and tex documents of up to 200,000 byes in size. Will only spellcheck if the user has enabled "check syntax" in the "Realtime Options". (fixed) issue when trying to save language settings when cursor position is not to be saved. (added) support for \chapter section delimiter in *tex files. (fixed) issue that prevented the highest level source listing from being sorted in the Name and Line sorted source trees. (changed) rather than reading and executing a file for configuration loading, we now use a variant of the 'unrepr()' mechanism with support for True/False. (changed) find/replace bar now uses variant of 'unrepr()' rather than the compiler module directly. (changed) moved parsers.py to plugins and stopped using import * to get its contents. From uymqlp502 at sneakemail.com Thu Aug 30 21:26:29 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Thu, 30 Aug 2007 18:26:29 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <46d76595$0$4013$426a74cc@news.free.fr> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> Message-ID: <1188523589.736146.263510@l22g2000prc.googlegroups.com> > FWIW, the "Eiffel and SPARK Ada folks" also "brilliantly explained" why > one can not hope to "write reliable programs" without strict static > declarative type-checking. And they are probably right. I don't think you understand what they mean by "reliable programs." Any idea how much Python is used for flight control systems in commercial transport aircraft or jet fighters? How about ballistic missile launch and guidance systems? Any idea why? For the record, I think that DBS could possibly make Python more suitable for *some* mission-critical or perhaps even safety-critical applications, but it will never be able to compete with SPARK Ada or even Ada at the highest level of that domain. The important question is this: why do I waste my time with bozos like you? From aboudouvas at panafonet.gr Fri Aug 10 06:45:30 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Fri, 10 Aug 2007 03:45:30 -0700 Subject: Question about properties. In-Reply-To: <5i2t7dF3kqc46U3@mid.uni-berlin.de> References: <1186741289.074717.174370@e16g2000pri.googlegroups.com> <5i2t7dF3kqc46U3@mid.uni-berlin.de> Message-ID: <1186742730.729034.256800@i13g2000prf.googlegroups.com> On Aug 10, 1:33 pm, Marc 'BlackJack' Rintsch wrote: > On Fri, 10 Aug 2007 03:21:29 -0700, king kikapu wrote: > > Hi, > > > i read in a book the following code snippet that is dealing with > > properties: > > > class ProtectAndHideX(object): > > def __init__(self, x): > > assert isinstance(x, int), '"x" must be an integer!"' > > self.__x = ~x > > > def get_x(self): > > return ~self.__x > > > x = property(get_x) > > > Can anyone please help me understand what the symbol "~" does here ?? > > This has nothing to do with properties. For integer objects ``~`` is the > bitwise negation or invertion operator. > > Ciao, > Marc 'BlackJack' Rintsch Xmmm...ok then but what is actually doing there ?? I removed it and things seems to work the same way... From Jiandong.Ge at gmail.com Thu Aug 2 17:05:55 2007 From: Jiandong.Ge at gmail.com (JD) Date: Thu, 02 Aug 2007 21:05:55 -0000 Subject: File access In-Reply-To: References: <1186072898.405831.105670@e16g2000pri.googlegroups.com> Message-ID: <1186088755.433691.158660@m37g2000prh.googlegroups.com> Thanks for the suggestion, I am thinking implement a database system for that. JD On Aug 2, 12:11 pm, Larry Bates wrote: > JD wrote: > > Hi, > > > What I am trying to do is to run a subprocess on another machine using > > subprocess.Popen, this subprocess contuinue writing something into a > > file when it is runing. > > > After submit this subprocess, I tried to open the file and readlines() > > in the loop (with a delay) in the loop) when the subprocess was > > runing. > > > The problem is I could not get anything untill the subprocess > > finished. > > > I also tried to run another python programm when the subprocess is > > runing, I could get what I want. > > > Does anyone know why? Thanks! > > > JD > > I believe you are approaching this incorrectly. You should probably be using a > socket server/socket client to communicate between these two. Or perhaps you > could use a multi-user database table. Writing/reading to files from two > different workstations and expecting them to by synchronized most likely won't work. > > -Larry From oliver-at-hallmarkins.net Thu Aug 16 18:20:19 2007 From: oliver-at-hallmarkins.net (Oliver Nelson) Date: Thu, 16 Aug 2007 15:20:19 -0700 Subject: Canceling events from COM objects Message-ID: <46c4cdb8$0$17203$39cecf19@news.twtelecom.net> I have MapPoint working in Python, and I'm trying to cancel events on the map, but I can't seem to make that happen. I'm responding to the events successfully in my panel object. My code is like this: global MapPointMod MapPointMod = win32com.client.gencache.EnsureModule("{51C0A9CA-F7B7-4F5A-96F4-43927C6FA50F}", 0, 1, 0) class MyPanel(wx.Panel): def __init__(self, *args, **kwds): # begin wxGlade: MyPanel.__init__ kwds["style"] = wx.TAB_TRAVERSAL wx.Panel.__init__(self, *args, **kwds) self.frame = args[0] MyMap = MakeActiveXClass(MapPointMod.MappointControl, eventObj=self) self.window_1 = MyMap(self, -1) self.window_1.OpenMap("C:\\TEMP\\GPS_ON.ptt") ... ... def OnBeforeClick(self, Button, Shift, X, Y, Cancel): print "tada" My event fires just fine, but I can't seem to figure out how to cancel the event so that mappoint doesn't do its stuff with it...I've tried setting Cancel based on the mappoint specs, but it doesn't seem to get sent back anywhere... Any ideas please? Thanx, OLIVER From witham.ian at gmail.com Wed Aug 1 17:41:54 2007 From: witham.ian at gmail.com (Ian Witham) Date: Wed, 01 Aug 2007 21:41:54 -0000 Subject: Filemaker interactions Message-ID: <1186004514.108975.119380@e9g2000prf.googlegroups.com> Hello, I'm hoping someone here can put me on the right track with some broad concepts here. What I am hoping to achieve is a simple HTML page to be served over our company LAN, into which the users (Real Estate Agents) can enter a property address or reference number. My next thought was to have a Python CGI script query our filemaker database of property listings, construct a PDF from the relevant information, and finally return this PDF to the user. At no stage do I want the user to have unfettered access to the database or the ability to alter/delete records. My question is: what is the most appropriate way for my script to interact with Filemaker? Can this be done with Filemaker Pro 6? According to the Filemaker Help, the "Local Data Access Companion" shares the FileMaker Pro database with ODBC-compliant applications on the same computer. Is this the right option? Can my CGI script be an ODBC client? How? Would it need to be Filemaker specific code or does ODBC have a standardised format? I'm grateful for any advice and a nudge in the right direction. Ian. From ghirai at ghirai.com Tue Aug 14 14:45:51 2007 From: ghirai at ghirai.com (Ghirai) Date: Tue, 14 Aug 2007 21:45:51 +0300 Subject: curses library In-Reply-To: References: Message-ID: <20070814214551.1cb50566.ghirai@ghirai.com> On Tue, 14 Aug 2007 18:27:16 GMT Neil Cerutti wrote: > On 2007-08-14, Ghirai wrote: > > I need to write a console application. > > > > Are there any wrappers around curses/ncurses? > > Or any other similar libraries? > > The answer depends on your chosen platform. Python hasn't got a > cross-platform console library as one of its included batteries. > > First try the curses module. It does come with Python on systems > with a curses port. > > For Windows, there's the Effbot's console module. > http://effbot.org/zone/console-index.htm > > Or go to plan B: Use a Tkinter or other GUI interface's text > widget. Forgot to say, i don't need it to work on windows :) -- Regards, Ghirai. From pablo.yabo at gmail.com Mon Aug 13 13:42:18 2007 From: pablo.yabo at gmail.com (Pablo Yabo) Date: Mon, 13 Aug 2007 14:42:18 -0300 Subject: C++ Binding with Threads Message-ID: Hello, I want to embed Python in an application and use an API of the application from Python. The application uses a library that creates several threads and I the users of the application will write Python scripts handling this events. The problem is that I having problems with threads. I saw that I have to PyEval_InitThreads and then PyThreadState_New and PyThreadState_Swap from the new thread but this way to solve the problem doesn't work for me because I need to let 2 or more threads run at the SAME time. The interpreter lock doesn't let them run at the same time so I'm looking for another solution. I saw Py_NewInterpreter and I tried to use it but it doesn't work if I don't keep the lock. Can anyone help me to solve this issue or tell me 'Forget it!'? Thanks on advance, Pablo Yabo -- http://www.nektra.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From rrs at researchut.com Mon Aug 13 14:08:15 2007 From: rrs at researchut.com (Ritesh Raj Sarraf) Date: Mon, 13 Aug 2007 23:38:15 +0530 Subject: Module imports during object instantiation References: <1186888682.860619.258610@19g2000hsx.googlegroups.com> <46c011b5$0$417$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Ritesh Raj Sarraf a ?crit : > > The initializer will be called *each time* you instanciate the class. > And nothing prevents client code from calling it explicitelly as many > times as it wants - ok, this would be rather strange, but this is still > technically possible. What I mean that you have no assurance about the > number of times an initializer will be called. > Yes, it should be called _each time_ I do an instantiation. But the point is, I'm doing it only once. And I don't see people instantiating multiple times. And even if you do, it should do separate imports. log1 = Log() log2 = Log() Both the objects are separate from each other in every manner and they share nothing. > > wrt/ your problem, remember that top-level code is executed when the > module is loaded (either as a main program or as an imported module). > The canonical solution to os-specific imports is to handle them at the > top-level: > > if os.name == 'posix: > from some_posix_module import get_colors > elif os.name in ['nt', 'dos']: > from some_nt_module import get_windows_color as get_colors > else: > get_colors = lambda: None # or any other sensible default value... > > class SomeClass(object): > def __init__(self, *args, **kw): > self.colors = get_colors() This is what I'm left with to do currently. But I doubt if that makes by classes independent and to "Just Work". If someone was to cut/paste just the class, it won't work. He'll have to go through the imports and figure out which one relates to the class he want's to import and add similar code to his. Ritesh -- If possible, Please CC me when replying. I'm not subscribed to the list. From khemkaamit at gmail.com Wed Aug 22 01:56:19 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Wed, 22 Aug 2007 11:26:19 +0530 Subject: for statement on empty iterable In-Reply-To: <1187761270.713307.224570@i38g2000prf.googlegroups.com> References: <1187760507.951994.50310@q4g2000prc.googlegroups.com> <7xabsk3zgm.fsf@ruckus.brouhaha.com> <1187761270.713307.224570@i38g2000prf.googlegroups.com> Message-ID: <1360b7230708212256l392155b9ua11d1113846b609e@mail.gmail.com> On 8/22/07, james_027 wrote: > hi Paul, > > > > > That doesn't crash or anything like that, but it also doesn't > > set the index variable, which can cause confusion in some situations. > > Thanks for your quick answer ... Actually I was thinking how do I > access the index inside a for statement? Can you help Have a look at "enumerate", You can iterate over a list like: for i,x in enumerate(['a', 'b', 'c']): print i, x It prints: 0 a 1 b 2 c cheers, amit ---- Amit Khemka website: www.onyomo.com wap-site: www.owap.in Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From steve at holdenweb.com Tue Aug 21 19:14:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 21 Aug 2007 19:14:30 -0400 Subject: Submit Your Python Scripts In-Reply-To: <1187718492.549619.164440@w3g2000hsg.googlegroups.com> References: <1187718492.549619.164440@w3g2000hsg.googlegroups.com> Message-ID: andrew.sain at gmail.com wrote: > Hi, just wanted to invite any Python script authors to submit their > Python script to our popular software site > at [http:elided] > > We have just today added a "Scripts" directory which includes a Python > subdirectory > [http:elided] > > The first submissions usually maintain a high position in our > directories so the sooner you can get your > script listed the more exposure you should be able to receive for your > script. > > You can also submit PHP, AJAX, ASP, Ruby on Rails, CGI, Flash, Python, > CFML, .NET, Java, XML and C/C++ scripts and coding. > Ooh, goody. I just *live* to expose my scripts. Not. What an *ugly* site. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From iclark at mail.ewu.edu Thu Aug 2 14:37:01 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Thu, 02 Aug 2007 11:37:01 -0700 Subject: problems playing with dates from any month. In-Reply-To: References: Message-ID: krishnakant Mane wrote: > On 02/08/07, Ian Clark wrote: > >> http://docs.python.org/lib/node85.html >> > I looked there even before. > but could not figure out what the code did. > I know in that variable called s there was a string in a valid date format. > but when datetime.strptime was used, I did not understand the place > where a date object say d was created. > I would expect some thing like d = and the function. but I did not fine that. > only reference was the datetime module and the documentation is not as good. >>> import datetime >>> import time >>> fmt_string = '29/05/2005' >>> date_tuple = time.strptime(fmt_string, '%d/%m/%Y') >>> print date_tuple (2005, 5, 29, 0, 0, 0, 6, 149, -1) >>> date_tuple_minus_tz = date_tuple[0:6] >>> print date_tuple_minus_tz (2005, 5, 29, 0, 0, 0) >>> date_obj = datetime.datetime(*date_tuple_minus_tz) This last line is equivalent to the following: >>> date_obj = datetime.datetime(2005, 5, 29, 0, 0, 0) The * in front of a tuple expands it's arguments when making a function call >>> print date_obj 2005-05-29 00:00:0 >>> print date_obj.day == 5 False > another question I am getting is that where is the list of all > formatting characters. like for example Y is 4 digit year M is month > MM is month in 2 digits etc. > I am trying to locate a list of all these denoters. > can you provide me the place? http://docs.python.org/lib/module-time.html Look for the strptime() function. > > >> Then it's just: >> >> if date_obj.day == 5: >> print 'It's the fifth day of the month' >> > this was much better than the documentation, thanks, > regards, > Krishnakant. Hope that helps. Ian From sentientholon at gmail.com Wed Aug 22 11:51:18 2007 From: sentientholon at gmail.com (Frederick Polgardy) Date: Wed, 22 Aug 2007 15:51:18 -0000 Subject: instance method questions In-Reply-To: References: Message-ID: <1187797878.979101.179400@e9g2000prf.googlegroups.com> On Aug 22, 10:23 am, Danny wrote: > 1) how do I dynamically inspect an object to determine if it has an instance > method? (there is a class method with the same name) class Foo: def foo(self): pass x = Foo() import types >>> isinstance(x.foo, types.MethodType) True > 2) how do I dynamically delete the instance method? >From the instance? You can't, you have to delete it from the class: >>> del Foo.foo From tim at tdw.net Mon Aug 27 12:41:53 2007 From: tim at tdw.net (Tim Williams) Date: Mon, 27 Aug 2007 17:41:53 +0100 Subject: Image.open( "C:\test.jpg") is this wrong ? In-Reply-To: References: Message-ID: <9afea2ac0708270941u2c9dad3eyb9877de04e76d6f7@mail.gmail.com> On 27/08/07, Simon Brunning wrote: > On 8/27/07, Carnell, James E wrote: > > > Image.open("C:\test.jpg") > > Try: > > Image.open(r"C:\test.jpg") > > See http://docs.python.org/ref/strings.html r"C:\test.jpg" also "C:\\test.jpg" or 'C:/test.jpg' From tjreedy at udel.edu Tue Aug 21 10:08:52 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 21 Aug 2007 10:08:52 -0400 Subject: GeneratorExit should derive from BaseException, not Exception References: <46CA0EFE.6020103@imvu.com> <46CA8DAD.6060704@imvu.com> Message-ID: | I've actually read the background on the exception hierarchy (and agree | with it all), especially other suggestions that GeneratorExit derive | from BaseException. As I understand it, Guido's objections are threefold: [snip] After waiting a day or so to see if you get any more feedback here, I think you are ready to take your chances on pydev. The filter object idea from your other post is an interesting idea for a more general solution but I have no opinion on practicality or acceptibility. tjr From antikraft at gmail.com Sat Aug 25 22:58:28 2007 From: antikraft at gmail.com (Clover) Date: Sat, 25 Aug 2007 21:58:28 -0500 Subject: Python error on Mac Message-ID: <46D0EC54.8030806@gmail.com> When trying to do some things on my Mac (starting Lyx, compiling Latex via TextMate) I get this error: python: execv: /Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python: No such file or directory I (and people on Lyx and TextMate lists) are at a complete loss as to why this is happening. I didn't (at least intentionally) fiddle with Python setup. Thanks! From nospam.themindstorm at gmail.com Wed Aug 1 13:59:41 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Wed, 1 Aug 2007 17:59:41 +0000 (UTC) Subject: Checking object types References: <496954360708011012p20f2dd3cu74f0ff34deb5505f@mail.gmail.com> Message-ID: "Robert Dailey" wrote in news:496954360708011012p20f2dd3cu74f0ff34deb5505f at mail.gmail.com: > ------=_Part_51775_19953536.1185988361742 > Hi, > > I'm currently interested in creating an __add__() operator for one of > my classes. This class handles both integers and objects its own type, > however I don't know how I can perform special add operations > depending on which is passed in. Since I haven't seen any evidence of > function overloading, I'm assuming I'll have to check the types of the > variables passed in inside of my __add__() method. > > Take the two following examples: > > vector3(3,4,2) + 5 = vector3(8,9,7) > vector3(3,2,1) + vector3(4,5,6) = vector3(7,7,7) > > Any tips? Thanks. > That's an option. Another option was posted a while ago by GvR and was using some decorator to dispatch to different methods according to the type. I don't seem to find the link right now, but you can search it on GvR blog. bests, ./alex -- .w( the_mindstorm )p. From stefan.behnel-n05pAM at web.de Mon Aug 27 05:54:35 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 27 Aug 2007 11:54:35 +0200 Subject: ANN: SCF released GPL In-Reply-To: <7x3ay5d1mn.fsf@ruckus.brouhaha.com> References: <2qnAi.21495$eY.19028@newssvr13.news.prodigy.net> <7x3ay5d1mn.fsf@ruckus.brouhaha.com> Message-ID: <46D29F5B.9050506@web.de> Paul Rubin wrote: > hg writes: >> I am looking for a free subversion server resource to put the code >> ... if you know of any. > > Does it have to be SVN? I think Savannah and Sourceforge both still > use CVS. At least SF has usable Subversion support by now. You can choose between CVS or SVN. Berlios works alike, and it's Europe based. http://developer.berlios.de/ > I'm not sure what Launchpad uses. Launchpad is Ubuntu, meaning it uses Bazaar. It has SVN integration, though. Stefan From bdesth.quelquechose at free.quelquepart.fr Sat Aug 25 04:29:29 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 25 Aug 2007 10:29:29 +0200 Subject: Is it reasonably easy easy to something like this with python? In-Reply-To: References: <1188326947.527698.245770@r23g2000prd.googlegroups.com> Message-ID: <46d488e7$0$20294$426a34cc@news.free.fr> Gerardo Herzig a ?crit : > walterbyrd wrote: > >> This is made with a php5 framework called qcodo. >> >> http://examples.qcodo.com/examples/dynamic/inline_editing.php >> >> With qcodo it's easy to make grids that are sortable and inline >> editable. Qcodo grids work from the database - not an xml table or >> array. Qcodo handles complex data relations, and fairly large >> datadabes. >> >> I like python better than php, but I don't know of any python tools to >> create these sorts of grids. >> >> >> > The one who make that table sorteable is AJAX. Not php. The php part is > kind of trivial (so it would be `trivial' in python too). It just reads > some data and format it in an html table. FWIW, Pylons have all sorts of javascript/ajax helpers (using prototype.js). From http Sat Aug 11 08:29:01 2007 From: http (Paul Rubin) Date: 11 Aug 2007 05:29:01 -0700 Subject: Deleting objects on the fly References: <1186705500.227658.163170@q3g2000prf.googlegroups.com> <46BC35F2.4070600@metavr.com> <1186835172.396997.210710@d55g2000hsg.googlegroups.com> Message-ID: <7xwsw2b6gi.fsf@ruckus.brouhaha.com> Dustan writes: > > | del x will remove x from memory if nothing else is refering to it, > > This is implementation dependent: true for CPython, not for Jython, ??? for > > IronPython. > Wait a second; do you mean to say that in Jython, del x will never > remove x from memory? How do you free up RAM? It stays around until the GC picks it up. From carsten at uniqsys.com Thu Aug 23 09:00:09 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 23 Aug 2007 09:00:09 -0400 Subject: Baby Steps, optionDB In-Reply-To: References: <1187862216.183609.89810@r23g2000prd.googlegroups.com> Message-ID: <1187874009.3380.7.camel@dot.uniqsys.com> On Thu, 2007-08-23 at 04:30 -0700, W. Watson wrote: > I used to program in C++, and there's one thing I've never liked about > OOP. Too much typing! Blame C++, not OOP. In time, you will find that Python's approach to OOP in particular and to programming in general allows you to express your ideas more concisely than you could in other programming languages. -- Carsten Haese http://informixdb.sourceforge.net From vedrandekovic at v-programs.com Fri Aug 3 07:56:54 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Fri, 03 Aug 2007 04:56:54 -0700 Subject: wxpython TreeCtrl with os.listdir Message-ID: <1186142214.786703.75380@w3g2000hsg.googlegroups.com> Hello, Does anybody know how can I "insert" os.listdir items in wx python TreeCtrl and every item assign adequately icon on this example import wx class TestFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="simple tree with icons", size=(400,500)) il = wx.ImageList(16,16) # adequately icons self.fldridx = il.Add(wx.ArtProvider.GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, (16,16))) # icon for os.listdir folder self.fldropenidx = il.Add(wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN,wx.ART_OTHER, (16,16))) # icon for os.listdir file self.fileidx = il.Add(wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, (16,16))) # icon for os.listdir open folder self.tree = wx.TreeCtrl(self) self.tree.AssignImageList(il) root = self.tree.AddRoot("wx.Object") self.tree.SetItemImage(root, self.fldridx,wx.TreeItemIcon_Normal) self.tree.SetItemImage(root, self.fldropenidx,wx.TreeItemIcon_Expanded) self.AddTreeNodes(root, data.tree) # There must be os.listdir items self.tree.Expand(root) def AddTreeNodes(self, parentItem, items): for item in items: if type(item) == str: newItem = self.tree.AppendItem(parentItem, item) self.tree.SetItemImage(newItem, self.fileidx,wx.TreeItemIcon_Normal) else: newItem = self.tree.AppendItem(parentItem, item[0]) self.tree.SetItemImage(newItem, self.fldridx,wx.TreeItemIcon_Normal) self.tree.SetItemImage(newItem, self.fldropenidx,wx.TreeItemIcon_Expanded) self.AddTreeNodes(newItem, item[1]) def GetItemText(self, item): if item: return self.tree.GetItemText(item) else: return "" app = wx.PySimpleApp(redirect=True) frame = TestFrame() frame.Show() app.MainLoop() Regards, Vedran From arkanes at gmail.com Wed Aug 8 11:10:15 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 8 Aug 2007 10:10:15 -0500 Subject: Stop a thread on deletion In-Reply-To: References: Message-ID: <4866bea60708080810w39832910s6c1e68ed017b45eb@mail.gmail.com> On 8/8/07, Sjoerd Op 't Land wrote: > Hello all, > > I'm using threading for generating video content. The trouble is how to > kill the thread, because there are multiple (simultaneous) owners of a > thread. Ideally, a flag would be set when the reference count of the > thread becomes zero, causing the run() loop to quit. Example: > > import threading > import time > import gc > > class myThread(threading.Thread): > def __init__(self): > self.passedOut = threading.Event() > threading.Thread.__init__(self) > def __del__(self): > self.passedOut.set() > def run(self): > i = 0 > while not self.passedOut.isSet(): > i += 1 > print "Hi %d" % i > time.sleep(0.25) > > > a = myThread() > a.start() > time.sleep(2.5) > a = None > time.sleep(2.5) > > Unfortunately, this doesn't work. When I remove the while-loop, __del__ > is called, actually. Appearantly there is still some reference to the > thread while it is running. > > I tried gc.get_referrers(self), but it seems to need some parsing. I'm > not sure how to implement that and I'm not sure whether it will work > always or not. > gc.get_referrers returns a list of object instances that hold a reference to the object. The important one in this case is, of course, the thread itself. The thread holds a reference to the run method which (of course) requires a reference to the object. In other words, a running thread cannot be refcounted to zero. You are going to need a better method of handling your resources. Perhaps instead of holding a reference to the thread, they could hold a reference to a proxy object: import threading import time import gc import pprint class myThread(threading.Thread): def __init__(self): self.passedOut = threading.Event() threading.Thread.__init__(self) def run(self): i = 0 while not self.passedOut.isSet(): i += 1 print "Hi %d" % i time.sleep(1) print "stopped" class ThreadProxy(object): def __init__(self, proxy_for): self.proxy_for = proxy_for def __del__(self): self.proxy_for.passedOut.set() def start(self): self.proxy_for.start() From arkanes at gmail.com Wed Aug 29 13:13:42 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 29 Aug 2007 12:13:42 -0500 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188369928.755777.142690@i38g2000prf.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> Message-ID: <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> On 8/29/07, Russ wrote: > On Aug 28, 10:58 pm, Michele Simionato > wrote: > > > Why do you think that would ad a strong positive capability? > > To me at least it seems a big fat lot of over-engineering, not > > needed in 99% of programs. In the remaining 1%, it would still not > > be needed since Python provides out of the box very powerful > > metaprogramming capabilities so that you can implement > > yourself the checks you need, if you really need them. > > I get the strong impression you don't really understand what > programming by contract is. > Don't be condescending. > I have not yet personally used it, but I am interested in anything > that can help to make my programs more reliable. The entire issue of software reliability, exactly what metrics you should use to measure it, and whether any specific technique results in more of it are very much in debate. If you want to experiment with these techniques, you can do so without them being in the Python core. Python has all the support you need to play with them right now. >If you are > programming something that doesn't really need to be correct, than you > probably don't need it. But if you really need (or want) your software > to be correct and reliable as possible, I think you you should be > interested in it. You might want to read this: > You don't want your software to KILL BABIES, do you? If you don't want your programs to KILL BABIES then you should use our technique, so you don't KILL BABIES. There are ways to make correct programs besides DBC. It may not even help in the general case - just as with unit testing and type proving, you're going to be limited by what you don't think to assert or document or test, and I've seen no evidence that DBC is any better than anything else at preventing unwritten assumptions. From zentraders at gmail.com Mon Aug 6 15:42:08 2007 From: zentraders at gmail.com (Zentrader) Date: Mon, 06 Aug 2007 12:42:08 -0700 Subject: RTF 2 Tiff In-Reply-To: <1186427712.284976.207560@d30g2000prg.googlegroups.com> References: <1186427712.284976.207560@d30g2000prg.googlegroups.com> Message-ID: <1186429328.713392.222020@z24g2000prh.googlegroups.com> On Aug 6, 12:15 pm, cjankow... at hbr-inc.com wrote: > Hi all, > I am trying to convert an RTF file to a Tiff image using Python. This > process will convert several hundred images daily. Currently I am > able to get the RTF file into a text format using Rtf2Txt.py, but I > loose the images contained in the RTF file. I have the same problem > when I convert to .HTML using Rtf2Html.py. I do not have a sample > that I can share because of HIPPA regulations. Can anyone please help > me? > > Thanks, > > Chris J. Perhaps someone will have a more Pythonic answer. Abiword will convert from rtf to html and can be run from the command line. I would also look at openjade and w3m. You may have to parse the file and look for the images and convert them separately using an Imagemagick type program. I don't have much experience with this, but hopefully one of these will work or someone else can provide more info. From andmart at gmail.com Fri Aug 3 11:32:23 2007 From: andmart at gmail.com (=?ISO-8859-1?Q?Andr=E9_Martins?=) Date: Fri, 3 Aug 2007 12:32:23 -0300 Subject: Eclipse/PyDev question. In-Reply-To: <1186153503.806195.225560@g4g2000hsf.googlegroups.com> References: <1186153119.391091.275860@r34g2000hsd.googlegroups.com> <1186153259.372809.230110@d30g2000prg.googlegroups.com> <1186153503.806195.225560@g4g2000hsf.googlegroups.com> Message-ID: I think you can download the eclipse plataform e get pydev through eclipse update. Eclipse Europa distro is a group of 21 projects like jdt and cdt not correlate to python. []'s -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Aug 28 00:36:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 28 Aug 2007 01:36:37 -0300 Subject: sorting a list of lists References: <1188233798.684136.263640@22g2000hsm.googlegroups.com> <1188235267.790442.193830@q5g2000prf.googlegroups.com> <46D31827.9060400@web.de> <1188240075.549626.42020@i38g2000prf.googlegroups.com> Message-ID: En Mon, 27 Aug 2007 15:41:15 -0300, iapain escribi?: >> Taking advantage of stable sorting is totally not a hack. The OP just >> tried >> the two sorting steps in the wrong order. > > I didnt say not to use stable sorting, but write a generic function > and hacky code. It is always better to adopt a generic approach. Sorting on multiple keys from last to first has been the "standard" and "generic" approach even before computers existed. Hollerith punched cards "processors" did it that way around 1890. -- Gabriel Genellina From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Aug 24 06:45:03 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 24 Aug 2007 12:45:03 +0200 Subject: Server-side scripting in python In-Reply-To: <1187843960.922925.127990@i13g2000prf.googlegroups.com> References: <1187614732.519547.296020@j4g2000prf.googlegroups.com> <1187755436.972359.293360@i13g2000prf.googlegroups.com> <0k2up4-lla.ln1@lairds.us> <1187843960.922925.127990@i13g2000prf.googlegroups.com> Message-ID: <46ceb673$0$415$426a74cc@news.free.fr> Nagarajan a ?crit : > On Aug 22, 8:50 pm, cla... at lairds.us (Cameron Laird) wrote: >> In article <1187755436.972359.293... at i13g2000prf.googlegroups.com>,Nagarajan wrote: >> >>>> . >>>> . >>>> . >>> Let me phrase my problem in a finer way. >>> I have done simple projects inpython. >>> I wanted to explore web programming facet ofpython. The problem at my >>> hand is to develop an email web client. I've developed web >>> applications in PHP. I need to evaluatepython-based web frameworks to >>> make a smart choice of the web framework or a language like PHP, Perl >>> based on performance predominantly. Do I make myself clear now? >> . >> . >> . (snip Cameron's answer) > Django is intuitive and handy. I think I would go with that. > Any suggestions? Yes : have a look at Pylons too. It's actually quite less 'polished' than Django, but it's IMHO going in the right direction (as a matter of fact, Turbogears 2.0 - another well-known Python MVC framework - will be based on Pylons...). Django is clearly more oriented toward content-management, which might not be what you want for this project. My 2 cents... From Graham.Dumpleton at gmail.com Wed Aug 8 20:34:24 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Thu, 09 Aug 2007 00:34:24 -0000 Subject: some import / namespace questions In-Reply-To: References: Message-ID: <1186619664.407509.161260@j4g2000prf.googlegroups.com> On Aug 9, 1:11 am, stef mientki wrote: > hello, > > I'm working on a rather strange program, > that is partially build dynamically, > and where users can create plugins, > without knowing any of the details of the core program. > > Of course this leads to some weird bugs, > so one of the things I want to view/log is the order (and even better > the way) modules are imported. Set and export the environment variable: PYTHONVERBOSE=1 in your environment before you run Python. This will generate lots of internal information about what Python is up to, including details about module importing, where it is searching for modules etc etc. For example: >>> import socket # /System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/socket.pyc matches /System/Library/Frameworks/ Python.framework/Versions/2.3/lib/python2.3/socket.py import socket # precompiled from /System/Library/Frameworks/ Python.framework/Versions/2.3/lib/python2.3/socket.pyc dlopen("/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/lib-dynload/_socket.so", 2); import _socket # dynamically loaded from /System/Library/Frameworks/ Python.framework/Versions/2.3/lib/python2.3/lib-dynload/_socket.so dlopen("/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/lib-dynload/_ssl.so", 2); import _ssl # dynamically loaded from /System/Library/Frameworks/ Python.framework/Versions/2.3/lib/python2.3/lib-dynload/_ssl.so import errno # builtin Output goes to standard error. There can be quite a lot, so you may want to redirect standard error to a file. Graham From jarausch at skynet.be Mon Aug 13 10:18:15 2007 From: jarausch at skynet.be (Helmut Jarausch) Date: Mon, 13 Aug 2007 16:18:15 +0200 Subject: Drawing a graph In-Reply-To: References: Message-ID: <46C06827.9060804@skynet.be> Ghirai wrote: > Hello list, > > I need to draw a graph, 2 axes, 2D, nothing fancy. > One of the axes is time, the other one is a series of integers. > > I don't care much about the output format. > > Are there any specialized libraries for this, or should i use PIL? > What about Gnuplot.py http://gnuplot-py.sourceforge.net/ -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From arunmail at gmail.com Thu Aug 2 22:03:38 2007 From: arunmail at gmail.com (lazy) Date: Fri, 03 Aug 2007 02:03:38 -0000 Subject: Berkely Db. How to iterate over large number of keys "quickly" In-Reply-To: References: <1186083838.318952.254370@q3g2000prf.googlegroups.com> Message-ID: <1186106618.835530.278450@d30g2000prg.googlegroups.com> On Aug 2, 1:42 pm, Ian Clark wrote: > lazy wrote: > > I have a berkely db and Im using the bsddb module to access it. The Db > > is quite huge (anywhere from 2-30GB). I want to iterate over the keys > > serially. > > I tried using something basic like > > > for key in db.keys() > > > but this takes lot of time. I guess Python is trying to get the list > > of all keys first and probbaly keep it in memory. Is there a way to > > avoid this, since I just want to access keys serially. I mean is there > > a way I can tell Python to not load all keys, but try to access it as > > the loop progresses(like in a linked list). I could find any accessor > > methonds on bsddb to this with my initial search. > > I am guessing BTree might be a good choice here, but since while the > > Dbs were written it was opened using hashopen, Im not able to use > > btopen when I want to iterate over the db. > > db.iterkeys() > > Looking at the doc for bsddb objects[1] it mentions that "Once > instantiated, hash, btree and record objects support the same methods as > dictionaries." Then looking at the dict documentation[2] you'll find the > dict.iterkeys() method that should do what you're asking. > > Ian > > [1]http://docs.python.org/lib/bsddb-objects.html > [2]http://docs.python.org/lib/typesmapping.html Thanks. I tried using db.first and then db.next for subsequent keys. seems to be faster. Thanks for the pointers From david at asdf.asdf Thu Aug 23 23:21:50 2007 From: david at asdf.asdf (bambam) Date: Fri, 24 Aug 2007 13:21:50 +1000 Subject: beginner, idomatic python 2 Message-ID: <13csjmeaoqh9le3@corp.supernews.com> Would someone like to suggest a replacement for this? This is a function that returns different kinds of similar objects, depending on what is asked for. PSP and PWR are classes. I don't really want to re-write the calling code very much: I'm just wondering if the function can be replaced with some kind of OOP pattern. def Device(DeviceType): if DeviceType=='PSP': return PSP() elif DeviceType=="Power Supply" return PWR() etc... Thanks! From gnewsg at gmail.com Tue Aug 21 19:53:31 2007 From: gnewsg at gmail.com (billiejoex) Date: Tue, 21 Aug 2007 16:53:31 -0700 Subject: Extracting the traceback Message-ID: <1187740411.848743.151960@x35g2000prf.googlegroups.com> Hi there, I'm facing a case where I need to get the traceback outptut when occurring an exception. I solved such problem by using traceback module in conjunction with StringIO: import StringIO, traceback try: raise Exception except: f = StringIO.StringIO() traceback.print_exc(file=f) print f.getvalue() ... but this seems a little poor to me since I first put output into the StringIO.StringIO(), then I get it back by using getvalue() on it. Is there a way to avoid the use of StringIO and get such output without using such (useless) additional step? Thanks in advance From carsten at uniqsys.com Thu Aug 30 09:47:21 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 30 Aug 2007 09:47:21 -0400 Subject: SAXParseException: not well-formed (invalid token) In-Reply-To: <46D6C40F.4060105@cesga.es> References: <46D6B9F6.2010402@web.de> <46D6C40F.4060105@cesga.es> Message-ID: <1188481641.3468.5.camel@dot.uniqsys.com> On Thu, 2007-08-30 at 15:20 +0200, Pablo Rey wrote: > Hi Stefan, > > The xml has specified an encoding ( ?>). It's possible that the encoding specification is incorrect: >>> u = u"\N{LATIN SMALL LETTER E WITH ACUTE}" >>> print repr(u.encode("latin-1")) '\xe9' >>> print repr(u.encode("utf-8")) '\xc3\xa9' If your input string contains the byte 0xe9 where your accented e is, the file is actually latin-1 encoded. If it contains the byte sequence 0xc3,0xa9 it is UTF-8 encoded. If the string is encoded in latin-1, you can transcode it to utf-8 like this: contents = contents.decode("latin-1").encode("utf-8") HTH, -- Carsten Haese http://informixdb.sourceforge.net From bdesth.quelquechose at free.quelquepart.fr Thu Aug 30 09:43:32 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 30 Aug 2007 15:43:32 +0200 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188520454.996940.293030@m37g2000prh.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> <1188430887.481586.106760@l22g2000prc.googlegroups.com> <1188504811.019632.186580@x35g2000prf.googlegroups.com> <46d75116$0$401$426a74cc@news.free.fr> <1188517050.174081.265900@x40g2000prg.googlegroups.com> <46d75d33$0$6231$426a34cc@news.free.fr> <1188520454.996940.293030@m37g2000prh.googlegroups.com> Message-ID: <46d76790$0$410$426a74cc@news.free.fr> Russ a ?crit : >>>That looks like new syntax to me. >> >>It's the syntax for decorator functions, and it's not that new - it >>cames with Python 2.4, released November 30, 2004. > > > After looking more carefully at your example, I don't think it is as > clean and logical as the > PEP 316 syntax. Possibly not, but at least it's trivial to implement. > At first I thought that your pre and post-conditions > applied to the class, Pre and post conditions applying to the class ? Now that's an interesting concept. IIRC, Eiffels pre and post conditions only apply to methods, and I fail to see how they could apply to a class. But since you're an expert on the subject, I don't doubt you'll enlighten us ? > but now I realize that they apply to the function. I prefer to see the > conditions inside > the function in the doc string. That just seems more logical to me. Not to me. Doc strings are not for implementation. But if you want to implement a DbC module using doc strings, please do so. > With all due respect, > your proposal is interesting, but I think it overextends the "function > decorator" idea a bit. Definitively not, on the contrary - that's *exactly* what decorators are for. Else, they would be nothing more than HOFs, and there would be no point in having this syntactic sugar. (snip). From esj at harvee.org Wed Aug 29 02:52:37 2007 From: esj at harvee.org (Eric S. Johansson) Date: Wed, 29 Aug 2007 02:52:37 -0400 Subject: setup.py question Message-ID: I have an environment where I have a bunch of data files or use would like Python application. I want to use the data_files specification of set up to distribute those files. But I also need to change ownership and permissions. I know there's some way to do this because I've done it once before but I can't find how I did it and I can't find how to do in the documentation. Any pointers on how to set ownership and permissions for files listed in the data_file section of a setup call would be wonderful. For what it's worth, I have modified install(_install) methods to handle set gid wrappers. It's a cool abuse of setup. :-) thanks From steve at holdenweb.com Mon Aug 27 13:23:55 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 27 Aug 2007 13:23:55 -0400 Subject: Co-developers wanted: document markup language In-Reply-To: <46CF4386.9020801@freakmail.de> References: <87odgyyx9u.fsf@wilson.homeunix.com> <87tzqpew22.fsf@wilson.homeunix.com> <87tzqp77my.fsf@wilson.homeunix.com> <7xy7g1if24.fsf@ruckus.brouhaha.com> <87mywh717i.fsf@wilson.homeunix.com> <46CEAF71.3050900@freakmail.de> <46CF4386.9020801@freakmail.de> Message-ID: Wildemar Wildenburger wrote: > Robert Kern wrote: >> Wildemar Wildenburger wrote: >> >>> Torsten Bronger wrote: >>> >>>> Hall?chen! >>>> >>>> >>> Yes, you're German. Have you ever noticed that (we) Germans are >>> virtually the only ones that feel the need to rub our nationality into >>> everyones faces? ;) >>> >> Howdy! >> >> We Americans do the same. ;-) >> >> > Weeell, you guys mostly rub your ignorance about the rest of the world > into everyones faces. That's a little different. > > There, I did it. Now I got my country invaded. But maybe that's a good > thing ... at least we will get democracy and finally find happiness. > > /W > (OK, sorry. I couldn't resist. Don't take it personally. Take it > nationally. ;) ) Unfortunately Americans are also well known for their inability to detect irony, so your pointed remarks about democracy and happiness will probably go mostly unnoticed. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From zyzhu2000 at gmail.com Fri Aug 24 00:24:03 2007 From: zyzhu2000 at gmail.com (beginner) Date: Fri, 24 Aug 2007 04:24:03 -0000 Subject: List Comprehension Question: One to Many Mapping? Message-ID: <1187929443.636690.287450@i13g2000prf.googlegroups.com> Hi All, How do I map a list to two lists with list comprehension? For example, if I have x=[ [1,2], [3,4] ] What I want is a new list of list that has four sub-lists: [[1,2], [f(1), f(2)], [3,4], [f(3), f(4)]] [1,2] is mapped to [1,2] and [f(1), f(2)] and [3,4] is mapped to [3,4], [f(3), f(4)]. I just can't find any way to do that with list comprension. I ended up using a loop (untested code based on real code): l=[] for y in x: l.append(y) l.append([f(z) for z in y]) Thanks, Geoffrey From greg at cosc.canterbury.ac.nz Tue Aug 7 05:42:16 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 07 Aug 2007 21:42:16 +1200 Subject: Redirecting stderr to null and revert In-Reply-To: <1186439213.076470.109060@d55g2000hsg.googlegroups.com> References: <1186439213.076470.109060@d55g2000hsg.googlegroups.com> Message-ID: <5hqtauF3mbh2tU1@mid.individual.net> reubendb wrote: > def nullStderr(): > sys.stderr.flush() > err = open('/dev/null', 'a+', 0) > os.dup2(err.fileno(), sys.stderr.fileno()) > > def revertStderr(): > sys.stderr = sys.__stderr__ You're doing the redirection at one level and trying to revert it at a different level. If this is a Python function that's doing its output by writing to sys.stderr, there's a much simpler way to do the redirection: sys.stderr = open('/dev/null', 'w') (that's the Python builtin function 'open', not the one in os). Then your revertStderr function will work. BTW I'd arrange for the reversion to be done in a try-finally, e.g. nullStderr() try: do_something() finally: revertStderr() so you won't get stuck with a redirected stderr if an exception occurs, and thereby not be able to see the traceback! -- Greg From steve at holdenweb.com Wed Aug 8 11:22:54 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 08 Aug 2007 11:22:54 -0400 Subject: Seek the one billionth line in a file containing 3 billion lines. In-Reply-To: <4866bea60708080658l170bd9eevd86cf58dbc1eddd8@mail.gmail.com> References: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> <7xzm12o7o7.fsf@ruckus.brouhaha.com> <1186555297.877273.40540@o61g2000hsh.googlegroups.com> <874pja70p5.fsf@benfinney.id.au> <4866bea60708080658l170bd9eevd86cf58dbc1eddd8@mail.gmail.com> Message-ID: <46B9DFCE.7000505@holdenweb.com> Chris Mellon wrote: > On 8/8/07, Ben Finney wrote: >> Sullivan WxPyQtKinter writes: >> >>> On Aug 8, 2:35 am, Paul Rubin wrote: >>>> Sullivan WxPyQtKinter writes: >>>>> This program: >>>>> for i in range(1000000000): >>>>> f.readline() >>>>> is absolutely every slow.... >>>> There are two problems: >>>> >>>> 1) range(1000000000) builds a list of a billion elements in memory >> [...] >>>> 2) f.readline() reads an entire line of input >> [...] >>> Thank you for pointing out these two problem. I wrote this program >>> just to say that how inefficient it is to use a seemingly NATIVE way >>> to seek a such a big file. No other intention........ >> The native way isn't iterating over 'range(hugenum)', it's to use an >> iterator. Python file objects are iterable, only reading eaach line as >> needed and not creating a companion list. >> >> logfile = open("foo.log", 'r') >> for line in logfile: >> do_stuff(line) >> >> This at least avoids the 'range' issue. >> >> To know when we've reached a particular line, use 'enumerate' to >> number each item as it comes out of the iterator. >> >> logfile = open("foo.log", 'r') >> target_line_num = 10**9 >> for (line_num, line) in enumerate(file): >> if line_num < target_line_num: >> continue >> else: >> do_stuff(line) >> break >> >> As for reading each line: that's unavoidable if you want a specific >> line from a stream of variable-length lines. >> > > The minimum bounds for a line is at least one byte (the newline) and > maybe more, depending on your data. You can seek() forward the minimum > amount of bytes that (1 billion -1) lines will consume and save > yourself some wasted IO. Except that you will have to count the number of lines in that first billion characters in order to determine when to stop. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From pavlovevidence at gmail.com Fri Aug 17 20:42:23 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 17 Aug 2007 17:42:23 -0700 Subject: How to setup pyOpenGL3.0.a6 for window xp? In-Reply-To: <1187395670.267971.88750@q4g2000prc.googlegroups.com> References: <1187395670.267971.88750@q4g2000prc.googlegroups.com> Message-ID: <1187397743.937458.301590@q3g2000prf.googlegroups.com> On Aug 17, 8:07 pm, math2life wrote: > Hi, > I've already download the pyOpenGL3..0.a6 for python2.4 and installed > python2.4, > > Is it necessary to install OpenGL? And if need, which version of > OpenGL should be > installed? Windows comes with OpenGL libraries. However, before you can use OpenGL you'll need a package that can provide an OpenGL context, which PyOpenGL doesn't do (easily). PyGame is the typical choice for most uses. If all you need is a simple window to draw on, this is the package you want. However, it doesn't (easily) work with common GUIs like GTK and Wx. If you want to use use OpenGL in a GUI app, then you'll want to find an "OpenGL canvas widget" for that GUI. Carl Banks From silfheed at gmail.com Sun Aug 5 14:13:21 2007 From: silfheed at gmail.com (Silfheed) Date: Sun, 05 Aug 2007 18:13:21 -0000 Subject: the one python book In-Reply-To: References: Message-ID: <1186337601.388854.254510@i38g2000prf.googlegroups.com> On Aug 4, 6:23 am, "dhr" wrote: Assuming that you already know that a ton of great stuff is on the web, I'd also recommend 'Programming Python' and 'Python Cookbook'. 'The Python Book' would have to be the Python book ('Programming Python', cuz it has a python on the cover and covers the python language, brilliant!....) It's huge and is full of great scripts and, most importantly, promotes good coding style. Hopefully they've updated the index tho, since the 2nd edition has an utterly pathetic index, tho you can still find what you want pretty quickly with just the toc. Python Cookbook is necessary because it covers so many little hidden secrets of python. The section on dateutil is worth the price of the book alone. From raims at dot.com Mon Aug 13 19:59:13 2007 From: raims at dot.com (Lawrence Oluyede) Date: Tue, 14 Aug 2007 01:59:13 +0200 Subject: chmod g+ Equivalent References: <1187042290.821786.178420@19g2000hsx.googlegroups.com> <1i2t81z.1f4cmrhu1sy8iN%raims@dot.com> <1187046225.596726.97390@g4g2000hsf.googlegroups.com> Message-ID: <1i2tc5o.a3g6188rwg8N%raims@dot.com> milan_sanremo wrote: > I understand that for setting the standard rwx permissions, but how do > these affect the ability to change the setgid bit? Under Solaris you > cannot do it from the command line in absolute mode, so perhaps it is > not possible in python > > I'm trying to get the equivalent of 'chmod g+' not something like > 'chmod 755'. Sorry, I think I misunderstood the request. Isn't "#define S_ISGID 0002000" what you're asking for? -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From dave.willmer at gmail.com Thu Aug 30 14:55:39 2007 From: dave.willmer at gmail.com (dave_w) Date: Thu, 30 Aug 2007 18:55:39 -0000 Subject: Important Research Project In-Reply-To: <1188482087.098419.56490@k79g2000hse.googlegroups.com> References: <13ddcvm1bsu3s94@corp.supernews.com> <1188482087.098419.56490@k79g2000hse.googlegroups.com> Message-ID: <1188500139.411988.127100@q5g2000prf.googlegroups.com> On Aug 30, 2:54 pm, Paul McGuire wrote: > On Aug 30, 8:12 am, "E.D.G." wrote: > > > Important Research Project (Related to computer programming) > > > Posted by E.D.G. on August 30, 2007 edgrs... at ix.netcom.com > > > This report is being posted to a number of Internet Newsgroups > > Always the hallmark of a considerate poster. > > > to see if > > there are any experienced computer programmers who would like to provide > > some assistance with an effort to develop a Perl language computer program. > > > Interested parties can try contacting me by e-mail or by posting a > > response note to the comp.lang.perl.misc newsgroup. They would need to > > download a recent (free) MSI copy of Perl from the ActiveState Web site and > > get it running on a Windows XP or Vista system. > > >http://www.activestate.com > > This is a little backwards, one usually presents their research topic > *first* and their contact info *last*. The reason? SO PEOPLE KNOW > WHAT THE @#$(&#!@ YOU ARE WORKING ON! Ok, I'll bite, keep reading... > > > I am presently using Perl 5.8.8 > > Whoop-de-doo for you. > > > but plan to upgrade to the latest > > version as soon as possible. People can use Windows 98 if that is the only > > operating system available. Perl also runs on other operating systems. But > > at this time I specifically need help with the Windows version. > > I suspect Perl is largely the same Perl on all those platforms. Win > 98? Is this a zombie spam from the turn of the century? > > > The goal is to have a single Perl program (or modules) perform functions > > that have been done by a sizeable collection of other language programs in > > the past. > > Doing what!? Grrr..., keep reading, there's gotta be a punch line... > > > Help is presently needed with learning how to get Perl to generate > > charts and also produce standalone .exe copies of itself. The plan is to > > then make those .exe copies available to other scientific researchers around > > the world for free use along with free use updates when they become > > available. If other researchers wish to get Perl running on their own > > computers then they will probably also be given the source code for the > > original program for free use so that they can do their own development > > work. > > Ohmigod, is Google broken? Or has Perl gone this long and this far > without support for creating charts and graphs? Sounds like about 10 > minutes of research. > > > Perl was originally chosen because it is quite versatile, is a free > > download, and is supported both by ActiveState and quite a few independent > > programmers. So other researchers could get their own versions running > > without having to worry about viruses or cost. > > (Why is this posted on all these non-Perl newsgroups, then? I've > *seen* Perl already, and never want to again!) > > > So far the work is fairly advanced. The effort has been underway for at > > least a decade. > > ... and we are just getting around to plotting some data. > > > The core data generation program was formally copyrighted > > several years ago. > > Red flag #37 - "formally copyrighted", wooo-ooooh > > > My present version of Perl will send data to Windows as > > if it were being manually typed into the keyboard (important for controlling > > other programs). And it can directed to respond to most keystrokes even > > when another program is the active one. Unfortunately, Windows also > > presently responds to those keystrokes. And that complicates things a bit. > > ... and has for the past decade, and I still haven't figured it out. > > > Not being a professional computer programmer I have been finding it > > difficult to get new features such as a chart generating ability merged with > > and running with Perl. And the entire research project is now being slowed > > as a result. One of my colleagues has done an extensive amount of work with > > Basic. And I even offered to pay him to help with the Perl development > > effort. But after he downloaded a copy of Perl and examined it he decided > > that this would involve too much effort. I have to agree with him. > > Maybe that up-front language choice could stand a review... > > > Once it is possible to create charts and .exe versions the plan is for > > researchers around the world to develop Perl modules for generating a > > variety of data related to sun, moon, planet, ocean tide crest and trough, > > and Solid Earth Tide locations. Most of those data can already be generated > > with other programs. Some of the data are not yet available anywhere as far > > as I am aware. If the effort is unusually successful the Perl program (or > > modules) might eventually be converted to CGI programs that will run at one > > or more Internet Web sites. > > AHHH! The "research", I almost forgot! Why is it left to the end of > the message? And do we still know what the @#(*&$ this "variety of > data" is for? I'm going to take a wild guess here - earthquake > prediction? perpetual motion? picking guaranteed-to-win lottery > numbers? > > After a pitch like that, who could not be tempted at the prospect of > "generating a variety of data related to sun, moon, etc. etc."? Sign > me up - NOT! > > GTFA, > -- Paul Thanks for the amusing reply Paul, i think you summed up a few people's feelings quite fairly, but maybe a little more tact next time? :-) I'm going to begin my answer with the age old taboo of 'use a different language', but since you cross-posted to comp.lang.python, i feel justified. so... use python. you didnt exactly state what you wanted out of the project, so i'm going to take a few guesses. if you want astrophysical data, there is a python module which is based on NASA JPL's ephemerides system, you can find it here: http://www.cv.nrao.edu/~rfisher/Python/py_solar_system.html and yes, i know there is Astro::SLA on CPAN. if you want (basic) ocean/tidal modelling, you can use this (again... python) http://geosci.uchicago.edu/~cdieterich/swom/ or take a look at this PDF entitled 'python for assembling climate modelling toolkits': www.esmf.ucar.edu/presentations/pres_0305_jacobs.pdf if you want to connect to online databases etc., using urllib2 (a standard python module), you can fetch the data you need in only a few lines of code (and i mean 2 or 3 lines for basic requests) for plotting... use matplotlib, in most python programmers minds it has reached legendary status. if you're still thinking about plotting in Perl, look here http://biptest.weizmann.ac.il/course/prog/graphics/success.html it is the graphing page from the Weizmann institute in Israel which does a course entitled 'Perl programming course for bioinformatics and internet'; perhaps you could use some of your research money to send someone on the course? and if you want to put graphs online, you can use matplotlib server side to generate a jpg for example, and then show that using html (again, not very many lines of code). without knowing exactly what needs accomplished, i ts difficult to help, but it seems like most of your programming has already been done, and just needs some code to glue different modules together (trust me on this one - use python). with python, matplotlib etc, everything is cross platform, if it is web-based access you're after, it doesnt matter what platform you develop on you also talk about generating standalone .exe files - use py2exe w/ NSIS, or pyInstaller, both of which have tutorials online. most importantly of all... re-read Paul's post above. if you don't find it as amusing as the rest of us, here's the gist... "Ohmigod, is Google broken?" cheers Dave From comp.ogz at gmail.com Thu Aug 16 03:42:28 2007 From: comp.ogz at gmail.com (=?utf-8?q?O=C4=9Fuz_Yar=C4=B1mtepe?=) Date: Thu, 16 Aug 2007 10:42:28 +0300 Subject: python socket usage Message-ID: <200708161042.29304.comp.ogz@gmail.com> Is it possible to send a data object like a tuple or a list in socket programming? If so how? It seems with socket module it is only possible to send strings. -- O?uz Yar?mtepe http://www.yarimtepe.com/en From bronger at physik.rwth-aachen.de Mon Aug 6 01:49:44 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 06 Aug 2007 07:49:44 +0200 Subject: Setting default output encoding Message-ID: <871wehky9z.fsf@wilson.homeunix.com> Hall?chen! I start a python script with subprocess from another Python script with python = subprocess.Popen(["python", "myscript.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) However, this child script has sys.stdout.encoding set to None, which means that Unicode strings cannot be printed without trouble. I tried environment = os.environ environment["LC_CTYPE"] = environment["LANG"] = "de_DE.UTF-8" python = subprocess.Popen(["python", "myscript.py"], env = environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE) for setting it to UTF-8, however, it didn't work. Any idea on how to achieve this? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From steve at holdenweb.com Thu Aug 23 00:11:29 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 23 Aug 2007 00:11:29 -0400 Subject: Learning Python using a book based on version 1.5 In-Reply-To: References: <1187814437.775758.159510@e9g2000prf.googlegroups.com> Message-ID: James Stroud wrote: > dogatemycomputer at gmail.com wrote: >> Greetings, >> >> A friend of mine dropped off a copy of Sams Teach Yourself Python in >> 24 Hours published in 2000. I skimmed the first couple of chapters >> looking for the interpreter version and the book was based on version >> Python version 1.5. >> >> Is this book still relevant? Should I toss it and look for something >> newer? >> >> Any thoughts would be appreciated. >> >> Best Regards, >> Dave >> > > If you want to make a decision based on a quorum, I would suggest to not > bother with that book. Yes the SAMS TY books are usually great > (especially anything Laura Lemay), but you if you use a 1.5 book, you > will be learning some stuff you will *need* to unlearn at the expense of > learning things you should know. > > I think the online tutorial is the way to go, or the newest Learning > Python from Lutz. After that, check out TPIP (Mertz) or the Programming > Python book from Lutz (for a global-esque view of the python world). > Maybe even think about the Cookbook (ed. Martelli). > > Dive-Into-Python starts with one of those "Don't worry about what all > this means" examples, which I tend to hate and so I never got passed the > first example--it may get better as you go judging from all of its > proponents. > I'm not sure I'd agree here. Certainly you will learn things that can be updated as you get to newer versions of Python, but there are relatively few backward incompatibilities, so your code will mostly work in newer versions without (too many) modifications. By all means look for something newer, but don't let that search stop you from getting started with the book you have. Andrew Kuchling has written a great series of "What's new in Python X.Y" articles that can bring you up to date relatively quickly once you are fluent in version 1.5. Start with: http://www.python.org/download/releases/2.0/new-python And welcome to the Python community. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From timid.gentoo at gmail.com Mon Aug 13 06:07:14 2007 From: timid.gentoo at gmail.com (_spitFIRE) Date: Mon, 13 Aug 2007 05:07:14 -0500 Subject: retrieving ATOM/FSS feeds In-Reply-To: <1i2s7c9.13bkwbfsd3mbqN%raims@dot.com> References: <1i2s7c9.13bkwbfsd3mbqN%raims@dot.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Lawrence Oluyede wrote: > If the content producer doesn't provide the full article via RSS/ATOM > there's no way you can get it from there. Search for full content feeds > if any, otherwise get the article URL and feed it to BeautifulSoup to > scrape the content. > For the same feed (where the content producer doesn't provide the full article!) I was able to see the complete post in other RSS aggregators (like Blam). I wanted to know how they were able to collect the feed! I knew for sure that you can't do screen scraping separately for each and every blog and that there has be a standard way or atleast that blogs maintain a standard template for rendering posts. I mean if each of the site only offered partial content and the rest had to be scraped from the page, and the page maintained a non-standard structure which is more likely, then it would become impossible IMHO for any aggregator to aggregate feeds! I shall for now try with BeautifulSoup, though I'm still doubtful about it. - -- _ _ _]{5pitph!r3}[_ _ _ __________________________________________________ ?I'm smart enough to know that I'm dumb.? - Richard P Feynman -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGwC1SA0th8WKBUJMRAs4eAJ0bLJVzEZls1JtE6e8MUrqdapXGPwCfVO02 yYzezvhJFY1SDHUGxrJdR5M= =rfLo -----END PGP SIGNATURE----- From attn.steven.kuo at gmail.com Wed Aug 29 11:15:16 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Wed, 29 Aug 2007 08:15:16 -0700 Subject: strange list comprehension on generator In-Reply-To: References: Message-ID: <1188400516.913614.129770@q4g2000prc.googlegroups.com> On Aug 29, 6:50 am, Roland Puntaier wrote: > def changeOne(aa,idx): > aa[idx]=not aa[idx] > yield aa > for i in range(idx): > for x in changeOne(aa,i): > yield x > > def changeOneOrder(aa): > yield aa > for i in range(len(aa)): > for x in changeOne(aa,i): > yield x > > a=[False]*3 > og=changeOneOrder(a) > #this does not return the way I would expect. why? > list(og) > #returns > #[[False, False, True], [False, False, True], [False, False, True], > [False, False, True], [False, False, True], [False, False, True], [False, > False, True], [False, False, True]] If you want the "intermediate" states of 'a' in list(og), then you need to yield a copy of that list, instead of the list itself: def changeOne(aa, idx): aa[idx] = not aa[idx] yield aa[:] # <------- a copy for i in range(idx): for x in changeOne(aa, i): yield x def changeOneOrder(aa): yield aa[:] # <------- a copy for i in range(len(aa)): for x in changeOne(aa, i): yield x a = [False] * 3 og = changeOneOrder(a) print list(og) Otherwise, as you've already noticed, you can loop over the iterator and do something with the "instantaneous" state of 'a'. -- Hope this helps, Steven From lycka at carmen.se Wed Aug 1 07:13:19 2007 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 01 Aug 2007 13:13:19 +0200 Subject: Python end of file marker similar to perl's __END__ In-Reply-To: <1185940391.135261.130950@i38g2000prf.googlegroups.com> References: <1185940391.135261.130950@i38g2000prf.googlegroups.com> Message-ID: beginner wrote: > Hi All, > > This is just a very simple question about a python trick. > > In perl, I can write __END__ in a file and the perl interpreter will > ignore everything below that line. This is very handy when testing my > program. Does python have something similar? raise SystemExit() exits the program at that point (unless you catch the exception...) "import sys;sys.exit(0)" is basically another spelling of the same thing. It doesn't mean that the interpreter ignores the rest of the file though, so it will complain about syntax in the whole file. Since I don't usually write linear top-to-bottom scripts in Python, I don't really see the use of splitting a file in an interpreted top and an ignored bottom though. I'd suggest employing a test driven approach to development. Then you don't usually have big chunks of code that you don't want to run. All that's there works (almost)... See e.g. http://powertwenty.com/kpd/downloads/TestDrivenDevelopmentInPython.pdf From horpner at yahoo.com Wed Aug 1 10:51:34 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 01 Aug 2007 14:51:34 GMT Subject: Python end of file marker similar to perl's __END__ References: <1185940391.135261.130950@i38g2000prf.googlegroups.com> <1185976656.753817.27980@x40g2000prg.googlegroups.com> Message-ID: On 2007-08-01, beginner wrote: > Thanks everyone for responding. It doesn't look like python has > it. I would definitely miss it. As Steve said, the nice thing > about __END__ is that things below __END__ do not have to have > legit syntax. That let me focus on the lines of code I am > debugging and do not have to worry about some bad syntax down > the line. This feature is especially handy if I am, saying, > replacing modoules or changing data structures. A C-like trick might be helpful while refactoring: if False: You have to indent all the non-working code by one level, but with a good editor that's a snap. Python will still parse the following lines (it must be valid Python syntax), but the resulting parse tree won't be executed. -- Neil Cerutti From rrs at researchut.com Thu Aug 16 13:25:26 2007 From: rrs at researchut.com (Ritesh Raj Sarraf) Date: Thu, 16 Aug 2007 22:55:26 +0530 Subject: Module imports during object instantiation References: <4c3vo4-u7k.ln1@learner.hq.netapp.com> <46c16ec9$0$405$426a34cc@news.free.fr> <1187205375.871837.254400@r34g2000hsd.googlegroups.com> <1187206998.252482.300780@a39g2000hsc.googlegroups.com> Message-ID: <6tdep4-0hf.ln1@learner.hq.netapp.com> Steve Holden wrote: > Ritesh Raj Sarraf wrote: >> On Aug 16, 12:16 am, Ritesh Raj Sarraf wrote: >>> On Aug 15, 11:42 pm, Neil Cerutti wrote: >>> > [...] >> Oops!!! Looks like I completely missed this. It _did_ print the error >> message. >> Apologies to all for not keeping a close eye on the error message. >> > Quite. It was obvious to many readers that you were fooling yourself > with a false hypothesis. The probability of something so fundamental > being wrong is vanishingly small. > Yes, and now I realize how I would have got into the stupid assumption that imports were never executed in a class' __init__() was because: * I defined an import within a class' __init__() * It used to get executed. * Then I used to make an assumption that calling it from one of the methods would work. But instead the module was never in the Namespace. And that led me to the mis-understanding that the import never got executed. What a fool am I. I think people gave a good reason when they mentioned about top-level imports. I would move ahead with keeping things simple. Thanks to all for your time and patience on this thread (At least, no one is yelling at me ;-) Ritesh -- If possible, Please CC me when replying. I'm not subscribed to the list. From martin at v.loewis.de Thu Aug 16 03:06:51 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 16 Aug 2007 09:06:51 +0200 Subject: threads, mutual exclusion, and lists In-Reply-To: References: <1187206583.255588.57920@e9g2000prf.googlegroups.com> Message-ID: <46C3F78B.9080305@v.loewis.de> >> My question is -- are python list operations atomic? If they are not, >> then I assume I need to put some mutual exclusion around the append() >> and pop() calls ? > > They are not, but there is one included in the standard library: > http://docs.python.org/dev/lib/module-Queue.html Why do you think they are not? Regards, Martin From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Aug 2 03:55:07 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 02 Aug 2007 09:55:07 +0200 Subject: Emacs + python In-Reply-To: <4vasi.139194$wG2.61677@newsfe17.lga> References: <4vasi.139194$wG2.61677@newsfe17.lga> Message-ID: <46b18ddb$0$25330$426a34cc@news.free.fr> hg a ?crit : (snip) > Are there any cscope & ECB equivalent for Python ? ECB (assuming we're talking about the same thing, ie Emacs Code Browser) works just fine with Python. From http Thu Aug 16 03:33:26 2007 From: http (Paul Rubin) Date: 16 Aug 2007 00:33:26 -0700 Subject: ElementTree surprise References: <7xd4xoxf16.fsf@ruckus.brouhaha.com> <87bqd89gkd.fsf@wilson.homeunix.com> <7x4pj0xax0.fsf@ruckus.brouhaha.com> <46c3fa3a$0$16098$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <7xfy2kx7ax.fsf@ruckus.brouhaha.com> Stefan Behnel writes: > So it's not even an ElementTree thing. ET just doesn't know what > exactly was in the original XML byte stream. A very simple way to > make sure you always get a string back is > >>> text = element.text or "" Thanks, I ended up doing something like that. What I wondered about the standard was whether it specified that parrot had no text node, as opposed to having an empty text node. I guess it doesn't matter, it just caught me by surprise. From martin at v.loewis.de Mon Aug 6 01:44:39 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Mon, 06 Aug 2007 07:44:39 +0200 Subject: Misleading wikipedia article on Python 3? In-Reply-To: <87y7gpr33a.fsf@pobox.com> References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> Message-ID: <46b6b548$0$26184$9b622d9e@news.freenet.de> John J. Lee schrieb: > "Martin v. L?wis" writes: > [... snip stuff I don't follow ...] >> However, it *is* a design goal to make 2.6 so that transition to >> 3k becomes simpler. That's not a 3k feature, but a 2.6 one. > > Not sure I care about this sort of thing for the purpses of my > question. I just wanted to know: is it easy to make my code so it > runs on 2.6 and 3.0, without funny stuff like a code translator? > Seems wikipedia said "yes" and Guido said "no". Neither of these are qualified to make any statements about your code. Only you can find out yourself. OTOH, neither of these *did* make any statement about *your* code. Regards, Martin From steve at holdenweb.com Wed Aug 1 11:31:49 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 01 Aug 2007 11:31:49 -0400 Subject: Floats as keys in dict In-Reply-To: <1i25pz7.3m2bya88wujkN%aleax@mac.com> References: <1i25pz7.3m2bya88wujkN%aleax@mac.com> Message-ID: Alex Martelli wrote: > Brian Elmegaard wrote: > >> I am making a script to optimiza by dynamic programming. I do not know >> the vertices and nodes before the calculation, so I have decided to >> store the nodes I have in play as keys in a dict. >> >> However, the dict keys are then floats and I have to round the values >> of new possible nodes in each step. When profiling I see that the most >> time consuming part of my script is rounding. >> >> Is there a faster way than round() or is there a better way to test >> than 'in' or should I store the keys in another way than a dict? > > You may want to consider keeping a sorted list and using standard > library module bisect for searches and insertions -- its behavior is > O(log N) for a search, O(N) for an insertion, but it might be that in > your case saving the rounding could be worth it. > > Otherwise, you need to consider a different container, based either on > comparisons (e.g. AVL trees, of which there are several 3rd party > implementations as Python extensions) or on a hashing function that will > give the same hash for two numbers that are "close enough" (e.g., hash > ignoring the lowest N bits of the float's mantissa for some N). > That might be a bit dangerous in cases close to changes in exponent, though, where you could get numbers that were very close but had hugely different mantissa values because their exponents were one different, no? > round() operates on decimals and that may not be as fast as working on > binary representations, but, to be fast, a helper function giving the > "hash of a binary-rounded float" would have to be coded in C (or maybe > use psyco). > Your first suggestion was better, I think. Bisect would do the job. I have always thought that dict's numerical index semantics were suspect, but it's probably way too late to alter that now. [I'm assuming that Py3.0 is retaining the numerical equivalence relations]. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From gur.tom at gmail.com Tue Aug 28 08:45:07 2007 From: gur.tom at gmail.com (Tom Gur) Date: Tue, 28 Aug 2007 12:45:07 -0000 Subject: Embedding the python interpreter Message-ID: <1188305107.028128.136960@d55g2000hsg.googlegroups.com> Hey, Do you know an easy way to embed the python interpreter in a python program (so a non-technical user, which has no idea how to install the python interpreter would be able to run the script as an executable) ? From BerndWill at googlemail.com Sat Aug 11 05:04:36 2007 From: BerndWill at googlemail.com (OpenPavilion) Date: Sat, 11 Aug 2007 09:04:36 -0000 Subject: question: howto transfer objects between server and client? Message-ID: <1186823076.923464.294120@57g2000hsv.googlegroups.com> Hello community, maybe one of you can help me out with a question regarding the transfer of objects betwen client an server: I have three files: ####### ClassA.py ####### class ClassA: def setA(self, newA): self.a = newA def getA(self): return self.a ####### client.py ####### import xmlrpclib from ClassA import * a = ClassA() a.setA(4711) server = xmlrpclib.ServerProxy("http://localhost:8888") print server.getA(a) # <= here I would like to hand over an object ####### server.py ####### import SimpleXMLRPCServer from ClassA import * class Handler: def getA(self, aClass): return aClass.getA() # <- XMLRPC only transports simple types and dictionaries, but no objects handler_object = Handler() server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8888)) server.register_instance(handler_object) print "Listening on port 8888" server.serve_forever() The problem is, that though I hand a ClassA object to the XMLRPC server, the server only receives a dictionary (only transfering simple objects is a XMLRPC feature: http://docs.python.org/lib/module-xmlrpclib.html) Since XMLRPC has limited features: Is there any other server/client technique to transfer objects (not strings, or dictionaries, but self defined object types) ? Regards Bernd From python at jayloden.com Sun Aug 5 12:54:35 2007 From: python at jayloden.com (Jay Loden) Date: Sun, 05 Aug 2007 12:54:35 -0400 Subject: Submit web form only client-side with Python? COM? In-Reply-To: References: <1186257525.483524.5570@j4g2000prf.googlegroups.com> <7xmyx7ot0c.fsf@ruckus.brouhaha.com> <46B4FAFF.205@jayloden.com> Message-ID: <46B600CB.8010002@jayloden.com> Gabriel Genellina wrote: > En Sat, 04 Aug 2007 19:17:35 -0300, Jay Loden > escribi?: > >> Paul Rubin wrote: >>> goldtech writes: >>>> So I can present the user with an HTML form in it - but how can I >>>> write the form data to a local file on my work station? >>> The simplest way is with the cgi and CGIHTTPServer modules. You'd >>> write your form in an html file, with the target set to a Python >> CGIHTTPServer is not available on Windows (OP said they are on Win XP) > > CGIHTTPServer does work on Windows (even on Python 2.1, as far as I can > go) and using it might be simple enough. Hrm, if so then it's a documentation bug. That's actually good news then in this case :-) (see http://www.python.org/doc/2.1/lib/module-CGIHTTPServer.html ) [snip...] > I can't see any other reply from you on this thread... (I'm using the > gmane newsgroup interfase) It's under the title "Client-side HTML form processing with Python?", apparently the same post is listed twice or something like that. -Jay From bdesth.quelquechose at free.quelquepart.fr Fri Aug 24 09:39:26 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 24 Aug 2007 15:39:26 +0200 Subject: some problems with mod_python In-Reply-To: <1188245587.129794.258250@z24g2000prh.googlegroups.com> References: <1188245587.129794.258250@z24g2000prh.googlegroups.com> Message-ID: <46d337a1$0$422$426a74cc@news.free.fr> Johan a ?crit : > Hi > > I have installed and tested this on centos, fedora and freebsd all > give the same problem so I guess I missed some steps. > > I have compiled bot apache (2.2.4) and mod_python (3.3.1) according to > the docs and no problem with this. > But when I have made everything about testing mod_python an browse to > http://server/test and there expecting to see "Hello world" I instead > get an index of contents in this directory. If I go to http://server/test/mptest.py > it works. No errors in any log either. > > What Have I missed? The difference between AddHandler and SetHandler in apache's conf. > This I added to httpd.conf > > AllowOverride All > AddHandler mod_python .py > PythonHandler mptest > PythonDebug On > Your problem is with Apache configuration, not with mod_python. The AddHandler directive maps /*.py to your handler. So you have to call .py to trigger the desired behaviour. If you want *any* url under to be handled by mptest, you need to use SetHandler, not AddHandler. From python at jayloden.com Wed Aug 1 18:49:14 2007 From: python at jayloden.com (Jay Loden) Date: Wed, 01 Aug 2007 18:49:14 -0400 Subject: Bug in Time module, or in my understanding? In-Reply-To: References: Message-ID: <46B10DEA.4050005@jayloden.com> Joshua J. Kugler wrote: > I am getting results like these with the time module: > >>>> import time >>>> int(time.mktime(time.strptime('2007-03-11 02:00:00', '%Y-%m-%d %H:%M > %S'))) > 1173610800 >>>> int(time.mktime(time.strptime('2007-03-11 03:00:00', '%Y-%m-%d %H:%M > %S'))) > 1173610800 >>>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1173610800)) > '2007-03-11 03:00:00' > > I know it probably has something to do with daylight savings, but how can I > get back out that which I put in? The times concerned are all standard > time, so how can I keep the time module from asserting its belief that I > want to convert to daylight savings? > > Incidentally, it only happens with times on 2007-03-11 from 02:00:00 to > 02:59:59, and not with time data from past years. I *think* what's happening is that time.strptime() is setting the DST flag to "-1" for Unknown. The docs say this happens by default if it's not specified in the string: >>> time.strptime('2007-03-11 02:00:00', '%Y-%m-%d %H:%M:%S') (2007, 3, 11, 2, 0, 0, 6, 70, -1) >>> time.strptime('2007-03-11 03:00:00', '%Y-%m-%d %H:%M:%S') (2007, 3, 11, 3, 0, 0, 6, 70, -1) If you try calling time.mktime() with the flag unset you get the same result for both (note that I'm in an eastern time zone so it doesn't match yours exactly), and if it's set, you get a different result: >>> time.mktime((2007, 3, 11, 3, 0, 0, 6, 70, -1)) 1173596400.0 >>> time.mktime((2007, 3, 11, 2, 0, 0, 6, 70, 0)) 1173596400.0 >>> time.mktime((2007, 3, 11, 2, 0, 0, 6, 70, 1)) 1173592800.0 Not sure what your input is from, but can you maybe change the string to include the time zone? >>> time.mktime(time.strptime('2007-03-11 03:00:00 EST', '%Y-%m-%d %H:%M:%S %Z')) 1173600000.0 >>> time.mktime(time.strptime('2007-03-11 02:00:00 EST', '%Y-%m-%d %H:%M:%S %Z')) 1173596400.0 Hope some of this helps -J From steve at holdenweb.com Wed Aug 8 11:22:54 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 08 Aug 2007 11:22:54 -0400 Subject: Seek the one billionth line in a file containing 3 billion lines. In-Reply-To: <4866bea60708080658l170bd9eevd86cf58dbc1eddd8@mail.gmail.com> References: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> <7xzm12o7o7.fsf@ruckus.brouhaha.com> <1186555297.877273.40540@o61g2000hsh.googlegroups.com> <874pja70p5.fsf@benfinney.id.au> <4866bea60708080658l170bd9eevd86cf58dbc1eddd8@mail.gmail.com> Message-ID: <46B9DFCE.7000505@holdenweb.com> Chris Mellon wrote: > On 8/8/07, Ben Finney wrote: >> Sullivan WxPyQtKinter writes: >> >>> On Aug 8, 2:35 am, Paul Rubin wrote: >>>> Sullivan WxPyQtKinter writes: >>>>> This program: >>>>> for i in range(1000000000): >>>>> f.readline() >>>>> is absolutely every slow.... >>>> There are two problems: >>>> >>>> 1) range(1000000000) builds a list of a billion elements in memory >> [...] >>>> 2) f.readline() reads an entire line of input >> [...] >>> Thank you for pointing out these two problem. I wrote this program >>> just to say that how inefficient it is to use a seemingly NATIVE way >>> to seek a such a big file. No other intention........ >> The native way isn't iterating over 'range(hugenum)', it's to use an >> iterator. Python file objects are iterable, only reading eaach line as >> needed and not creating a companion list. >> >> logfile = open("foo.log", 'r') >> for line in logfile: >> do_stuff(line) >> >> This at least avoids the 'range' issue. >> >> To know when we've reached a particular line, use 'enumerate' to >> number each item as it comes out of the iterator. >> >> logfile = open("foo.log", 'r') >> target_line_num = 10**9 >> for (line_num, line) in enumerate(file): >> if line_num < target_line_num: >> continue >> else: >> do_stuff(line) >> break >> >> As for reading each line: that's unavoidable if you want a specific >> line from a stream of variable-length lines. >> > > The minimum bounds for a line is at least one byte (the newline) and > maybe more, depending on your data. You can seek() forward the minimum > amount of bytes that (1 billion -1) lines will consume and save > yourself some wasted IO. Except that you will have to count the number of lines in that first billion characters in order to determine when to stop. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From joshua at eeinternet.com Wed Aug 1 19:08:36 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 01 Aug 2007 15:08:36 -0800 Subject: Bug in Time module, or in my understanding? References: <1186008332.730742.56520@w3g2000hsg.googlegroups.com> Message-ID: On Wednesday 01 August 2007 14:45, Paul Boddie wrote: > Well, I think that if you inspect the result of strptime, you'll see > that the last element of the time "tuple" - in fact, the tm_isdst > member of a time "structure" - is set to -1: > >>>> time.strptime('2007-03-11 02:00:00', '%Y-%m-%d %H:%M:%S') > (2007, 3, 11, 2, 0, 0, 6, 70, -1) >>>> time.strptime('2007-03-11 03:00:00', '%Y-%m-%d %H:%M:%S') > (2007, 3, 11, 3, 0, 0, 6, 70, -1) > > What is likely to happen when such results are passed to mktime is > that the underlying library function will use its discretion in > determining whether daylight savings time is in operation or not. That sounds about right. > By asserting tm_isdst as being 0, the usual apparent interval between > the times is preserved. I'll do that. This isn't so much about DST vs. non-DST (as I may be putting values in here that were recorded during DST), but in this case it was just trying to get the same value out that I had put in. Thanks for the pointers! j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE From labrach at gmail.com Fri Aug 31 07:54:17 2007 From: labrach at gmail.com (labrach at gmail.com) Date: Fri, 31 Aug 2007 11:54:17 -0000 Subject: python + gcov In-Reply-To: References: <1188404571.590476.265840@r34g2000hsd.googlegroups.com> <1188472743.570376.120390@o80g2000hse.googlegroups.com> Message-ID: <1188561257.559682.255040@19g2000hsx.googlegroups.com> > I always bit the bullet and finally just did that. and here the steps to follow ... http://plexity.blogspot.com/2006/02/profiling-python-extensions.html laurent From grante at visi.com Wed Aug 15 18:13:52 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 15 Aug 2007 22:13:52 -0000 Subject: wxPython before MainLoop References: <13bl9a75laqcm70@corp.supernews.com> <13bnh5bs4b9h427@corp.supernews.com> <5i3b1jF3n5bdtU1@mid.individual.net> <13c1v79hs0dob3@corp.supernews.com> <13c27q5meq90lb2@corp.supernews.com> Message-ID: <13c6ul0g7crj8a4@corp.supernews.com> On 2007-08-14, [david] wrote: > Steve, it wasn't me that raised the comparison > with MFC. If you don't think that's a helpful > comparison, why not reply to that post instead? > > I don't mind Bj?rn's suggestion that I don't > know what I'm talking about, because I started > it by telling him he was wrong. > > But you don't have that excuse. > > (david) Oh dear, arguing with Steve Holden is a rather inauspicious way to start out in c.l.p. -- Grant Edwards grante Yow! CHUBBY CHECKER just at had a CHICKEN SANDWICH in visi.com downtown DULUTH! From jingwu.mail at gmail.com Tue Aug 7 20:18:32 2007 From: jingwu.mail at gmail.com (jingwu.mail at gmail.com) Date: Wed, 08 Aug 2007 00:18:32 -0000 Subject: step through .py file in a .NET application written in C# in Visual Studio In-Reply-To: <1186493064.496160.296460@b79g2000hse.googlegroups.com> References: <1186438925.541501.235800@g4g2000hsf.googlegroups.com> <1186493064.496160.296460@b79g2000hse.googlegroups.com> Message-ID: <1186532312.523393.189010@l70g2000hse.googlegroups.com> On Aug 7, 9:24 am, Paul McGuire wrote: > On Aug 6, 5:22 pm, Bo wrote: > > > > > Hello All, > > > I am experimenting IronPython in Visual Studio. Here is what I have, > > what I did and what I want > > > 1. I have installed Visual Studio SDK 4.0 according to thisbloghttp://blogs.msdn.com/aaronmar/archive/2006/02/16/a-bit-more-on-ironp... > > > If I run Visual Studio under Experimental Hive, aPythonfile opened > > is color coded. > > > 2. Also, my computer has apparently installed some IronPython DLL > > because my Visual Studio can recoginize the following class: > > IronPython.Hosting.PythonEngine. > > > If I declare something like the following in Visual Studio: > > > public static class MyPythonClass { > > private static IronPython.Hosting.PythonEngine MY_ENGINE; > > //suppose I have created an instance of PhythonEngine and assigned > > to MY_ENGINE > > ............ > > > } > > > If I do "Go to Definition" of PythonEngine, I can navigate to the > > Definition of PythonEngine, but it is from MetaData. > > > 3. In my .NET application (written in C#) , I can invoke the > > execution of an externalpythonfile using something like: > > MyPythonClass.MY_ENGINE.ExecuteFile("myPythonFileWithAbsolutePath.py") > > > Thepythonfile (myPythonFileWithAbsolutePath.py) can be executed all > > right, but I want to step through it to debug it. Any suggestions on > > how to do it? > > > Thanks abunch. > > > Bo > > Um, make sure you compile with debug? > > I have coded in Boo, which is veryPython-like, and it will step > through the debugger just fine, so IP should do the same in theory. > But I've not used IP, so all I can give are generic "are you sure it's > plugged in?" type of suggestions. > > Hmm, upon rereading your post, I see that you want the debugger to > step through a separate file that was executed using ExecuteFile. > Unless there are some debug options on ExecuteFile, I'd say your > chances are slim, since the file being executed is not really part of > the image being debugged. You could also try explicitly invoking the > debugger from within the file that you are loading, using (this works > from Boo): > > System.Diagnostics.Debugger.Launch() > System.Diagnostics.Debugger.Break() > > -- Paul Thanks Paul, for giving me the suggestions. I will try your suggestion. I have been struggling with the most of today. Here is a summary of what I have found. May be useful to other 1. My IronPython DLL is version 1.1. It is download here http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython 2. Apparently, there is a problem with either the ipy.exe or IronPython.DLL that one cannot step into a function (F11 in visual studio). Here is the discussion http://lists.ironpython.com/pipermail/users-ironpython.com/2007-May/004957.html I am not sure if this is related to my case. 3. Here is Jim Hugunin's presentation http://msdn.microsoft.com/msdntv/episode.aspx?xml=episodes/en/20051110PythonJH/manifest.xml Apparently, he can step through the external ironpython file in an C# application. He probably used an old version of Iron Python. The method he used to execute the external iron python file is Engine.Runfile() From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Aug 26 17:20:36 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 26 Aug 2007 23:20:36 +0200 Subject: pySerial in a daemon process References: <1188158581.316824.89360@k79g2000hse.googlegroups.com> Message-ID: <5je954F3s0nilU1@mid.individual.net> paul wrote: > If I put these back in and try to run the daemon, the script fails > when I try to connect to the serial port, with this error: > serial.serialutil.SerialException: Could not open port: [Errno 13] > Permission denied: '/dev/ttyS0' Did you check the permissions on this file? Often you have to be member of a "dialout" group or similar to get access. Regards, Bj?rn -- BOFH excuse #172: pseudo-user on a pseudo-terminal From zzbbaadd at aol.com Thu Aug 30 19:42:50 2007 From: zzbbaadd at aol.com (zzbbaadd at aol.com) Date: Thu, 30 Aug 2007 16:42:50 -0700 Subject: list index() In-Reply-To: <87bqcod2gq.fsf@benfinney.id.au> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188495863.242815.236900@o80g2000hse.googlegroups.com> <87bqcod2gq.fsf@benfinney.id.au> Message-ID: <1188517370.998114.119940@q4g2000prc.googlegroups.com> On Aug 30, 4:31 pm, Ben Finney wrote: > zzbba... at aol.com writes: > > In my case of have done os.listdir() on two directories. I want to see > > what files are in directory A that are not in directory B. > > You get that information unambiguously. It's an exceptional case, > since there's no index to return, so it throws an exception. > > > I have used exceptions in other languages and only do so on logic > > that should never happen. > > You're confusing "assert" ("this should always be true") with > "exception" ("this is an exception to the the normal flow of this > process"). > > An exception isn't "something that should never happen", it's > something that is entirely possible and needs to be handled somehow. I don't think that is the definition used across computer science. It suddenly dawned on me that what would be best would be a contains() (or IN syntax for those who can't afford to wait) for lists. if mylist.contains("hello): > > -- > \ "Always do right. This will gratify some people, and astonish | > `\ the rest." -- Mark Twain | > _o__) | > Ben Finney From pydecker at gmail.com Sun Aug 12 08:50:25 2007 From: pydecker at gmail.com (Peter Decker) Date: Sun, 12 Aug 2007 08:50:25 -0400 Subject: Database intensive application In-Reply-To: <1186895306.237395.189530@z24g2000prh.googlegroups.com> References: <1186895306.237395.189530@z24g2000prh.googlegroups.com> Message-ID: On 8/12/07, Rohit wrote: > I am a novice. I want to know whether Python can be used to develop > client/server database and web applications like .NET. Which is the > best book/source to learn Python? You've already gotten several excellent answers for web applications; if you need to create client/server desktop database apps, your best (and AFAIK, only) choice would be Dabo: http://dabodev.com -- # p.d. From philip at corp.spock.com Sat Aug 11 18:32:30 2007 From: philip at corp.spock.com (Philip Zigoris) Date: Sat, 11 Aug 2007 15:32:30 -0700 Subject: Threading problem when many sockets open Message-ID: <75fd6670708111532g58fc78f6p6f5dc9de590c4d4a@mail.gmail.com> Hi all, I have written a socket based service in python and under fairly heavy traffic it performs really well. But i have encountered the following problem: when the system runs out of file descriptors, it seems to stop switching control between threads. Here is some more detail: The system has n+2 threads, where n is usually around 10. This was implemented using the 'threading' and 'socket' modules in the python 2.5 standard library. -- The "master" thread accepts new socket connections and then enqueues the connection on a Queue (from the standard library). -- There are n "handler threads" that pop a connection off of the queue, read some number of bytes (~10), do some processing and then send ~100 bytes back over the connection and close it. -- The last thread is just a logging thread that has a queue of messages that it writes to either stdout or a file. Under pretty substantial load, the processing is quick enough that the connections do not pile up very quickly. But, in some cases they do. And what I found was that as soon as the size of the Queue of connections reached a high enough number (and it was always the same), all of the processing seemed to stay in the "master" thread. I created a siege client that opened up 1000+ connections and the server would go into a state where the master thread repeatedly polled the socket and printed an error. The Queue size stayed fixed at 997 even if i shut down all of the connectionso n the client side. Under normal operating conditions, those connections would be detected as broken in the handler thread and a message would be logged. So it seems that the "handler" threads aren't doing anything. (And they are still alive, i check that in the master thread). OK. I hope all of this is clear. Currently, I've solved the problem by putting a cap on the queue size and i haven't seen the problem reoccur. But it would be nice to understand exactly what went wrong. Thanks in advance. -- -- Philip Zigoris I SPOCK I 650.366.1165 Spock is Hiring! www.spock.com/jobs From michael at jedimindworks.com Thu Aug 23 16:48:50 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 23 Aug 2007 13:48:50 -0700 Subject: simple spider in python In-Reply-To: <1187876014.845912.236690@e9g2000prf.googlegroups.com> References: <1187876014.845912.236690@e9g2000prf.googlegroups.com> Message-ID: On Aug 23, 2007, at 6:33 AM, gmcalendar at gmail.com wrote: > Hi everybody, i'm new to the forum so: hello everybody (should I say > "world"?) ^_^ > I'm trying to do a simple spider in python which: > > 1) ask google a query > 2) parse the data > > I'm a python newbie so *any* help would be very, very welcommed. > Thanks in advice! First thing to know is that google doesn't like the User-agent header urllib2 uses by default -- you'll have to masquerade as a browser (google throws a 403 error if you connect as 'User-Agent: Python- urllib/2.5': look into urllib2.build_opener()). Second thing to know is that the interesting results have class attribute set to "l". hope this helps, Michael --- Asking a person who he *is* ... is not Pythonic! --Anton Vredegoor From tommy.nordgren at comhem.se Mon Aug 20 07:08:21 2007 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Mon, 20 Aug 2007 13:08:21 +0200 Subject: Sorting a list of Unicode strings? In-Reply-To: <1187542237.139346.6910@o80g2000hse.googlegroups.com> References: <1187542237.139346.6910@o80g2000hse.googlegroups.com> Message-ID: On 19 aug 2007, at 18.50, oliver at obeattie.com wrote: > Hey Guys, > > Maybe I'm missing something fundamental here, but if I have a list of > Unicode strings, and I want to sort these alphabetically, then it > places those that begin with unicode characters at the bottom. Is > there a way to avoid this, and make it sort them properly? > > I'm sure that this is the "proper way" programatically with character > entities etc. - but when I have a list of countries, and I have ?land > Islands right at the bottom, it just doesn't look right. > > Any help would be really appreciated. > > Thanks, > Oliver > > -- > http://mail.python.org/mailman/listinfo/python-list That is the correct alfabetic sort order for ?land. The Swedish letters ? , ? and ? sorts last in Alphabetic order. ----------------------------------------------------- An astronomer to a colleague: -I can't understsnad how you can go to the brothel as often as you do. Not only is it a filthy habit, but it must cost a lot of money too. -Thats no problem. I've got a big government grant for the study of black holes. Tommy Nordgren tommy.nordgren at comhem.se From multiseed at gmail.com Tue Aug 21 18:27:43 2007 From: multiseed at gmail.com (Shiao) Date: Tue, 21 Aug 2007 22:27:43 -0000 Subject: Logging module gives duplicate log entries In-Reply-To: References: <1187702248.203917.188570@k79g2000hse.googlegroups.com> <1187731317.661324.244870@k79g2000hse.googlegroups.com> Message-ID: <1187735263.468497.147220@l22g2000prc.googlegroups.com> Maybe my question wasn't very clear. What I meant is that these four lines lead in my case to two entries per logged event: applog = logging.getLogger() applog.setLevel(logging.DEBUG) hdl = logging.FileHandler('/tmp/foo.log') applog.addHandler(hdl) However if I REPLACE the above by: logging.basicConfig(level=logging.DEBUG, filename='/tmp/foo.log') things work as expected. From kw at codebykevin.com Wed Aug 8 12:34:35 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 08 Aug 2007 12:34:35 -0400 Subject: Tkinter or wxpython? In-Reply-To: References: <7xlkcopu4r.fsf@ruckus.brouhaha.com> <7x7io8r6na.fsf@ruckus.brouhaha.com> <46B9DE7B.3050909@codebykevin.com> Message-ID: <46B9F09B.2060903@codebykevin.com> Chris Mellon wrote: > On 8/8/07, Kevin Walzer wrote: > Using Tile, of course, loses you the first major benefit of Tk - that > it's already included in the standard library. So in this sense it's > still "ugly old school look and feel" vs "no external dependencies", > which is the swing decision for many people. People who prefer the Tk > API, of course, will be happy to use Tile. Tile has been implemented in the Tk core starting with version 8.5, still somewhere between alpha and beta stage. Once 8.5 is out, and Python is configured to build against Tk 8.5 (instead of 8.4), it should Just Work. > > Also, while you can get (mostly) native *look*, the feel is absent. > Unless I'm very uninformed, Tile is a theming engine only, and doesn't > implement platform conventions with regard to behavior (the "feel" > part of look and feel). What do you mean here? Things like keyboard accelerators, menu placement, and so on? Those things are already natively implemented by Tk, and the developer just needs to invoke them. Sometimes some conditional code is required for stuff like keyboard accelerators (the "tk windowingsytem" command is useful for this), but again, it should Just Work. Or am I missing something? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From philippe.martin at att.net Sun Aug 26 19:13:07 2007 From: philippe.martin at att.net (hg) Date: Sun, 26 Aug 2007 23:13:07 GMT Subject: SCF (Python Smar Card Framework) Message-ID: <7OnAi.21500$eY.10887@newssvr13.news.prodigy.net> Dear all, I am releasing much of my work including SCF (Cross platform Smart Card library & Tools) to the GPL license. If interested, go to http://www.SnakeCard.com/Source.html I am moving the doc to doxygen and cleaning up the code, so what you'll see there will change in the course of the next few weeks - basically can only get meaningful info on the classes hierarchy at this stage. I am looking for a free subversion server resource to put the code ... if you know of any. Some of the work there will be windows-only related (GINA, activeX components ...) and the applets JavaCard and BasicCard ... I'm releasing these during the next few days. Regards, Philippe From evan at yelp.com Mon Aug 20 23:42:46 2007 From: evan at yelp.com (Evan Klitzke) Date: Mon, 20 Aug 2007 20:42:46 -0700 Subject: Retrieving a variable's name. In-Reply-To: <1187658202.236626.93600@50g2000hsm.googlegroups.com> References: <1187658202.236626.93600@50g2000hsm.googlegroups.com> Message-ID: On 8/20/07, rodrigo wrote: > How would I go about retrieving a variable's name (not its value)? I > want to write a function that, given a list of variables, returns a > string with each variable's name and its value, like: > > a: 100 > b: 200 Let me preface my response by saying that this is a really weird thing to do, and almost certainly _not_ what you want to be doing. If I was to run across code like this, I'd be appalled ;-) Here's one way to do it, however: def make_dict(*args): d = {} for arg in args: for key, value in globals().iteritems(): if value is arg: d[key] = value break return d Note that this returns a dictionary, rather than a string, but this is trivial to modify. -- Evan Klitzke From eugen.wintersberger at jku.at Thu Aug 16 08:07:47 2007 From: eugen.wintersberger at jku.at (Eugen Wintersberger) Date: Thu, 16 Aug 2007 14:07:47 +0200 Subject: ctypes and C99 complex numbers Message-ID: <1187266067.24753.12.camel@wheeler.hlphys.uni-linz.ac.at> Hi there I want to use ctypes in connection with C functions that use complex datatypes defined in the C99 standard. Does someone know a simple way how to implement this? Are there any plans to integrate the C99 complex data types in the ctypes module? best regards Eugen Wintersberger -- -------------------------------------------- | | | Dipl. Ing. Eugen Wintersberger | | Department of semicondutor physics | | University of Linz | | Altenbergerstrasse 69 | | A-4040 Linz | | Austria | | | | Mobile.: +43 664 3112861 | | Tel.: +43 732 2468 9605 | | E-Mail.: eugen.wintersberger at jku.at | | Skype: eugen20056221 | | ICQ: 214418739, nickname: thot | | | -------------------------------------------- From lance.ellinghaus at eds.com Wed Aug 22 11:43:22 2007 From: lance.ellinghaus at eds.com (Ellinghaus, Lance) Date: Wed, 22 Aug 2007 11:43:22 -0400 Subject: SpreadsheetML writer?? In-Reply-To: References: <1187596936.136499.200280@l22g2000prc.googlegroups.com><46cc26ed$0$432$426a74cc@news.free.fr> Message-ID: <752A61D5C34D41478E638FC92AF9051B014F2FD8@usahm207.amer.corp.eds.com> Does anyone have or know of a module to write out Excel spreadsheets in SpreadsheetML format? Thank you, lance Lance Ellinghaus From nospam at invalid.com Sun Aug 19 22:55:33 2007 From: nospam at invalid.com (Jack) Date: Sun, 19 Aug 2007 19:55:33 -0700 Subject: Parser Generator? References: <_6mdnZxbdNKTVFrbnZ2dnUVZ_tqtnZ2d@comcast.com> <1i33g9h.1i48q26dmp7l5N%aleax@mac.com> Message-ID: Very interesting work. Thanks for the link! "Alex Martelli" wrote in message news:1i33g9h.1i48q26dmp7l5N%aleax at mac.com... > > > """ > NLTK ?? the Natural Language Toolkit ?? is a suite of open source Python > modules, data sets and tutorials supporting research and development in > natural language processing. > """ > > > Alex From mail at microcorp.co.za Fri Aug 17 04:08:09 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 17 Aug 2007 10:08:09 +0200 Subject: (sort of) deterministic timing in Python References: <1i2si8h.1qc8f77i68gyeN%johnmfisher@comcast.net> <7xlkcbgto6.fsf@ruckus.brouhaha.com> Message-ID: <017501c7e0a6$cff9dc40$03000080@hendrik> "Paul Rubin" wrote: >johnmfisher at comcast.net (John Fisher) writes: >> mark start time >> start event >> event finishes >> count time until next interval >> start second event??? >> >> rather than this: >> >> start event >> event finishes >> sleep for interval >> start second event >> ... >> So how do I accomplish this in Python with a minimum of labour? > >Normally I'd use something like: > > from time import time > > t0 = time() > start event ... event finishes > t1 = time() > elapsed = t1 - t0 > sleep(interval - elapsed) > start second event ... > >Am I missing something? Not much - only beware of cases when elapsed is greater than interval - not sure what time.sleep(negative_number) does. - Hendrik From rkmr.em at gmail.com Fri Aug 10 12:57:05 2007 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Fri, 10 Aug 2007 09:57:05 -0700 Subject: AttributeError: 'module' object has no attribute 'HTTPSHandler' Message-ID: Hi I built and installed python 2.5 from source and when I do this: opener = urllib2.build_opener(SmartRedirectHandler(), DefaultErrorHandler(), urllib2.HTTPSHandler()) I get this error. AttributeError: 'module' object has no attribute 'HTTPSHandler' What should I do? From crosseyedpenguin at digitalrockart.phxcoxmail.com Sun Aug 5 16:01:40 2007 From: crosseyedpenguin at digitalrockart.phxcoxmail.com (Roger) Date: Sun, 05 Aug 2007 13:01:40 -0700 Subject: smtplib, gmail, quit vs. close and SSL3_GET_RECORD:wrong version number Message-ID: I am having a problem sending email through smtp.gmail.com using smtplib. Everything works and the mail is sent and received, except quit. The following shows the problem (without bothering to login or do the sendmail): >>>> import smtplib >>>> server = smtplib.SMTP('smtp.gmail.com',25) >>>> server.ehlo() > (250, 'mx.google.com at your service, [68.98.218.211]\nSIZE 28311552\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES') >>>> server.starttls() > (220, '2.0.0 Ready to start TLS') >>>> server.ehlo() > (250, 'mx.google.com at your service, [68.98.218.211]\nSIZE 28311552\n8BITMIME\nAUTH LOGIN PLAIN\nENHANCEDSTATUSCODES') >>>> server.noop() > (250, '2.0.0 OK') >>>> server.quit() > > Traceback (most recent call last): > File "", line 1, in > server.quit() > File "c:\Python25\lib\smtplib.py", line 716, in quit > self.docmd("quit") > File "c:\Python25\lib\smtplib.py", line 378, in docmd > return self.getreply() > File "c:\Python25\lib\smtplib.py", line 352, in getreply > line = self.file.readline() > File "c:\Python25\lib\smtplib.py", line 160, in readline > chr = self.sslobj.read(1) > sslerror: (1, 'error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number') >>>> I have not had this problem with other mail servers (but only tried two). A solution for gmail seems to be to replace the server.quit() with server.close(). The difference between the two commands is quit() sends a 'QUIT' string before calling close(). Because close() is not included in the smtplib docs, it does not appear to be the right solution. What is the correct way to terminate a gmail session? Roger From nobody at nowh.ere Tue Aug 21 17:11:34 2007 From: nobody at nowh.ere (John McGaw) Date: Tue, 21 Aug 2007 17:11:34 -0400 Subject: Latest models of Gibson guitars In-Reply-To: <1187544898.289948.322160@22g2000hsm.googlegroups.com> References: <1187544898.289948.322160@22g2000hsm.googlegroups.com> Message-ID: <%xIyi.22058$aa7.17937@bignews3.bellsouth.net> mobilendd at gmail.com wrote: > Reviews of latest models of best guitars, fender, gibson, yamaha, and > many more, with pictures and prices. Are these new guitars made of SPAM like your message and your "blog"? From oliver at obeattie.com Sun Aug 19 12:50:37 2007 From: oliver at obeattie.com (oliver at obeattie.com) Date: Sun, 19 Aug 2007 16:50:37 -0000 Subject: Sorting a list of Unicode strings? Message-ID: <1187542237.139346.6910@o80g2000hse.googlegroups.com> Hey Guys, Maybe I'm missing something fundamental here, but if I have a list of Unicode strings, and I want to sort these alphabetically, then it places those that begin with unicode characters at the bottom. Is there a way to avoid this, and make it sort them properly? I'm sure that this is the "proper way" programatically with character entities etc. - but when I have a list of countries, and I have ?land Islands right at the bottom, it just doesn't look right. Any help would be really appreciated. Thanks, Oliver From pablo.yabo at gmail.com Fri Aug 10 19:31:37 2007 From: pablo.yabo at gmail.com (Pablo Yabo) Date: Fri, 10 Aug 2007 20:31:37 -0300 Subject: Threading Message-ID: Hello, I'm trying to call Python routines from C/C++. These routines must intereact in a multi-thread environment. I mean that routine A will loop waiting for a condition of routine B. This condition are coded in C so I don't need routine A running in the same interpreter of routine B. I tried using: PyEval_AcquireLock(); PyInterpreterState* mainInterpreterState = mainThreadState->interp; PyThreadState * myThreadState = PyThreadState_New(mainInterpreterState); PyThreadState_Swap(myThreadState); ... Call Python code here PyThreadState_Swap(NULL); PyEval_ReleaseLock(); Obviosly, I called thread initialization code in the main thread like http://www.linuxjournal.com/article/3641 The problem with this code is that I hold the interpreter lock when calling routine A or B so they cannot run simultaneous and that is a requierement for me (as I explained before). It executes some code of the routine I called but then it hungs. If I release the lock before calling the Python code it doesn?t work neither somhow. Then I tried to create an interpreter for each thread. It is not desirable but it's acceptable: PyEval_AcquireLock(); PyThreadState* myThreadState = Py_NewInterpreter(); PyThreadState_Swap(myThreadState); PyEval_ReleaseLock(); ... Call Python code here PyEval_AcquireLock(); PyThreadState_Swap(NULL); Py_EndInterpreter(myThreadState); PyEval_ReleaseLock(); But it doesn't work. It seems that it requieres to take the lock to call Python code. If I comment the PyEval_ReleaseLock line and PyEval_AcquireLock pair it calls other threads before hunging. I saw some threads talking about some similar situations and I saw no answer to this. This issue remains unsolved? Thanks on advance, Pablo -- http://www.nektra.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bill.scherer at verizonwireless.com Thu Aug 23 07:46:25 2007 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Thu, 23 Aug 2007 07:46:25 -0400 Subject: sentance containg the string or symbol =?UTF-8?B?zqk=?= In-Reply-To: References: Message-ID: <46CD7391.8040002@verizonwireless.com> yadin wrote: > how can i print a sentance containg the string or symbol ? in python > and also lambda? > > >>> "?" '\xce\xa9' >>> print '\xce\xa9' ? >>> ...works on my terminal anyway. -------------- next part -------------- An HTML attachment was scrubbed... URL: From siona at chiark.greenend.org.uk Tue Aug 14 12:46:03 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 14 Aug 2007 17:46:03 +0100 (BST) Subject: LEGB rule, totally confused ... References: Message-ID: <3u*sChSr@news.chiark.greenend.org.uk> stef mientki wrote: > def Run (): > print X <=== UnboundLocalError: local variable > 'X' referenced before assignment > X = X + 1 > >Why do I get the error ? >Printing isn't assigning anything or am I missing something. >Now if I remove "X = X + 1" I don't get an error ??? Several people have already explained the scoping rules acting here, but let's just look at how that error message is telling you everything you need to know to fix the problem. "local variable 'X' referenced before assignment" "local variable 'X'" immediately tells you that the 'X' in question is not your global 'X'. "referenced before assignment": well, 'print X' is surely a reference to 'X', and 'X = X + 1' is an assignment to it, and 'print X' appears before 'X = X + 1'. That this is the key you have confirmed experimentally. The question to ask here is "Why does Python think 'X' is local?" Everything else is answered by the error message. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From hyugaricdeau at gmail.com Thu Aug 30 09:29:06 2007 From: hyugaricdeau at gmail.com (Hyuga) Date: Thu, 30 Aug 2007 13:29:06 -0000 Subject: Asking all python programmers. In-Reply-To: References: Message-ID: <1188480546.990325.252350@r29g2000hsg.googlegroups.com> On Aug 29, 11:09 am, "sjpiii" wrote: > You mean use correct spelling and grammar? But what about all the time > we've spent creating cutesy little non-words like "l8er?" > > Actually, I'm less tolerant of those than of normal spelling and grammar > errors because of the number of posters here for whom english is not their > native language. What I find worst of all, however, are people for whom English is not their first language, *and* they write in lazy, slangy AOL-speak. Making mistakes is fine, and even being completely incomprehensible is bearable if it looks like an effort was made to use the language correctly. I don't know about anyone else, but when I'm learning a new language, spoken or programming, I try my best to use it is correctly as possible given my level of experience with it. Using slang and shorthand correctly really requires you to know what you're doing--sort of like optimizing. From gandalf at shopzeus.com Thu Aug 16 16:48:26 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 16 Aug 2007 22:48:26 +0200 Subject: advice about `correct' use of decorator In-Reply-To: <46C4B097.4080309@fmed.uba.ar> References: <46C4B097.4080309@fmed.uba.ar> Message-ID: <46C4B81A.8000304@shopzeus.com> Gerardo Herzig wrote: > Hi all. I guess i have a conceptual question: > Im planing using a quite simple decorator to be used as a conditional > for the execution of the function. I mean something like that: > > @is_logued_in > def change_pass(): > bla > bla > > And so on for all the other functions who needs that the user is still > loged in. > > where obviosly the is_logued_in() function will determine if the dude is > still loged in, and THEN execute change_pass(). If the dude is not loged > in, change_pass() is NOT executed at all. Instead, it will be redirected > to the `login' screen. > Are you developing a website or a GUI program? Laszlo From ocollioud at gmail.com Fri Aug 24 05:31:40 2007 From: ocollioud at gmail.com (olive) Date: Fri, 24 Aug 2007 09:31:40 -0000 Subject: Co-developers wanted: document markup language In-Reply-To: <87mywh717i.fsf@wilson.homeunix.com> References: <87odgyyx9u.fsf@wilson.homeunix.com> <87tzqpew22.fsf@wilson.homeunix.com> <87tzqp77my.fsf@wilson.homeunix.com> <7xy7g1if24.fsf@ruckus.brouhaha.com> <87mywh717i.fsf@wilson.homeunix.com> Message-ID: <1187947900.676122.144490@e9g2000prf.googlegroups.com> > > Well, because they are awful. ;-) I don't see that there is a > bunch of already existing projects, in fact, I don't see anyone > challenging LaTeX at all. However, competition is a good thing, and > I think there are enough aspects about LaTeX that can be done better > so that this project is worth being done. What about ODF ? (http://www.odfalliance.org/) Isn't it a good competitor ? Olive From mail at microcorp.co.za Fri Aug 24 05:21:41 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 24 Aug 2007 11:21:41 +0200 Subject: Socket recv(1) seems to block instead of returning end of file. References: <13cr4u8mimniub4@corp.supernews.com> Message-ID: <014f01c7e65d$82cd7b40$03000080@hendrik> "Grant Edwards" wrote: > On 2007-08-23, Hendrik van Rooyen wrote: > > > While doing a netstring implementation I noticed that if you > > build a record up using socket's recv(1), then when you close > > the remote end down, the recv(1) hangs, > > I don't see that behavior running 2.4 on Gentoo. I express myself badly - when I say "close down" I don't mean "close down as in socket.close" I mean "close down as in click on the tkinter window, or with keyboard interrupt" - sorry for the confusion > > > despite having a short time out of 0.1 set. > > What time out? A socket's recv method doesn't do timeouts. If I set a time out, then the recv does not block, but gives me a timed out exception. > > > If however, you try to receive more than one char, (I tested > > with 3, did not try 2), then when you shut the remote end down > > you do not get a time out, but an empty string - the normal > > end of file, I suppose. > > > > Has anybody else seen this behaviour? > > No. recv(1) works fine for me (Python 2.4 under Gentoo). > Perhaps you could post a minimal example that doesn't work for > you? I am now frustrated - its not as simple as I thought - my application still only detects EOF if I do more than recv(1), but I cannot demonstrate simply - anyway, I have modified your code to look more like my program's code, and it follows below - if it does nothing else, it should convince you that recv() *does* time out... The receiver code below detects if I close the sending console window, as well as control-c - Rats! I will muck around with this more to see if I can get to the bottom of it, as I can't see anything different between what is below and my program, except that in both cases the comms are done in threads which are not the main loop. - Hendrik ------------------------------------------------------------------------ #!/usr/bin/python #reader import socket HOST = 'Linuxbox' # Symbolic name meaning the local host PORT = 57001 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) socket.setdefaulttimeout(0.100) s.listen(1) conn, addr = s.accept() print 'Connected by', addr data = '' while 1: try: data = data + conn.recv(1) except socket.error,msg: if 'timed out' in msg: print msg continue else: print 'socket error is',msg break if not data: break if data.endswith('\n'): print data data = '' print 'heigh ho the end has come!' conn.close() ------------------------------------------------------------------------ ------------------------------------------------------------------------ #!/usr/bin/python # writer import socket,time,random HOST = 'Linuxbox' # Symbolic name meaning the local host PORT = 57001 # Arbitrary non-privileged port socket.setdefaulttimeout(0.100) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: try: print 'Attempting to connect to server' s.connect((HOST, PORT)) break except socket.error, msg: time.sleep(5) continue print 'Connected - Time out is:',s.gettimeout() data = "The quick brown fox jumps over the lazy dog 0123456789\n" count = 0 while count < 500: try: s.send(data) except socket.error,msg: if 'timed out' in msg: print msg time.sleep(0.05) continue else: print 'socket error is:',msg break print "tx:",len(data) time.sleep(random.randint(200,800)/1000.0) s.close() ------------------------------------------------------------------------ From nepbabucxspamfree at yahoo.ca Tue Aug 21 22:40:51 2007 From: nepbabucxspamfree at yahoo.ca (Bikal KC) Date: Wed, 22 Aug 2007 12:10:51 +0930 Subject: Fast socket write In-Reply-To: <1187744469.240933.149610@r23g2000prd.googlegroups.com> References: <1187744469.240933.149610@r23g2000prd.googlegroups.com> Message-ID: <46cba22b$1_1@news.chariot.net.au> Greg Copeland wrote: > I'm having a brain cramp right now. I can't see to recall the name of Is your cramp gone now ? :P From steveo at syslang.net Sat Aug 25 22:54:09 2007 From: steveo at syslang.net (Steven W. Orr) Date: Sat, 25 Aug 2007 22:54:09 -0400 (EDT) Subject: Need a better understanding on how MRO works? In-Reply-To: <1i3evke.1rwf8pn10k1h30N%aleax@mac.com> References: <1i3evke.1rwf8pn10k1h30N%aleax@mac.com> Message-ID: On Saturday, Aug 25th 2007 at 17:19 -0700, quoth Alex Martelli: =>Steven W. Orr wrote: => ... =>> name = 'C1' =>> nclass = new.classobj(name,(D1,),globals()) =>> globals()[name] = nclass => =>Here, you're creating a VERY anomalous class C1 whose __dict__ is =>globals(), i.e. the dict of this module object; => =>> name = 'C2' =>> nclass = new.classobj(name,(D1,),globals()) =>> globals()[name] = nclass => =>and here you're creating another class with the SAME __dict__; => =>> globals()[name].m1 = m1replace => =>So of course this assignment affects the 'm1' entries in the dict of =>both classes, since they have the SAME dict object (a la Borg) -- that =>is, IF they're old-style classes (i.e. if D1 is old-style), since in =>that case a class's __dict__ is in fact a dict object, plain and simple. => =>However, if D1 is new-style, then C1.__dict__ and C2.__dict__ are in =>fact instances of -- each with a copy of the entries that =>were in globals() when you called new.classobj, but DISTINCT from each =>other and from globals(), so that further changes in one (or globals) =>don't affect globals (nor the other). => =>I guess this might be a decent interview question if somebody claims to =>be a "Python guru": if they can make head or tails out of this mess, boy =>the *ARE* a Python guru indeed (in fact I'd accord minor guruhood even =>to somebody who can get a glimmer of understanding of this with ten =>minutes at a Python interactive prompt or the like, as opposed to =>needing to understand it "on paper" without the ability to explore:-). => =>Among the several "don't"s to learn from this: don't use old-style =>classes, don't try to make two classes share the same dictionary, and =>don't ask about MRO in a question that has nothing to do with MRO =>(though I admit that was a decent attempt at misdirection, it wouldn't =>slow down even the minor-guru in any appreciable way:-). => => =>Alex =>-- =>http://mail.python.org/mailman/listinfo/python-list => Thanks Alex. I am humbled, though I was before I started. I really don't have a lot of understanding of what you're saying so I'll probably have to study this for about a year or so. * (I need to look up what dictproxy is.) I don't have any idea what the ramifications are of your use of the word DISTINCT. Are you somehow suggesting that new.classobj does a deep copy of the globals copy that's passed to it? * Also, I'd like to understand what the difference is between nclass = new.classobj(name,(D1,),globals()) vs. def classfactory(): class somename(object): def somestuff(): pass return somename G1 = classfactory() globals()[name] = G1 Does new.classobj do anything special? I appreciate your time. -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From shevitz at lanl.gov Wed Aug 22 11:23:25 2007 From: shevitz at lanl.gov (Danny) Date: Wed, 22 Aug 2007 15:23:25 +0000 (UTC) Subject: instance method questions Message-ID: howdy, I have created an instance method for an object using new.instancemethod. It works great. Now the questions are: 1) how do I dynamically inspect an object to determine if it has an instance method? (there is a class method with the same name) 2) how do I dynamically delete the instance method? thanks, Danny From ptmcg at austin.rr.com Mon Aug 27 08:40:09 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 27 Aug 2007 05:40:09 -0700 Subject: Parser Generator? In-Reply-To: References: <1188159150.755231.239390@o80g2000hse.googlegroups.com> <1188185192.735485.237740@57g2000hsv.googlegroups.com> Message-ID: <1188218409.525240.300590@o80g2000hse.googlegroups.com> On Aug 26, 10:48 pm, Steven Bethard wrote: > Paul McGuire wrote: > > On Aug 26, 8:05 pm, "Ryan Ginstrom" wrote: > >> The only caveat being that since Chinese and Japanese scripts don't > >> typically delimit "words" with spaces, I think you'd have to pass the text > >> through a tokenizer (like ChaSen for Japanese) before using PyParsing. > > > Did you think pyparsing is so mundane as to require spaces between > > tokens? Pyparsing has been doing this type of token-recognition since > > Day 1. Looking for tokens without delimiting spaces was one of the > > first applications for pyparsing. This issue is not unique to Chinese > > or Japanese text. Pyparsing will easily find the tokens in this > > string: > > > y=a*x**2+b*x+c > > > as > > > ['y','=','a','*','x','**','2','+','b','*','x','+','c'] > > The difference is that in the expression above (and in many other > tokenization problems) you can determine "word" boundaries by looking at > the class of character, e.g. alphanumeric vs. punctuation vs. whatever. > > In Japanese and Chinese tokenization, word boundaries are not marked by > different classes of characters. They only exist in the mind of the > reader who knows which sequences of characters could be words given the > context, and which sequences of characters couldn't. > > The closest analog would be to ask pyparsing to find the words in the > following sentence: > > Thepyparsingmoduleprovidesalibraryofclassesthatclientcodeusestoconstructthe?grammardirectlyinPythoncode. > > Most approaches that have been even marginally successful on these kinds > of tasks have used statistical machine learning approaches. > > STeVe- Hide quoted text - > > - Show quoted text - Steve - You mean like this? from pyparsing import * knownWords = ['of', 'grammar', 'construct', 'classes', 'a', 'client', 'pyparsing', 'directly', 'the', 'module', 'uses', 'that', 'in', 'python', 'library', 'provides', 'code', 'to'] knownWord = oneOf( knownWords, caseless=True ) sentence = OneOrMore( knownWord ) + "." mush = "ThepyparsingmoduleprovidesalibraryofclassesthatclientcodeusestoconstructthegrammardirectlyinPythoncode." print sentence.parseString( mush ) prints: ['the', 'pyparsing', 'module', 'provides', 'a', 'library', 'of', 'classes', 'that', 'client', 'code', 'uses', 'to', 'construct', 'the', 'grammar', 'directly', 'in', 'python', 'code', '.'] In fact, this is almost the exact scheme used by Zhpy for extracting Chinese versions of Python keywords, and mapping them back to English/ Latin words. Of course, this is not practical for natural language processing, as the vocabulary gets too large. And you can get ambiguous matches, such as a vocabulary containing the words ['in', 'to', 'into'] - the runtogether "into" will always be assumed to be "into", and never "in to". Fortunately (for pyparsing), your example was sufficiently friendly as to avoid ambiguities. But if you can select a suitable vocabulary, even a runon mush is parseable. -- Paul From steve at holdenweb.com Thu Aug 30 13:15:46 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Aug 2007 13:15:46 -0400 Subject: Python doesn't see the directories I create In-Reply-To: References: <46d6856b$0$17674$426a74cc@news.free.fr> Message-ID: Neil Cerutti wrote: > On 2007-08-30, Bruno Desthuilliers wrote: >> mr_gadget a ?crit : >>> When I create a subfolder, python is not seeing it. Can someone please >>> explain this behaviour ? I just started with python, read the tutorial over >>> the weekend and am writing my very first script. So I may not be seeing >>> something. Both os.path and glob.glob seem not to see a folder I created. >>> Other sibling folders seem to work fine. On a whim I tried paths with \\ >>> double slashes and that worked. But why should single slashes work for some >>> folders and not for others ?? >> s/slash/antislash/g >> >> It's a very well known gotcha due to MS's choice to use the >> antislash as path separator. In most languages - Python >> included - the antislash is used for escape sequences >> (non-printable characters). > > Keeping in mind which came first, isn't it at least as accurate > to attribute this problem to Python's choice of escape character? > There were probably advantages to adopting the same escape > character as other well-known languages/codes, but the choice has > caused some trouble over the years. > > To me, Python's collection of special-purpose string literal > notations is one of its little warts. > > Of course, I'm not smart enough to have delivered the ONE TRUE > string literal notation either, but I do have a computer and an > internet connection, so there you are. > Well, it's a wart that's shared with many other languages - including, interestingly enough, Microsoft's very own C#, from whose documentation the following examples are taken: string a = "hello, world"; // hello, world string b = @"hello, world"; // hello, world string c = "hello \t world"; // hello world string d = @"hello \t world"; // hello \t world string e = "Joe said \"Hello\" to me"; // Joe said "Hello" to me string f = @"Joe said ""Hello"" to me"; // Joe said "Hello" to me string g = "\\\\server\\share\\file.txt"; // \\server\share\file.txt string h = @"\\server\share\file.txt"; // \\server\share\file.txt string i = "one\r\ntwo\r\nthree"; The fact is that some strings are always going to cause trouble. Unfortunately programming itself is a task that requires a little more knowledge to be applied to the task. Just learn the rules and move on. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From steve at REMOVE.THIS.cybersource.com.au Fri Aug 3 21:46:52 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 04 Aug 2007 11:46:52 +1000 Subject: How to pass a reference to the current module References: Message-ID: On Fri, 03 Aug 2007 17:22:40 -0700, James Stroud wrote: > Basically, what I am trying to acomplish is to be able to do this in any > arbitrary module or __main__: > > > funcname = determined_externally() > ModuleUser.do_something_with(AModule, funcname) > > > Ideally, it would be nice to leave out AModule if the functions were > designed in the same namespace in which do_something_with is called. I second Carsten Haese's suggestion that instead of passing function names, you pass function objects, in which case you don't need the module. But perhaps you need some way of finding the function, given its name. def get_function_from_name(name, module=None): if module is None: # use the current namespace namespace = locals() # or globals() if you prefer else: namespace = module.__dict__ return namespace[name] -- Steven. From neokosmos at gmail.com Sun Aug 5 13:01:46 2007 From: neokosmos at gmail.com (Paul Miller) Date: Sun, 05 Aug 2007 10:01:46 -0700 Subject: Semantics of thread.error Message-ID: <1186333306.599950.139160@e16g2000pri.googlegroups.com> In the language documentation, all that is said about thread.error is that it's raised "on thread-specific errors." Is there anywhere a list of conditions which will cause thread.error to be raised? (I mean, other than the thread library C source, of course.) Thanks! Paul From jeremy+complangpython at jeremysanders.net Sat Aug 25 05:28:40 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Sat, 25 Aug 2007 10:28:40 +0100 Subject: Co-developers wanted: document markup language References: <87odgyyx9u.fsf@wilson.homeunix.com> <87tzqotwkk.fsf@wilson.homeunix.com> Message-ID: Torsten Bronger wrote: > I don't know exactly what you mean but the answer is probably no. > For example, I want the author to state the title, keywords, etc of > his document, however, he should not state that he wants the title > printed centred and 4cm from the top of the page. > > The latter is defined in the "theme" which will be given as a set of > ordinary LaTeX commands (for the LaTeX backend). Isn't the problem that making such a theme will be very hard? One of the annoying things about LaTeX is lack of control over positioning (e.g. floats, page breaks...). The one thing most LaTeX users moan about is trying to get their document to fit into an n page limit (e.g. for a proposal). Maybe the theme could have some options to control spacing, however, like some sort of CSS. I think the one thing that would improve LaTeX is orthogonality in its commands (e.g. why no 8pt option for the document, why the crazy \small, \LARGE, etc commands?), and fixing the font system to be based around modern fonts. Finally making bibtex part of the core and making it easy to use would be great. -- Jeremy Sanders http://www.jeremysanders.net/ From tundra at tundraware.com Fri Aug 31 22:20:42 2007 From: tundra at tundraware.com (Tim Daneliuk) Date: Fri, 31 Aug 2007 21:20:42 -0500 Subject: So what exactly is a complex number? In-Reply-To: <46d89ba9$0$30380$9b4e6d93@newsspool4.arcor-online.net> References: <451mq4-les.ln1@ozzie.tundraware.com> <46d89ba9$0$30380$9b4e6d93@newsspool4.arcor-online.net> Message-ID: Wildemar Wildenburger wrote: > Tim Daneliuk wrote: >> A number by itself is called a "scalar". For example, when I say, >> "I have 23 apples", the "23" is a scalar that just represents an >> amount in this case. >> >> One of the most common uses for Complex Numbers is in what are >> called "vectors". In a vector, you have both an amount and >> a *direction*. For example, I can say, "I threw 23 apples in the air >> at a 45 degree angle". Complex Numbers let us encode both >> the magnitude (23) and the direction (45 degrees) as a "number". >> > 1. Thats the most creative use for complex numbers I've ever seen. Or > put differently: That's not what you would normally use complex numbers > for. Oh, one other thing I neglected to mention. My use of "vector" here is certainly incorrect in the mathematician's sense. But I first ran into complex arithmetic when learning to fly an airplane. The airplane in flight has a speed (magnitude) and a bearing (direction). The winds aloft also have speed and bearing. These are called the aircraft "vector" and the wind "vector" respectively. They must be added to compute the actual (effective) speed/direction the aircraft is flying. In the Olden Days (tm), we did this graphically on a plastic flight computer and a grease pencil. With the advent of calculators like the HP 45 that could do polar <-> rectangular conversion, this sort of problem became a snap to do. It is from this experience that I used the (non-mathematical) sense of the word "vector" ... ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From evan at yelp.com Tue Aug 21 20:09:15 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 21 Aug 2007 17:09:15 -0700 Subject: Extracting the traceback In-Reply-To: <1187740411.848743.151960@x35g2000prf.googlegroups.com> References: <1187740411.848743.151960@x35g2000prf.googlegroups.com> Message-ID: On 8/21/07, billiejoex wrote: > Hi there, > I'm facing a case where I need to get the traceback outptut when > occurring an exception. > I solved such problem by using traceback module in conjunction with > StringIO: > > import StringIO, traceback > try: > raise Exception > except: > f = StringIO.StringIO() > traceback.print_exc(file=f) > print f.getvalue() > > ... but this seems a little poor to me since I first put output into > the StringIO.StringIO(), then I get it back by using getvalue() on > it. > Is there a way to avoid the use of StringIO and get such output > without using such (useless) additional step? If you just want to print the output (as in your example), you can use file=sys.stdout or file=sys.stderr in the call to print_exc. If you want to store the traceback into a string for some other purpose (e.g. logging, email notifications) I believe that you must use a StringIO object. -- Evan Klitzke From ptmcg at austin.rr.com Tue Aug 7 11:33:55 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 07 Aug 2007 08:33:55 -0700 Subject: parsing a dbIII file In-Reply-To: References: <1186469710.277542.246430@w3g2000hsg.googlegroups.com> Message-ID: <1186500835.221263.76210@d55g2000hsg.googlegroups.com> On Aug 7, 2:21 am, Steve Holden wrote: > korove... at gmail.com wrote: > > Hello everybody, I'm new to python (...I work with cobol...) > > > I have to parse a file (that is a dbIII file) whose stucture look like > > this: > > |string|, |string|, |string that may contain commas inside|, 1, 2, 3, | > > other string| > As Steve mentioned pyparsing, here is a pyparsing version for cracking your data: from pyparsing import * data = "|string|, |string|, |string that may contain commas inside|, 1, 2, 3, |other string|" integer = Word(nums) # change unquoteResults to True to omit '|' chars from results string = QuotedString("|", unquoteResults=False) itemList = delimitedList( integer | string ) # parse the data and print out the results as a simple list print itemList.parseString(data).asList() # add a parse action to convert integer strings to actual integers integer.setParseAction(lambda t:int(t[0])) # reparse the data and now get converted integers in results print itemList.parseString(data).asList() Prints: ['|string|', '|string|', '|string that may contain commas inside|', '1', '2', '3', '|other string|'] ['|string|', '|string|', '|string that may contain commas inside|', 1, 2, 3, '|other string|'] -- Paul From see at signature.invalid Sun Aug 5 09:22:02 2007 From: see at signature.invalid (Douglas Wells) Date: Sun, 5 Aug 2007 09:22:02 -0400 (EDT) Subject: Comparing RFC1123 based Dates References: <1186281836.970400.103490@i13g2000prf.googlegroups.com> <1186284911.988459.324690@e16g2000pri.googlegroups.com> Message-ID: In article <1186284911.988459.324690 at e16g2000pri.googlegroups.com>, Phoe6 writes: > Phoe6 wrote: > > I would like to parse RFC 1123 date format and compare two dates. I > > find that > > datetime module does not specifically confirms to any RFC. Any > > suggestions as how I can handle the RFC 1123 date format using > > standard libraries before I go to re based parsing? > > Well, > >>> import time > >>> timeobj = time.strptime("Thu, 01 Dec 1994 16:00:00 GMT","%a, %d %b %Y %H:%M:%S %Z") > > was easy. Well, it might have been easy, but it's got several gotchas (in both Python and C), including: - The zone field (%Z) only corresponds for the GMT and UT timezones, which are obsolete (see RFC 2822). There is no support for the recommended +/-time-offset form. - The day-of-week (%a) and month (%b) fields in strptime and strftime are subject to the process's locale, whereas the RFC time forms are not. Those are hardwired to names that happen to correspond to the C, POSIX, and probably most of the en_* locales, but not to others that would be used by billions of people. Thus anyone using your program who doesn't happen to reside in one of the English-speaking countries (or does and is using a native locale) is likely to encounter problems when using your program. - The day-of-week field is optional. - Comments are allowed (but deprecated) in the whitespace fields of the time format. (On the other hand, I've never seen this is normal e-mail.) I find the use of strptime and strftime difficult enough to manage with Internet date/times that I restrict my use of them to programs that are limited to processing date/times. Even then, I then explicitly set the locale (LC_TIME) to the "C" locale. Otherwise, I use ad hoc code that explicitly recognizes the RFC-defined forms. -- . Douglas Wells . Connection Technologies . . Internet: -sp9804- -at - contek.com- . From gherron at islandtraining.com Thu Aug 23 13:37:29 2007 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 23 Aug 2007 10:37:29 -0700 Subject: My 'time' module is broken, unsure of cause In-Reply-To: <200708231122.55588.bulliver@badcomputer.org> References: <200708231122.55588.bulliver@badcomputer.org> Message-ID: <46CDC5D9.8050800@islandtraining.com> darren kirby wrote: > Hi all, > > I have a strange error here and I am unsure how to further investigate it: > > Python 2.4.4 (#1, Aug 23 2007, 10:51:29) > [GCC 4.1.2 (Gentoo 4.1.2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>> import time >>>> > 40:42:0 > >>>> now = time.time() >>>> > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'time' > You probably has a file named time.py in your current directory, and it is *that* file you are importing. (Run Python with a "-v" option to see what file "import time" is actually importing.) > Notice the '40:42:0' that always gets output. I searched Gentoo's bugzilla but > can not see anything relevant. I rebuilt python but the behavior recurs. I am > unsure if the issue is with Python, Gentoo, or perhaps with the underlying > lib (presumably glibc) that Python uses for the time module. This is working > fine on another machine (also 2.4.4, GCC 3.4.6, Gentoo Hardened). > > Anyone seen this? Any hints for me to track this issue down? Any further > information I could provide? > > Thanks for consideration, > -d > From http Mon Aug 27 00:48:00 2007 From: http (Paul Rubin) Date: 26 Aug 2007 21:48:00 -0700 Subject: ANN: SCF released GPL References: <2qnAi.21495$eY.19028@newssvr13.news.prodigy.net> Message-ID: <7x3ay5d1mn.fsf@ruckus.brouhaha.com> hg writes: > I am looking for a free subversion server resource to put the code > ... if you know of any. Does it have to be SVN? I think Savannah and Sourceforge both still use CVS. I'm not sure what Launchpad uses. I guess if necessary I could set up a subversion repo for you on a server that I use. I've been wanting to put together some GNU security tools under the name Fort GNOX, so maybe this can be a start. From half.italian at gmail.com Thu Aug 9 14:25:09 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Thu, 09 Aug 2007 18:25:09 -0000 Subject: Threaded Design Question Message-ID: <1186683909.797328.68770@i13g2000prf.googlegroups.com> Hi all! I'm implementing one of my first multithreaded apps, and have gotten to a point where I think I'm going off track from a standard idiom. Wondering if anyone can point me in the right direction. The script will run as a daemon and watch a given directory for new files. Once it determines that a file has finished moving into the watch folder, it will kick off a process on one of the files. Several of these could be running at any given time up to a max number of threads. Here's how I have it designed so far. The main thread starts a Watch(threading.Thread) class that loops and searches a directory for files. It has been passed a Queue.Queue() object (watch_queue), and as it finds new files in the watch folder, it adds the file name to the queue. The main thread then grabs an item off the watch_queue, and kicks off processing on that file using another class Worker(threading.thread). My problem is with communicating between the threads as to which files are currently processing, or are already present in the watch_queue so that the Watch thread does not continuously add unneeded files to the watch_queue to be processed. For example...Watch() finds a file to be processed and adds it to the queue. The main thread sees the file on the queue and pops it off and begins processing. Now the file has been removed from the watch_queue, and Watch() thread has no way of knowing that the other Worker() thread is processing it, and shouldn't pick it up again. So it will see the file as new and add it to the queue again. PS.. The file is deleted from the watch folder after it has finished processing, so that's how i'll know which files to process in the long term. I made definite progress by creating two queues...watch_queue and processing_queue, and then used lists within the classes to store the state of which files are processing/watched. I think I could pull it off, but it has got very confusing quickly, trying to keep each thread's list and the queue always in sync with one another. The easiset solution I can see is if my threads could read an item from the queue without removing it from the queue and only remove it when I tell it to. Then the Watch() thread could then just follow what items are on the watch_queue to know what files to add, and then the Worker() thread could intentionally remove the item from the watch_queue once it has finished processing it. Now that I'm writing this out, I see a solution by over-riding or wrapping Queue.Queue().get() to give me the behavior I mention above. I've noticed .join() and .task_done(), but I'm not sure of how to use them properly. Any suggestions would be greatly appreciated. ~Sean From erlangga.kusuma at gmail.com Mon Aug 6 11:21:54 2007 From: erlangga.kusuma at gmail.com (angga_cute) Date: Mon, 06 Aug 2007 08:21:54 -0700 Subject: computer, printer, and another Message-ID: <1186413714.616729.198620@x35g2000prf.googlegroups.com> Hi guys.... I have some information for you... I would like you to invite to visiting my web, may be you need some information about newest information about computer, laptop, and than printer. I have little bit information on my web http://www.komputer-djogja.blogspot.com/ I hope my web can give you alot of information... Thanks for you attention... From kyosohma at gmail.com Wed Aug 29 10:03:19 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 29 Aug 2007 07:03:19 -0700 Subject: What's the difference ? In-Reply-To: <1188394767.333396.129020@r29g2000hsg.googlegroups.com> References: <1188394767.333396.129020@r29g2000hsg.googlegroups.com> Message-ID: <1188396199.136398.321900@r34g2000hsd.googlegroups.com> On Aug 29, 8:39 am, Alex wrote: > Hye, > > I was just wondering what is the difference between > > >> if my_key in mydict: > >> ... > > and > > >> if mydict.has_keys(my_key): > >> ... > > I've search a bit in the python documentation, and the only things I > found was that they are "equivalent". > > But in this (quiet old) sample ( "http://aspn.activestate.com/ASPN/ > Cookbook/Python/Recipe/59875" ), there is difference between the two > notation. > > Thanks in advance Weird. Hetland's book, "Beginning Python" states that it's a matter of taste. Martelli's "Python Cookbook 2nd Ed." says to use the get() method instead as you never know if a key is in the dict. However, I can't seem to find any reference to has_key in his book. According to Chun in "Core Python Programming", has_key will be obsoleted in future versions of Python, so he recommends using "in" or "not in". There's your non-answer. Hope that helps. Mike From anno4000 at radom.zrz.tu-berlin.de Sat Aug 25 10:29:25 2007 From: anno4000 at radom.zrz.tu-berlin.de (anno4000 at radom.zrz.tu-berlin.de) Date: 25 Aug 2007 14:29:25 GMT Subject: Regular expression use References: Message-ID: <5jasm5F3tgqdqU1@mid.dfncis.de> John W. Krahn wrote in comp.lang.perl.misc: > Nick Maclaren wrote: > > In article , > > Mirco Wahab writes: > > |> > > |> Using complex regular expressions is like tank destruction > > |> with contact charges glued on them. Only a few people > > |> will even survive the first "usage", but survivors will > > |> then eventually be able to destroy almost every tank with > > |> tremendous speed and precision. > > > > I must remember that! It is nicely put. > > I couldn't understand it. (An old Centurion trooper.) Me neither. The word "nicely" isn't the first thing it brings to mind. Anno From zyzhu2000 at gmail.com Thu Aug 16 23:15:10 2007 From: zyzhu2000 at gmail.com (beginner) Date: Fri, 17 Aug 2007 03:15:10 -0000 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> <1187311999.880853.135780@j4g2000prf.googlegroups.com> Message-ID: <1187320510.165621.224150@l22g2000prc.googlegroups.com> On Aug 16, 9:32 pm, Carsten Haese wrote: > On Fri, 2007-08-17 at 00:53 +0000, beginner wrote: > > $b is supposed to be a hash-table of hash-table. If a key exists in > > $b, it points to another hash table. The $a=$b->{"A"} ||={} pattern is > > useful when you want to add records to the double hash table. > > > For example, if you have a series of records in the format of (K1, K2, > > V), and you want to add them to the double hash-table, you can do > > $a=$b->{K1} || ={} > > $a->{K2}=V > > What is the best solution in Perl need not be the best solution in > Python. In Python you should just use a tuple as your dict key, i.e. > a[k1,k2] = v, unless you have some other constraints you're not telling > us. > > HTH, > > -- > Carsten Haesehttp://informixdb.sourceforge.net I use tuples this way all the time. It is indeed very neat. But it is not a replacement for double hash-table. If I want to retrieve information just by K1, it is not efficient to index on (K1, K2). From yichangjiang at gmail.com Mon Aug 13 02:48:42 2007 From: yichangjiang at gmail.com (ychjiang) Date: Sun, 12 Aug 2007 23:48:42 -0700 Subject: which IDE is highly recommended in Windows OS In-Reply-To: <1186970945.403792.51790@d55g2000hsg.googlegroups.com> References: <1186970945.403792.51790@d55g2000hsg.googlegroups.com> Message-ID: <1186987722.945794.142810@q3g2000prf.googlegroups.com> On 8 13 , 10 09 , Ge Chunyuan wrote: > hi Group: > > I am a new comer for Python, I wonder which IDE is recommended in > Windows OS. > Can anyone give some suggestion. > > Thanks indeed > Ge Chunyuan java eclipse pydev eclipse From nospam at invalid.com Sun Aug 26 19:26:29 2007 From: nospam at invalid.com (Jack) Date: Sun, 26 Aug 2007 16:26:29 -0700 Subject: Parser Generator? References: <1187834836.115735.111160@e9g2000prf.googlegroups.com> <1188159150.755231.239390@o80g2000hse.googlegroups.com> Message-ID: Thanks Json. There seem to be a few options that I can pursue. Having a hard time chooing one now :) "Jason Evans" wrote in message news:1188159150.755231.239390 at o80g2000hse.googlegroups.com... > On Aug 24, 1:21 pm, "Jack" wrote: >> "Jason Evans" wrote in message >> > http://www.canonware.com/Parsing/ >> >> Thanks Jason. Does Parsing.py support Unicode characters (especially >> CJK)? >> I'll take a look. > > Parsers typically deal with tokens rather than individual characters, > so the scanner that creates the tokens is the main thing that Unicode > matters to. I have written Unicode-aware scanners for use with > Parsing-based parsers, with no problems. This is pretty easy to do, > since Python has built-in support for Unicode strings. > > Jason > From aboudouvas at panafonet.gr Mon Aug 13 05:48:59 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Mon, 13 Aug 2007 02:48:59 -0700 Subject: Eclipse/PyDev question Message-ID: <1186998539.030727.279330@g4g2000hsf.googlegroups.com> Hi, i am using Eclipse (Platform Runtime binary) with PyDev and i was wondering if someone can help me with this: 1. I set breakpoints to a .py file and i have told Eclipse to open the Debug perspective when it sees that some .py file(s) of my project indeed contains breakpoints. So, i press F9, Eclipse starts, Debug perspective opens and i can use the debugger just fine. But when the app terminates, how can i tell Eclipse to switch automatically to the PyDev perspective and not remain in the Debug one ? 2. Let's say we have a project that consists of some .py files. I want to press F9 when the editor displays anyone of these files but make Eclipse to run the whole project (that has another .py as "default") and not the script that i am currently working on, is that possible ?? Thanks a lot for any help From ptmcg at austin.rr.com Thu Aug 16 22:09:39 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 16 Aug 2007 19:09:39 -0700 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: <1187305420.464078.156440@x35g2000prf.googlegroups.com> References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> <1187305420.464078.156440@x35g2000prf.googlegroups.com> Message-ID: <1187316579.536255.175540@w3g2000hsg.googlegroups.com> On Aug 16, 6:03 pm, Carl Banks wrote: > On Aug 16, 6:35 pm, beginner wrote: > > > Hi All. > > > I'd like to do the following in more succint code: > > > if k in b: > > a=b[k] > > else: > > a={} > > b[k]=a > > > a['A']=1 > > > In perl it is just one line: $a=$b->{"A"} ||={}. > > > Thanks, > > Geoffrey > > Define b as a default dict: > > b = defaultdict(dict) > b[k]['A'] = l > > Carl Banks- Hide quoted text - > > - Show quoted text - I think the most direct translation of the OP's example to Python would be: # setup b as special flavor of dict, that creates a # new dict for not-yet-created keys b = defaultdict(dict) # actual python impl of $a=$b->{k}||={} a = b[k] # assign 1 to retrieved/created dict a['A'] = 1 -- Paul From bbxx789_05ss at yahoo.com Mon Aug 6 14:31:15 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 06 Aug 2007 11:31:15 -0700 Subject: udp, datagram sockets In-Reply-To: References: <1186416225.769753.307110@o61g2000hsh.googlegroups.com> Message-ID: <1186425075.604433.122380@g4g2000hsf.googlegroups.com> On Aug 6, 10:59 am, Thomas Jollans wrote: > > You don't make any attempt to break out of the outer loop. (break breaks the > innermost loop) > By design. My server stands ready to process any and all messages forever. The problem I'm having is that my server processes the same message forever. From horpner at yahoo.com Mon Aug 6 06:49:36 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 06 Aug 2007 10:49:36 GMT Subject: Misleading wikipedia article on Python 3? References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <7xzm15q8fy.fsf@ruckus.brouhaha.com> Message-ID: <41Dti.37401$G23.10727@newsreading01.news.tds.net> On 2007-08-06, Neil Cerutti wrote: > On 2007-08-06, Paul Rubin wrote: >> Carsten Haese writes: >>> For instance, if you never use print statements in your code, >>> you won't notice that print is becoming a function. If you >>> do, you'll have to make appropriate accommodations. >> >> Why on earth did they make this change? It just seems >> gratuitous. Is the assert statement also being changed? Are >> they going to update all the docs that say that the yield >> statement works like the print statement? > > From the footnotes of PEP 3100: > > http://mail.python.org/pipermail/python-dev/2005-September/056154.html > http://www.python.org/dev/peps/pep-3105 Incidentally, from the second link I find it shocking that the keyword parameter "file" shadows a builtin. It seems to endorse a bad practice. -- Neil Cerutti From steve at holdenweb.com Sun Aug 12 22:06:00 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 12 Aug 2007 22:06:00 -0400 Subject: Ligmail bug? In-Reply-To: References: <20070812005057.GA15805@ob41.org> <20070812182439.GA2427@ob41.org> <46BEE9B8.8080904@holdenweb.com> Message-ID: <46BFBC88.2010400@holdenweb.com> Ed Leafe wrote: > On Aug 12, 2007, at 7:06 AM, Steve Holden wrote: > >> [Please reply via the list when a response is made via the list. >> You may >> now have detached the follow-ups from your original question, but at >> least if you use the list there's a chance someone else will help >> you if >> I give up or don't have time. Note I have sent this response to the >> list; you are Cc'd to make sure you pick it up even though it may not >> appear in the same thread.] > > I've seen others comment on this, so I'll throw in my 2 cents. > > The default behavior for this list should be to reply to the list, > as you have pointed out. Yet for some unfathomable reason, the > keepers of the list have set it up to default to reply to the > original sender. This is nothing short of stupid, and I cast my vote > (if I even have one) for changing this default to a more intelligent > one, if for no other reason than to not have to constantly read > comments like this chiding someone for acting in a predictable fashion. > Since I subscribe to the newsgroup rather than to the mailing list I don't see that behavior. It's by far the most convenient way to interact with c.l.py, and gmane.org makes it easy to do so with Firefox or Outlook Express. I've never really understood why Outlook doesn't include an NNTP client. I presume Apple Mail (which appears in your headers) doesn't act as a newsreader either? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From arkanes at gmail.com Wed Aug 29 14:28:54 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 29 Aug 2007 13:28:54 -0500 Subject: Accessing docstrings at runtime? In-Reply-To: <011b01c7ea69$95512fe0$e6003dcc@worf2> References: <011b01c7ea69$95512fe0$e6003dcc@worf2> Message-ID: <4866bea60708291128o29803077r5fe06249ab6cc29c@mail.gmail.com> On 8/29/07, Kenneth Love wrote: > How do I print the docstring for a class property? > > When I run the code below, I get the docstring for the string module > and not the one I set for the property. > > --------------------------------------------- > # NOTE: Found in Python docs defining built-in functions (such as > # property()). FIXED: Bug in getx, setx, and delx where "__x" > # was misreferenced as "_x". > class C(object): > def __init__(self): > self.__x = None > def getx(self): > return self.__x > def setx(self, value): > self.__x = value > def delx(self): > del self.__x > x = property(getx, setx, delx, "I'm the 'x' property.") > > if __name__ == "__main__" > y = C() > y.x = 'test' > print y.x > print y.x.__doc__ > --------------------------------------------- > > I get the following output: > > --------------------------------------------- > test > str(object) -> string > > Return a nice string representation of the object. > If the argument is a string, the return value is the same object. > --------------------------------------------- > > What am I doing wrong? > You're looking at an instance, not at the class. y.x is going through the descriptor lookup and is returning the string, so the __doc__ is the the __doc__ of the string object, as you see. If you want to look at the property directly, look it up in the class object: C.x.__doc__ From theshadowx at gmail.com Thu Aug 23 14:34:01 2007 From: theshadowx at gmail.com (TheShadow) Date: Thu, 23 Aug 2007 18:34:01 -0000 Subject: Question about embedding python in C++ In-Reply-To: References: <1187891085.147246.19380@i38g2000prf.googlegroups.com> Message-ID: <1187894041.718724.313060@m37g2000prh.googlegroups.com> On Aug 23, 11:57 am, Farshid Lashkari wrote: > TheShadow wrote: > > When extending python in c/c++ after you register a module is there a > > way in c/c++ to check if they were correctly registered? > > > Cause I'm having the problem where when I execute the the python > > script it finds the module but none of the functions. > > Are you calling Py_InitModule(...) in your initmodule function? If so, > Py_InitModule(...) returns a reference to the module object. You can use > this object to double check that your function names exist in the > modules dictionary. Most likely, there is an error in your code. If you > post it, it would be easier to tell what the problem is. > > -Farshid Hrmm I forgot about the module init function... I was just calling Py_initModule() From steve at holdenweb.com Fri Aug 3 09:20:09 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 03 Aug 2007 09:20:09 -0400 Subject: File Handling & TRY/EXCEPT In-Reply-To: <33119.3366124809$1186129744@news.gmane.org> References: <33119.3366124809$1186129744@news.gmane.org> Message-ID: Robert Rawlins - Think Blue wrote: > Hello Guys, > > > > I?m looking for some advice on how best to handle file read/write errors > with try/except as i?m a little vague on this, I have a small memory > leak in my app and I?m starting to think its generated by my log file > write. For an example of the function look below. > > > > def addAppLog(self, event): > try: > logfile = open('/pblue/new/Logs/Application.csv','a') > now = datetime.datetime.now() > logstring = '%s,%s \n' % (event, str(now)) > logfile.write(logstring) > except: > self.addAppLog(event) > It seems somewhat perverse, when the logging code raises an exception, to recursively log - presumably the same exception will be raised again? > else: > > logfile.close() > Remember that in 2.5 you can use try ... except ... finally > > Now I?m looking for some help to sort this out as I?m sure it?s pretty > untidy, I want to make it as air tight as possible. The basic concept > was that if it tries writing to the log file and it fails, then it needs > to reattempt it, right? > Wrong. The one thing you can't log is a logging attempt error! > > > What?s the best way to handle this to ensure that there are not any > memory leaks caused when the file is open() but not followed by a > close(). I?m running 2.4 and I know some of these newer versions don?t > need you to explicitly close() the file objects, but I would certainly > feel a lot better. > > > > Any advice? > This is just a quick on-the-fly look at what you did, I am sure you will receive other, probably more helpful, comments. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From kyosohma at gmail.com Fri Aug 3 11:46:45 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 03 Aug 2007 08:46:45 -0700 Subject: How to log python Shell results In-Reply-To: <1186154042.876531.47100@k79g2000hse.googlegroups.com> References: <1186154042.876531.47100@k79g2000hse.googlegroups.com> Message-ID: <1186156005.938842.157480@m37g2000prh.googlegroups.com> On Aug 3, 10:14 am, Colly wrote: > How do I output the IDLE 1.2.1 Python Shell results to a log file. Redirect stdout to the log file. out = sys.stdout # save stdout for restoration later f = open(r'c:\test\test.log', 'w') sys.stdout = f # now stdout is redirected # do some stuff that prints output f.close() # when done, close the file sys.stdout = out # restore stdout Or you could just copy and paste it yourself. Mike From richardjones at optushome.com.au Mon Aug 13 06:18:05 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Mon, 13 Aug 2007 20:18:05 +1000 Subject: Adventure-Engines in Python References: Message-ID: <46c02fdd$0$14405$afc38c87@news.optusnet.com.au> Wildemar Wildenburger wrote: > Are there any? An adventure game was written for one of the PyWeek challenges: http://www.pyweek.org/e/aerunthar/ You might be able to use that as a starting point. Richard From paul at boddie.org.uk Wed Aug 1 18:51:27 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 01 Aug 2007 15:51:27 -0700 Subject: Wing IDE for Python v. 3.0 beta1 released In-Reply-To: References: <46AF8ED7.2070206@wingware.com> <20070801212840.GA25065@spookie1.spookiegate> <496954360708011453h2a68dee4x48dcb15bb25ea717@mail.gmail.com> Message-ID: <1186008687.142015.55060@q75g2000hsh.googlegroups.com> Steve Holden wrote: > > I can't think of any other products I use where you can contact the > support team from right inside the software. And get answers without > paying per-incident support fees! Proprietary products, right? A lot of KDE applications have a "Report Bug..." item in the "Help" menu, for example. Perhaps you're thinking of the same kind of thing. Paul From gslindstrom at gmail.com Fri Aug 31 12:06:39 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Fri, 31 Aug 2007 11:06:39 -0500 Subject: Complex Numbers Message-ID: > ---------- Forwarded message ---------- > From: "Lamonte Harris" > To: python-list at python.org > Date: Thu, 30 Aug 2007 20:11:14 -0500 > Subject: So what exactly is a complex number? > Like in math where you put letters that represent numbers for place > holders to try to find the answer type complex numbers? Not quite. Consider the square root of -1. It's not real because you can't square a real number and get a negative, so we define "i" (or, perhaps "j") to be the square root of -1. An imaginary number is of the form Ai, where A is "real". So 2i, -3.14i are imaginary. Complex Numbers are of the form A + Bi Where A and B are real (so they have a "real" component and am "imaginary" component). So yo might see 2 + 3i, etc. You'll see them a lot in engineering. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tenax.raccoon at gmail.com Mon Aug 20 15:42:44 2007 From: tenax.raccoon at gmail.com (Jason) Date: Mon, 20 Aug 2007 19:42:44 -0000 Subject: I Need help from all the group participants In-Reply-To: References: <1187636668.436474.289220@o80g2000hse.googlegroups.com> Message-ID: <1187638964.815505.85390@57g2000hsv.googlegroups.com> On Aug 20, 1:14 pm, Boris Ozegovic wrote: > dogatemycompu... at gmail.com wrote: > > I would be happy to help but I don't have a clear understand of what > > the poster needs. > > Suppose you want to find out what is someone's pulse/heart rate, you can > ask question in many ways, syntaxically, but with same semantic. One way > to find out someone's pulse is to ask: "What is John's pulse", other is > "Please, tell me, what is Jonh's pulse", or "Send me John's pulse > immediatelly!", etc. So, if you can write some other question to find out > someone's pulse, please do, but, it would be great if your question would > have different pattern, e.g. "Please, tell me John's pulse immediatelly" > and "Tell me John's pulse right now" have the same pattern, because they > are syntaxically very alike. > > -- > Ne dajte da nas la?ljivac Bandi? truje:http://cnn.blog.hr/arhiva-2007-06.html#1622776372 I wonder what John's pulse is? Display John's pulse. I need to know John's pulse. How many beats per minute is John's heart going? What's John's pulse rate? How fast is John's heart rate? How fast is John's blood pumping? What is the rate of John's heart? What is the rate of John's pulse? How fast is John's heart beating? What is the frequency of John's heart pulses? What is the frequency of John's cardiac cycle? How fast is John's cardiac cycle? What is the rate of John's pulse? I want the result of John's auscultation. Give me John's heart beats, or give John death! Okay, probably not the last one. If you're trying to do some natural language processing, you should take a look at the Natural Language Tool Kit (NLTK) [1]. The NLTK is written in Python, and also has a book to help you out (available free online or as a physical book for price). In any case, English is a terribly difficult language to parse, and can have many ambiguities that can only be resolved through knowledge of the subjects and verbs involved. Good luck on your project. Just remember: Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo [2]. [1] The NLTK website is at "http://nltk.sourceforge.net/index.php/ Main_Page" [2] That's actually valid English. See "http://en.wikipedia.org/wiki/ Buffalo_buffalo_Buffalo_buffalo_buffalo_buffalo_Buffalo_buffalo" --Jason From raims at dot.com Sat Aug 18 21:27:42 2007 From: raims at dot.com (Lawrence Oluyede) Date: Sun, 19 Aug 2007 03:27:42 +0200 Subject: How to call module functions inside class instance functions? References: <1187484041.838615.259980@e9g2000prf.googlegroups.com> Message-ID: <1i32p8v.nezbxp1h95n1uN%raims@dot.com> beginner wrote: > I have encountered a small problems. How to call module functions > inside class instance functions? For example, calling func1 in func2 > resulted in a compiling error. > > "my module here" > > def func1(): > print "hello" > > class MyClass: > def func2(): > #how can I call func1 here. > func1() #results in an error rhymes at groove ~ % cat t.py def func1(): print "hello" class MyClass: def func2(): func1() rhymes at groove ~ % python -c "import t" rhymes at groove ~ % As you can see there no compiling error, because the syntax is correct, you'll eventually get a runtime error like this: >>> import t >>> c = t.MyClass() >>> c.func2() Traceback (most recent call last): File "", line 1, in TypeError: func2() takes no arguments (1 given) That's because you left out the "self" argument in the definition of "func2()". This version is correct: -- def func1(): print "hello" class MyClass(object): def func2(self): func1() c = MyClass() c.func2() -- rhymes at groove ~ % python tcorrect.py hello HTH -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From mailpitches at email.com Fri Aug 31 22:42:55 2007 From: mailpitches at email.com (mp) Date: Fri, 31 Aug 2007 19:42:55 -0700 Subject: Non-Blocking IO Message-ID: <1188614575.647228.248640@k79g2000hse.googlegroups.com> I'm trying to use popen2 to call a program and then write and read data from the program using a Python script. Unfortunately, my calls to read block (I need non-blocking IO), and all the workarounds I've seen online don't work. Here is my most promising solution and how it breaks: Source of solution: http://mail.python.org/pipermail/python-dev/2005-March/052263.html def setblocking(fd,flag): " set/clear blocking mode" # get the file's current flag settings fl = fcntl.fcntl(fd, fcntl.F_GETFL) if flag: # clear non-blocking mode from flags fl = fl & ~os.O_NONBLOCK else: # set non-blocking mode from flags fl = fl | os.O_NONBLOCK # update the file's flags fcntl.fcntl(fd, fcntl.F_SETFL, fl) def try3(): fin,fout= os.popen2("echo.py") setblocking(fout.fileno(),False) os.write(fin.fileno(),'blah') fin.flush() print os.read(fout.fileno(),256) Calling try3() yields the error: File "./test.py", line 54, in try3 print os.read(fout.fileno(),256) OSError: [Errno 35] Resource temporarily unavailable If anyone could help me accomplish this I'd be extremely grateful. Thanks! MP From aboudouvas at panafonet.gr Fri Aug 3 10:58:39 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Fri, 03 Aug 2007 07:58:39 -0700 Subject: Eclipse/PyDev question. Message-ID: <1186153119.391091.275860@r34g2000hsd.googlegroups.com> Hi, this is actually a question to those of us who use Eclipse and Pydev as their main Python developing environment. As i use Eclipse (3.3 Europa) only for Python and i have nothing to do with Java, is there a way to disable/uninstall some Java-specific stuff and make the environment actually more snappy ?? thanks for any help From rcdailey at gmail.com Mon Aug 20 16:53:12 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 20 Aug 2007 15:53:12 -0500 Subject: optparse - required options In-Reply-To: <46C9F7D1.9040506@jayloden.com> References: <496954360708201251r137dfaedqe632361891eae343@mail.gmail.com> <46C9F7D1.9040506@jayloden.com> Message-ID: <496954360708201353v19ea266cr50f144d1d71d5912@mail.gmail.com> Well, I don't know what is wrong with people then. I don't see how required arguments are of bad design. Some command-line applications are built around performing tasks based on information received. Compilers, for example. A compiler can't do much of anything unless you give it at the very least a filename. So, a --file command would most definitely be one required argument. Anyway, I'm not trying to start a debate on this issue. I have my own implementation for required arguments at the moment, I am just a little bit surprised that this module doesn't make it convenient. It would definitely help on code duplication. Thanks for your response. On 8/20/07, Jay Loden wrote: > > Robert Dailey wrote: > > Hi, > > > > I've been reading through the python documentation on the optparse > > module and I was unable to find out how to specify if an option is > > optional or required. The documentation vaguely states that actions can > > be used to do this, however I was not able to figure out how. If anyone > > could help I'd greatly appreciate it. > > > > According to the optparse docs: > > required option > an option that must be supplied on the command-line; note that the > phrase ``required option'' is self-contradictory in English. optparse > doesn't prevent you from implementing required options, but doesn't > give you much help at it either. See examples/required_1.py and > examples/required_2.py in the optparse source distribution for two > ways to implement required options with optparse. > > > And from what I can see, this seems to be somewhat intentional, see > http://wiki.python.org/moin/OptParse the note at the bottom with a link to > a mailing list thread. As far as I can tell, evidently some people feel that > required options are indicative of a bad design and therefore optparse was > designed not to make this easy on the programmer. > > -Jay > -------------- next part -------------- An HTML attachment was scrubbed... URL: From winter at biotec.tu-dresden.de Tue Aug 21 15:00:05 2007 From: winter at biotec.tu-dresden.de (Christof Winter) Date: Tue, 21 Aug 2007 21:00:05 +0200 Subject: How to optimise this code? In-Reply-To: References: Message-ID: <46CB3635.7050705@biotec.tu-dresden.de> David N Montgomery wrote: > class testCase: > def __init__(self, tc): > if tc == 1:self.testCase1() > if tc == 2:self.testCase2() > if tc == 3:self.testCase3() > if tc == 4:self.testCase4() > if tc == 5:self.testCase5() > if tc == 6:self.testCase6() > > def testCase1(self): > print "tc1" > > def testCase2(self): > print "tc2" > > def testCase3(self): > print "tc3" > > def testCase4(self): > print "tc4" > > def testCase5(self): > print "tc5" > > def testCase6(self): > print "tc6" > > > def testCaseX(self): > print "tcX" > > totalNumberOfTestCases = 6 > x = 0 > while x <= totalNumberOfTestCases: > x += 1 > testCase(x) > > > This template code is working, but I envisage having 100+ test cases and > am concerned about my useage of if statements. I would be grateful for > any pointers as to how I can run all tests cases, regardless of how > many, in a more efficient manner. > > Thank you in advance. To get rid of the if statements, replace __init__ function with: def __init__(self, tc): functionToCall = eval("self.testCase%s" % tc) functionToCall() HTH, Chris From kyosohma at gmail.com Wed Aug 29 09:23:00 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 29 Aug 2007 06:23:00 -0700 Subject: self extracting zipefile (windows) and (standard module) zipefile In-Reply-To: <1188388421.010643.19050@50g2000hsm.googlegroups.com> References: <1188388421.010643.19050@50g2000hsm.googlegroups.com> Message-ID: <1188393780.454058.196360@22g2000hsm.googlegroups.com> On Aug 29, 6:53 am, Werner wrote: > Hi, > > I try to read (and extract) some "self extracting" zipefiles on a > Windows system. The standard module zipefile seems not to be able to > handle this. > > >>> fName = r"C:\tmp\mySelfExtratingFile.exe" > >>> import zipfile > >>> zipefile.is_zipfile(fName)) > > False > > Is there a wrapper or has some one experience with other libaries to > extract those files? > > Thanks in advance > Werner Since it's an executable, why not just use the subprocess module? I did find this set of scripts, but I don't know if they will help: http://www.example-code.com/python/zip.asp I did find how to extract via the command line, which you could use in conjunction with the subprocess module: http://help.globalscape.com/help/cutezip2/Creating_and_extracting_archives.htm Mike From NO_Kroeger at gmx.de Tue Aug 21 13:58:16 2007 From: NO_Kroeger at gmx.de (=?ISO-8859-1?Q?Nils_Oliver_Kr=F6ger?=) Date: Tue, 21 Aug 2007 19:58:16 +0200 Subject: Python is removing my quotes! In-Reply-To: <496954360708210927w10655bbdtc977aace232bf05d@mail.gmail.com> References: <496954360708210900p6da42670o3a28d6b0dbd4c524@mail.gmail.com> <46CB0E29.2010306@islandtraining.com> <496954360708210927w10655bbdtc977aace232bf05d@mail.gmail.com> Message-ID: <46CB27B8.4000205@gmx.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Robert Dailey schrieb: > Thank you for your response. The back slashes work! It's a bit annoying; but > I have Microsoft to thank for that. It's not Microsoft, you would experience the same problems under any Unix I know of. At least the bash treats quotes as special characters, so does afaik the sh and a couple of other shells in the Unixverse. You will also need to escape blanks and depending on the shell a number of other special characters (like for example the pipe). Greetings Nils -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGyye3zvGJy8WEGTcRAuWiAJ9SVUmNtQDkeGO1zBIXLeL548kXswCeMAEA zYMRE8LSV/9kYiAQkCz1PAU= =oDke -----END PGP SIGNATURE----- From rrs at researchut.com Mon Aug 13 14:02:11 2007 From: rrs at researchut.com (Ritesh Raj Sarraf) Date: Mon, 13 Aug 2007 23:32:11 +0530 Subject: Module imports during object instantiation References: <4c3vo4-u7k.ln1@learner.hq.netapp.com> Message-ID: <3ui6p4-lt3.ln1@learner.hq.netapp.com> Steve Holden wrote: > Ritesh Raj Sarraf wrote: >> class Log: >> >> def __init__(self, verbose, lock = None): >> >> if verbose is True: >> self.VERBOSE = True >> else: self.VERBOSE = False >> > Better: > > self.VERBOSE = verbose > > or, if you suspect verbose might pass in a mutable value, > > self.VERBOSE bool(verbose) > Thanks for pointing this out. > What's leading you to conclude the import isn't being executed? You > realise, I trust, that the module's code will only be executed on the > first call to __init__()? > Well. Putting it in a "try" inside __init__() doesn't do anything. The import never happens. And thus if I make a call in any of the methods, it fails with an error message. A NameError IIRC. > You are right in assuming that __init__() is called once per instance > created, and it's legitimate to make an import conditional in the way > you have because of the "execute code only once" behavior - if the > module is already in sys.modules then it won't be re-imported, the > existing one will be used. > This is what even my understanding is. But am afraid to say that this understanding is not implemented in Python. Have you tried doing this? Does it work for you? > Having said all that, I still don't see why you can't just put the > try/except at the top level of your code and have color be a global. Why > repeat the attempted import and the computation for each object you > create? Alternatively, do it at the class level, so it's only executed > once when the class is declared? > Hmmm!! This is where I might not have done my homework. I just tried to import the same class (Log) the following way and it worked. from module import Log It worked. Now I have some questions. Going with your point of try/except imports at the top level, I am having multiple imports at the top level for the multiple classes that I have in the module. Not everything from the top level imports is required for the class Log (Say, just one module is what is required). So when I do a `from module import Log`, do all the modules at the top level get imported? My understanding says Yes, and if that's true, that's bad IMO. (Sorry! I'd really not thought about this when reading about Python module imports) My ultimate goal is to make all my classes as independent as possible while keeping them as lightweight as possible. If all top level module import statements are getting executed during a `from module import class`, this is _not_ lightweight IMO. That's what led me to try imports in __init__() but unfortunately I haven't seen that working for me even once. Ritesh -- If possible, Please CC me when replying. I'm not subscribed to the list. From Karsten.G.Weinert at googlemail.com Thu Aug 9 10:54:10 2007 From: Karsten.G.Weinert at googlemail.com (Karsten W.) Date: Thu, 09 Aug 2007 07:54:10 -0700 Subject: py2exe, command line parameter problem Message-ID: <1186671250.863328.204810@r34g2000hsd.googlegroups.com> Hello, my small program is a Tkinter-App which supports some command line options. When the app is started within the python environment, everything works fine. When the py2exe-frozen app is started, everything works until I pass command line parameters. Then the gui window is not displayed. It's python 2.3 on WinXp with py2exe 0.6.6. How can I debug this behaviour? Any hint appreciated, Karsten. From pacman128 at gmail.com Tue Aug 14 15:49:16 2007 From: pacman128 at gmail.com (Paul Carter) Date: Tue, 14 Aug 2007 19:49:16 -0000 Subject: module: zipfile.writestr - line endings issue In-Reply-To: <1187112768.095414.223640@w3g2000hsg.googlegroups.com> References: <1187107452.905165.45700@l70g2000hse.googlegroups.com> <1187110504.154878.317460@19g2000hsx.googlegroups.com> <1187112768.095414.223640@w3g2000hsg.googlegroups.com> Message-ID: <1187120956.574400.99170@g4g2000hsf.googlegroups.com> On Aug 14, 1:32 pm, towers wrote: > Thanks - your code works for me also. > > But I still get the issue when I read the file directly and add it to > the archive. > > Say if I: > > 1. Use the test.csv file created with your code - currently the line > endings look good (viewed in notepad on Win XP) > 2. Run the following code: > > # begin code > import zipfile > import os.path > > # Now, create the zipfile > dfile = open('test.csv', 'r') > zip_file = zipfile.ZipFile(r'C:\temp\ice\line endings\test.zip', 'w', > zipfile.ZIP_DEFLATED) > zip_file.writestr('test.csv',dfile.read()) > dfile.close() > zip_file.close() > > 3. Then extract the file and the file endings have been corrupted. Now > one long line in notepad. (Other programs interpret correctly though.) > > Maybe the issue lies with this way (i.e. dfile.read()) of writing the > file to the archive...possibly. > > Damon > Please don't top post. The problem is with how you are opening the file. You need to open in binary mode if you wish to read your file unaltered. Also, file() is preferred over open() these days I think. Use: dfile = file('test.csv', 'rb') -- Paul Carter From rbygscrsepda at gmail.com Mon Aug 6 22:45:23 2007 From: rbygscrsepda at gmail.com (rbygscrsepda at gmail.com) Date: Tue, 07 Aug 2007 02:45:23 -0000 Subject: Relative-importing * In-Reply-To: <87zm15870h.fsf@benfinney.id.au> References: <1185559874.299008.167010@x40g2000prg.googlegroups.com> <871weth2gg.fsf@benfinney.id.au> <46ae3894$0$19609$426a34cc@news.free.fr> <1186200218.666444.254200@q3g2000prf.googlegroups.com> <87vebv9yrr.fsf@benfinney.id.au> <1186363732.188847.48070@q3g2000prf.googlegroups.com> <87zm15870h.fsf@benfinney.id.au> Message-ID: <1186454723.425679.220510@q3g2000prf.googlegroups.com> On Aug 6, 12:19 am, Ben Finney wrote: > rbysam... at gmail.com writes: > > (In addition, it probably would make the program somewhat slower to > > have an internal class inside every module, and performance is > > important to me, as I'm planning to use this project in a future > > game. > > This is known as "premature optimisation", and it's harmful. It's > folly to avoid a core part of the language because you're worried > about hypothetical performance issues. > > Instead, write your program so that it's easy to understand and > maintain; then, if it's noticeably slow, *measure* the performance > using profiling so you know exactly what is slow; then, and only then, > work on speeding up the slow parts. > > > These modules are not going to have full-fledged object construction > > and so forth. I don't want to construct and use objects at all > > If that's truly what you desire, you're using the wrong > language. Everything inPythonis an object, even if you don't use > object-oriented programming. > > > it seems like a waste of time and memory to me to inherit __new__, > > __del__, and so on. > > You've stated that you're a beginner to programming, so you probably > are unaware that this statement has no basis in how class inheritance > actually works. The point is that inherited behaviour is implemented > in *one* place, not that it's repeated everywhere. > > Moreover, this is a further expression of your tendency for premature > optimisation. You should aim instead to write code naturally (learning > what's natural when you're a beginner), and only once you have > something that *works* should you think about performance issues. > > > All that I want these modules to do is to encapsulate varying > > information and behavior for /other/ objects to use.) > > This sounds like an ideal case for seeting up a class hierarchy for > this move behaviour. > > > But regardless of if it's the "right thing to do", do you all think > > it's an unintended bug? > > Do we think what is an unintended bug? > > I think if you go out of your way to avoid the class inheritance > system for implementing what looks strongly like a hierarchy of > behaviour, you will have design bugs. Hopefully now that you're > reading this thread, they won't be *unintended* bugs; whether you > *intentionally* proceed with a buggy design is up to you :-) > > -- > \ "With Lisp or Forth, a master programmer has unlimited power | > `\ and expressiveness. WithPython, even a regular guy can reach | > _o__) for the stars." -- Raymond Hettinger | > Ben Finney I understand what you're saying; thank you for the advice. :) But unfortunately, my original question wasn't completely answered. I wasn't asking about if my own program had a bug, in the first place. I was asking if the error I talked about in the first post was a bug in the Python compiler itself. It's undocumented, and so it seems unintended--especially since importing * is a feature built in to Python on purpose, whether or not it's easily abused or if it's useful. Here's the error again--whenever you try to import * from a relative package like ., .., .sibling, ..cousin, and any other package name starting with "*", you get an error. Specifically, in Python 1.5, all of the following generate the error below: from . import * from .sibiling_package import * from .. import * from ..cousin_package import * SyntaxError: 'import *' not allowed with 'from .' Importing * is a feature, but this seems like an artificial inconsistency to me. It's as if the compiler raises an error when it tries to import * as soon as it sees "from .", regardless of what comes after it. So is this a bug in python? And if it happens to be a bug, how can I alert the developers of the python compiler? Again, thank you! :) From james.p.news at gmail.com Thu Aug 23 15:54:17 2007 From: james.p.news at gmail.com (james.p.news at gmail.com) Date: Thu, 23 Aug 2007 19:54:17 -0000 Subject: libgmail failure In-Reply-To: <1187841574.800105.219970@z24g2000prh.googlegroups.com> References: <1187730447.621592.93740@q4g2000prc.googlegroups.com> <1187841574.800105.219970@z24g2000prh.googlegroups.com> Message-ID: <1187898857.060464.175200@z24g2000prh.googlegroups.com> Thanks! That worked brilliantly. -James From jeffrey at fro.man Sun Aug 19 12:48:28 2007 From: jeffrey at fro.man (Jeffrey Froman) Date: Sun, 19 Aug 2007 09:48:28 -0700 Subject: How to find script's directory References: Message-ID: <13cgt2t39d2m32@corp.supernews.com> Papalagi Pakeha wrote: > I guess I could do it with a little help of os.path.realpath() for all > those cases where absolute or relative path was used. But how should I > approach it when it's invoked as plain 'blah.py' because its directory > name is in $PATH? Use the value of __file__ rather than sys.argv[0] -- it contains the directory information. You may still need to normalize the value using various os.path functions. Jeffrey From rschroev_nospam_ml at fastmail.fm Sat Aug 11 17:10:18 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 11 Aug 2007 21:10:18 GMT Subject: Something in the function tutorial confused me. In-Reply-To: References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <1186424693.529497.217040@w3g2000hsg.googlegroups.com> <46B8626A.2070303@bigfoot.com> <5hsoi3F3mlni2U1@mid.individual.net> <1186581124.3383.55.camel@dot.uniqsys.com> <1i2nhxn.tme05x17r39odN%aleax@mac.com> Message-ID: <_Apvi.47643$p5.1534144@phobos.telenet-ops.be> Gregory D. Weber schreef: > Neil Cerutti wrote: >> On 2007-08-11, Alex Martelli wrote: >>> Neil Cerutti wrote: >>> ... >>>> The Python Language Reference seems a little confused about the >>>> terminology. >>>> >>>> 3.4.7 Emulating numeric types >>>> 6.3.1 Augmented assignment statements >>>> >>>> The former refers to "augmented arithmetic operations", which I >>>> think is a nice terminology, since assignment is not necessarily >>>> taking place. Then the latter muddies the waters. >>> Assignment *IS* "necessarily taking place"; if you try the augmented >>> assignment on something that DOESN'T support assignment, you'll get an >>> exception. Consider: >>> >>>>>> tup=([],) >>>>>> tup[0] += ['zap'] >>> Traceback (most recent call last): >>> File "", line 1, in >>> TypeError: 'tuple' object does not support item assignment >>> >>> Tuples don't support item ASSIGNMENT, and += is an ASSIGNMENT, >>> so tuples don't allow a += on any of their items. >>> >>> If you thought that += wasn't an assignment, this behavior and >>> error message would be very problematic; since the language >>> reference ISN'T confused and has things quite right, this >>> behavior and error message are perfectly consistent and clear. >> Thanks for the correction. I was under the illusion that >> sometimes augmented assignment would instead mutate the >> object. >> > > I too thought += was an assignment. And it bit me very painfully a few weeks ago. It is an assignment, but not only an assignment: first either the creation of a new object (in case of immutable objects) or the modification of an existing object (in case of mutable objects), than an assignment. > If it's an assignment, then wouldn't "x += y" mean the same thing as "x = x + y"? No: - x += y, x is only evaluated once - in x += y, the operation is performed in-place if possible, meaning that (quoting from the language reference): rather than creating a new object and assigning that to the target, the old object is modified instead > If so, why does an assignment to variable a, below, have the *side effect* of changing variable b ... ? > >>>> a = [1, 2, 3] -> A list is created and assigned to a >>>> b = a -> That list is also assigned to b >>>> b > [1, 2, 3] >>>> a += [4] -> The list is modified (the list [4] is added to it) and assigned to a. It was already assigned to a, so that assignment doesn't do very much in this case. But it is performed. >>>> a > [1, 2, 3, 4] >>>> b > [1, 2, 3, 4] -> Both a and b are still bound to the original (but now modified) list object > ... but using the "x = x + y" style, the assignment to variable c, below, does *not* have a side effect on variable d (as indeed it should not!)? > >>>> c = [1, 2, 3] -> A list is created and assigned to c >>>> d = c -> That list is also assigned to d >>>> d > [1, 2, 3] >>>> c = c + [4] -> A new list object is created (the sum of the original one and the list [4]) and assigned to c >>>> c > [1, 2, 3, 4] -> c is now bound to the new list object >>>> d > [1, 2, 3] -> ... while d is still bound to the original list object I hope this clears up things a bit... -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From naga86 at gmail.com Wed Aug 22 00:03:56 2007 From: naga86 at gmail.com (Nagarajan) Date: Tue, 21 Aug 2007 21:03:56 -0700 Subject: Server-side scripting in python In-Reply-To: References: <1187614732.519547.296020@j4g2000prf.googlegroups.com> Message-ID: <1187755436.972359.293360@i13g2000prf.googlegroups.com> On Aug 21, 6:40 pm, cla... at lairds.us (Cameron Laird) wrote: > In article <1187614732.519547.296... at j4g2000prf.googlegroups.com>,Nagarajan wrote: > >Hi group, > >I need to develop a web application. I am in a fix as to choose among > >the various server-side scripting options. I want to explore python > >(am a newbie) to gain expertise and upon search, I learnt about > >PSP(Python Server Pages) that uses Jython as its scripting language. > >Is it a better option over PHP or Perl? Could anyone point out the > >pros and cons of using PSP over others? > > . > . > . > I suspect that several of us don't understand your question. > > Python supports several--arguably, a plethora, more than any other > language--distinct "frameworks" for server-side scripting of Web > applications . > PSP certainly is among these, although it's recommended less often than > several others. Is PSP better than PHP or Perl? First, do you > understand that PSP isn't directly comparable to PHP or Perl? The > latter two are languages, while PSP is a Web framework. In any > case, the answer is certain to be, "it depends". There certainly > are situations for each of PSP, PHP, Perl, and many other technol- > ogies. > > I summarize: if you have an interest in practicing Python while > building Web applications, your prospects certainly are bright; > you'll receive abundant help from the folks here and elsewhere. > For us to provide more specific details about Perl, PSP, and so > on, meaningful to your own needs, will only be possible when you > articulate the latter more fully . Let me phrase my problem in a finer way. I have done simple projects in python. I wanted to explore web programming facet of python. The problem at my hand is to develop an email web client. I've developed web applications in PHP. I need to evaluate python-based web frameworks to make a smart choice of the web framework or a language like PHP, Perl based on performance predominantly. Do I make myself clear now? Thanks for all the help extended. From rpk.general at gmail.com Sun Aug 12 01:08:26 2007 From: rpk.general at gmail.com (Rohit) Date: Sun, 12 Aug 2007 05:08:26 -0000 Subject: Database intensive application Message-ID: <1186895306.237395.189530@z24g2000prh.googlegroups.com> I am a novice. I want to know whether Python can be used to develop client/server database and web applications like .NET. Which is the best book/source to learn Python? From nachogomez at gmail.com Sun Aug 5 03:17:43 2007 From: nachogomez at gmail.com (=?UTF-8?Q?Ra=C3=BAl_G=C3=B3mez_C.?=) Date: Sun, 5 Aug 2007 03:17:43 -0400 Subject: Tkinter or wxpython? In-Reply-To: <1186122505.996640.262520@d55g2000hsg.googlegroups.com> References: <1186122505.996640.262520@d55g2000hsg.googlegroups.com> Message-ID: <684b0a740708050017h373397fgc307819583c0b2d9@mail.gmail.com> Well, for a newbie I think the best choice is PythonCard, is a framework based on wxPython but much more simple, check it out! On 8/3/07, Glenn Hutchings wrote: > > On Aug 3, 1:00 am, "wang frank" wrote: > > I want to build a GUI to execut python script. I found TKinter and > > wxpython. Which one is easier for a newbie? and which one is better? > > Well, Tkinter comes with Python, so newbies can get up and running > straight away without having to download and install anything else. > And there are probably lots more examples out there that a newbie can > look at and learn from. As for *better*, wxPython has a lot more > kinds of widgets in it, which will make writing GUIs less tedious in > the long run, and the widgets look a lot nicer too. > > Glenn > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Fri Aug 3 09:34:43 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 03 Aug 2007 06:34:43 -0700 Subject: Help: GIS In-Reply-To: <1186112804.718290.207580@z24g2000prh.googlegroups.com> References: <1186112804.718290.207580@z24g2000prh.googlegroups.com> Message-ID: <1186148083.009159.89310@j4g2000prf.googlegroups.com> On Aug 2, 10:46 pm, zxo102 wrote: > Hi, > I am new in GIS area and need your suggestions for where I can > start from. I have a python based web application with a database. > Now I would like to add a GIS map into my application. When a user > clicks a certain area in the GIS map, it can grab the data from the > database via my python based application. Do I have to use MapServer > or Grass or some other backends for this purpose? > Thanks a lot. > > Ouyang While I am not a part of our GIS department, they use ArcGIS which has Python support built in. If that's what you're using, you should be able to use the examples given on ESRI's website: http://www.spatialvision.com.au/html/tips-python-arc9.htm Hmmm...not much there. Here are some other links I found: http://nrm.salrm.uaf.edu/~dverbyla/arcgis_python/index.html http://www.ollivier.co.nz/publication/uc2004/python_workshop/sld008.htm http://www.3dartist.com/WP/python/pycode.htm I don't know if these will be much help. You really need to just dig in and start coding. I would recommend "Programming Python 3rd Ed." by Lutz if you want something in hard copy. "Dive Into Python" is a free book that's online that I'm told is very good. Both have good examples, some of which are involved. All the web oriented Python books are a few years old, but the code in them still works, for the most part. Mike From fabioztessitore at libero.it Wed Aug 1 03:53:41 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 01 Aug 2007 07:53:41 GMT Subject: Error with Tkinter and tkMessageBox References: <46af71b7$0$10619$4fafbaef@reader2.news.tin.it> <1185909168.055341.90910@d30g2000prg.googlegroups.com> <46af8c5d$0$10619$4fafbaef@reader2.news.tin.it> Message-ID: <46b03c04$0$4796$4fafbaef@reader4.news.tin.it> Il Tue, 31 Jul 2007 18:45:57 -0400, jim-on-linux ha scritto: > Try This: > > def reply(): > showinfo('ciao','hello') > I've tried without success ... thanks I've also discovered that when I (or some other prog using tkinter) display menu, the underscore is an ugly little black box. So, tkinter don't work fine on my machine. What a pity! thanks, all, bye From mark.dufour at gmail.com Wed Aug 22 11:00:19 2007 From: mark.dufour at gmail.com (srepmub) Date: Wed, 22 Aug 2007 15:00:19 -0000 Subject: Shed Skin Python-to-C++ compiler 0.0.23 In-Reply-To: <1187725658.819624.309370@r34g2000hsd.googlegroups.com> References: <1187725658.819624.309370@r34g2000hsd.googlegroups.com> Message-ID: <1187794819.745225.240130@j4g2000prf.googlegroups.com> > Adding socket support would certainly open the door for many common > classes applications. If I had my pick, I say, sockets and then re. Thanks. Especially sockets should be not too hard to add, but I probably won't work on these directly myself. Let me know if you are interested.. :-) > BTW, I gatta say projects like shedskin and pypy are the most exciting > python projects I'm aware of. Please keep of the good work. I'm so > excited about the day I can begin using shedskin for the types of > projects I use python on. I'm practically working alone on Shedskin, so the better bet will be PyPy, unless I start getting more help. BTW I usually add a link to the homepage, but somehow I forgot this time: http://mark.dufour.googlepages.com Thanks! Mark Dufour. From rcdailey at gmail.com Thu Aug 2 14:53:14 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 2 Aug 2007 13:53:14 -0500 Subject: XML Processing In-Reply-To: <1186080339.344993.167670@z24g2000prh.googlegroups.com> References: <1186080339.344993.167670@z24g2000prh.googlegroups.com> Message-ID: <496954360708021153l2b20f522ia690707a8fdd7aa3@mail.gmail.com> Both strings in your example are exactly the same, unless I'm missing something. On 8/2/07, Roman wrote: > > Is there a package that converts a string that contains special > characters in xml to to literal value. For instance, converts string > http://myhome/¶m to http://myhome/¶m. > > Thanks in advance > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgoldenberg at gmail.com Thu Aug 9 18:14:46 2007 From: bgoldenberg at gmail.com (Benjamin Goldenberg) Date: Thu, 09 Aug 2007 22:14:46 -0000 Subject: Querying Graphics Card Name In-Reply-To: <46bb8ff6$0$25982$afc38c87@news.optusnet.com.au> References: <1186686984.160312.175270@i13g2000prf.googlegroups.com> <46bb8ff6$0$25982$afc38c87@news.optusnet.com.au> Message-ID: <1186697686.543735.261100@i13g2000prf.googlegroups.com> On Aug 9, 4:06 pm, Richard Jones wrote: > Benjamin Goldenberg wrote: > > I would like to find out the name of the graphics card of the machine > > my program is running on. I have looked into the pyopengl module, and > > using them to query the card, but it seems like there ought to be a > > simpler way to find this out without setting up a glcontext. Does > > anyone have any ideas? > > You need a context if you're going to ask OpenGL to tell you what the card > is. To find out any other way would be highly platform-specific, possibly > though looking in the /proc directory on Linux, and who-knows-where-else on > other platforms. > > Also, have a look at tools/info.py in the pyglet project > > > Richard Thanks for the reference, but I was unable to find tools/info.py in pyglet. What would be the full path to this file? Thanks. From grante at visi.com Fri Aug 31 11:52:22 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 31 Aug 2007 15:52:22 -0000 Subject: Looking for Delaunay triangulation module... Message-ID: <13dge9m2339ka68@corp.supernews.com> Can anybody point me to a Delaunay triangulation module (for Win32)? I'm currently using http://flub.stuffwillmade.org/delny/ under Linux, but I have been unable to find a build for Windows. I don't have the tools (or skills) to build libqhull and Pythion extensions on Win32). I've also found the delaunay module in scipy's "sandbox". I could never get that module to work under Linux, and I can't build it for Windows anyway. So for lack of a delaunay module, I'm stuck trying to port my application to Win32. I've spent some time Googling and found various references to pur Python delaunay modules that were abandoned because they were slow (though I haven't been able to find any of the actual modules). Slow is better than none. ;) -- Grant Edwards grante Yow! An air of FRENCH FRIES at permeates my nostrils!! visi.com From ldo at geek-central.gen.new_zealand Fri Aug 31 00:48:02 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 31 Aug 2007 16:48:02 +1200 Subject: Code design problem References: <1188389375.238847.298320@w3g2000hsg.googlegroups.com> Message-ID: In message <1188389375.238847.298320 at w3g2000hsg.googlegroups.com>, Marco Nawijn wrote: > The problem I face is that the implementation of the application class > is completely different for the local and remote case. The local case is a > straightforward implemenation using the subprocess module, the remote > case is a CORBA implementation. Any reason why you need to use something as complex as CORBA? On *nix systems, depending on filesystem access issues, the difference between local and remote execution of commands isn't much more than cmd versus ssh host cmd From managerrrr at gmail.com Tue Aug 21 19:15:15 2007 From: managerrrr at gmail.com (managerrrr at gmail.com) Date: Tue, 21 Aug 2007 23:15:15 -0000 Subject: Free Air Conditioners!!!!!! Message-ID: <1187738115.972271.94080@r23g2000prd.googlegroups.com> http://freeairconditioners.blogspot.com/ From uymqlp502 at sneakemail.com Fri Aug 31 01:18:36 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Thu, 30 Aug 2007 22:18:36 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> Message-ID: <1188537516.622167.115080@z24g2000prh.googlegroups.com> > I've always wondered... Are the compilers (or interpreters), which take > these programs to machine code, also formally proven correct? No, they are not formally proven correct (too complicated for that), but I believe they are certified to a higher level than your "typical" compiler. I think that Ada compilers used for certain safety-critical applications must meet higher standards than, say, GNU Ada, for example. And the OS > in which those programs operate, are they also formally proven correct? Same as above, if I am not mistaken. > And the hardware, microprocessor, electric supply, etc. are they also > 'proven correct'? I think the microprocessors used for flight control, for example, are certified to a higher level than standard microprocessors. How would you prove a power supply to be "correct"? I'm sure they meet higher reliability standards too. From vasudevram at gmail.com Sun Aug 26 10:45:15 2007 From: vasudevram at gmail.com (vasudevram) Date: Sun, 26 Aug 2007 14:45:15 -0000 Subject: Joining Big Files In-Reply-To: <1188092913.645157.15370@o80g2000hse.googlegroups.com> References: <1188035844.616831.205350@i38g2000prf.googlegroups.com> <1188090939.364787.296630@r34g2000hsd.googlegroups.com> <1188092913.645157.15370@o80g2000hse.googlegroups.com> Message-ID: <1188139515.349468.315290@q5g2000prf.googlegroups.com> On Aug 26, 6:48 am, Paul McGuire wrote: > On Aug 25, 8:15 pm, Paul McGuire wrote: > > > > > On Aug 25, 4:57 am, mosscliffe wrote: > > > > I have 4 text files each approx 50mb. > > > 50mb? Really? Did you actually try this and find out it was a > > problem? > > > Try this: > > import time > > > start = time.clock() > > outname = "temp.dat" > > outfile = file(outname,"w") > > for inname in ['file1.dat', 'file2.dat', 'file3.dat', 'file4.dat']: > > infile = file(inname) > > outfile.write( infile.read() ) > > infile.close() > > outfile.close() > > end = time.clock() > > > print end-start,"seconds" > > > For 4 30Mb files, this takes just over 1.3 seconds on my system. (You > > may need to open files in binary mode, depending on the contents, but > > I was in a hurry.) > > > -- Paul > > My bad, my test file was not a text file, but a binary file. > Retesting with a 50Mb text file took 24.6 seconds on my machine. > > Still in your working range? If not, then you will need to pursue > more exotic approaches. But 25 seconds on an infrequent basis does > not sound too bad, especially since I don't think you will really get > any substantial boost from them (to benchmark this, I timed a raw > "copy" command at the OS level of the resulting 200Mb file, and this > took about 20 seconds). > > Keep it simple. > > -- Paul There are (at least) another couple of approaches possible, each with some possible tradeoffs or requirements: Approach 1. (Least amount of code to write - not that the others are large :) Just use os.system() and the UNIX cat command - the requirement here is that: a) your web site is hosted on *nix (ok, you can do it if on Windows too - use copy instead of cat, you might have to add a "cmd /c " prefix in front of the copy command, and you have to use the right copy command syntax for concatenating multiple input files into one output file). b) your hosting plan allows you to execute OS level commands like cat, and cat is in your OS PATH (not PYTHONPATH). (Similar comments apply for Windows hosts). import os os.system("cat file1.txt file2.txt file3.txt file4.txt > file_out.txt") cat will take care of buffering, etc. transparently to you. Approach 2: Read (in a loop, as you originally thought of doing) each line of each of the 4 input files and write it to the output file: ("Reusing" Paul McGuire's code above:) outname = "temp.dat" outfile = file(outname,"w") for inname in ['file1.dat', 'file2.dat', 'file3.dat', 'file4.dat']: infile = file(inname) for lin in infile: outfile.write(lin) infile.close() outfile.close() end = time.clock() print end-start,"seconds" # You may need to check that newlines are not removed in the above code, in the output file. Can't remember right now. If they are, just add one back with: outfile.write(lin + "\n") instead of outfile.write(lin) . ( Code not tested, test it locally first, though looks ok to me. ) The reason why this _may_ not be much slower than manually coded buffering approaches, is that: a) Python's standard library is written in C (which is fast), including use of stdio (the C Standard IO library, which already does intelligent buffering) b) OS's do I/O buffering anyway, so do hard disk controllers c) from some recent Python version, I think it was 2.2, that idiom "for lin in infile" has been (based on somethng I read in the Python Cookbook) stated to be pretty efficient anyway (and yet (slightly) more readable that earlier followed approaches of reading a text file). Given all the above facts, it probably isn't worth your while to try and optimize the code unless and until you find (by measurements) that it's too slow - which is a good practice anyway: http://en.wikipedia.org/wiki/Optimization_(computer_science) Excerpt from the above page (its long but worth reading, IMO): "Donald Knuth said, paraphrasing Hoare[1], "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." (Knuth, Donald. Structured Programming with go to Statements, ACM Journal Computing Surveys, Vol 6, No. 4, Dec. 1974. p.268.) Charles Cook commented, "I agree with this. It's usually not worth spending a lot of time micro-optimizing code before it's obvious where the performance bottlenecks are. But, conversely, when designing software at a system level, performance issues should always be considered from the beginning. A good software developer will do this automatically, having developed a feel for where performance issues will cause problems. An inexperienced developer will not bother, misguidedly believing that a bit of fine tuning at a later stage will fix any problems." [2] " HTH Vasudev ----------------------------------------- Vasudev Ram http://www.dancingbison.com http://jugad.livejournal.com http://sourceforge.net/projects/xtopdf ----------------------------------------- From S.Mientki-nospam at mailbox.kun.nl Wed Aug 1 05:04:22 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 01 Aug 2007 11:04:22 +0200 Subject: Reload after an exception, not possible ? In-Reply-To: References: Message-ID: <7be74$46b04b15$d443bb3a$12979@news.speedlinq.nl> Steve Holden wrote: > Stef Mientki wrote: >> hello, >> >> I've a graphical application (wxPython), >> where the code in the main GUI loop is given below. >> >> >> 1 JAL_Loaded = False >> 2 while len(App_Running) > 0: >> 3 if JALsPy_globals.State == SS_Run: >> 4 try: >> 5 if JAL_Loaded: >> 6 reload ( JAL_simulation_file ) >> 7 else: >> 8 JAL_Loaded = True >> 9 import JAL_simulation_file >> 10 except JALsPy_globals.Reload_Exception: >> 11 JALsPy_globals.State = SS_Halt >> >> >> The first time the while loop is entered, >> JAL_Loaded is False (line 1), >> and when I press some button, >> the code will enter at line 8, >> importing a module, that has executable code with an infinite loop. >> >> To exit this infinite loop, an exception is generated (by a button >> press), >> and program comes back in the above while-loop line (10,11,2). >> >> So far so good. >> >> Then I change the code in the imported file, >> and when I start the engine again, >> the flag JAL_Loaded is True, so I don't import, >> but I reload the file. >> >> Now I get the next exception >> UnboundLocalError: local variable 'JAL_simulation_file' referenced >> before assignment >> >> So obviously I can't reload but have to do an import again >> (which makes the code much simpler ;-) >> but I don't understand why the reload raises an exception ???? >> > You have an assignment to JAL_simulation_file elsewhere inside the same > function, No these are the only 2 uses of "JAL_simulation_file" in the whole project. later in the code. This means that Python will assume that it > is local to the function, but the import statement will affect the > module namespace rather than the function namespace. > > In other words, your code is roughly equivalent to what follows, with > the added complexity that the illegal reference isn't triggered until > the second iteration of a loop. > > >>> def f(): > ... print os > ... import os > ... os = "Something" > ... > >>> f() > Traceback (most recent call last): > File "", line 1, in > File "", line 2, in f > UnboundLocalError: local variable 'os' referenced before assignment > >>> > > The solution? Don't assign to JAL_simulation_file, and the function will > use the local instead. > The solution is much simpler, but I don't understand why the "import", which really reloads the changed code in JAL_simulation_file, works the second time :-( 2 while len(App_Running) > 0: 3 if JALsPy_globals.State == SS_Run: 4 try: 9 import JAL_simulation_file 10 except JALsPy_globals.Reload_Exception: 11 JALsPy_globals.State = SS_Halt cheers, Stef Mientki From bdesth.quelquechose at free.quelquepart.fr Thu Aug 2 10:30:53 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 02 Aug 2007 16:30:53 +0200 Subject: __call__ considered harmful or indispensable? In-Reply-To: References: Message-ID: <46b24200$0$19638$426a74cc@news.free.fr> skip at pobox.com a ?crit : > I don't personally use __call__ methods in my classes, but I have > encountered it every now and then here at work in code written by other > people. The other day I replaced __call__ with a more obvious method name, > so now instead of executing > > obj(foo, bar, baz) > > the code in question is > > obj.execute(foo, bar, baz) > > In this case there was a bug. Depending on inputs, sometimes obj > initialized to a class, sometimes an instance of that class. (I fixed that > too while I was at it.) The problem was that the use of __call__ obscured > the underlying bug by making the instance as well as the class callable. I don't quite get the point here. A concrete example would be welcome. > In this particular case it was clearly unnecessary and just obfuscated the > code. I'm wondering, are there some general cases where __call__ methods of > a user-defined class are simply indispensable? "simply indispensable", I don't know. FWIW, most of the features of Python are not "simply indispensable" !-) Most of what you can do with a callable instance can be done with closures (and is usually done so in FPLs), but given Python's OO nature, it's sometimes clearer and simpler to use callable instances than closures. One example that comes to mind is partial application that I first saw implemented with closures in Django, then as a class in PEP 309's example. Another common use case is parameterized function decorators, that are often cleaner (IMHO) when implemented as classes with __call__ than with three levels of nested funcs. In both cases, closures and callables implementations are functionally equivalent, and this is transparent for user code, so it's mostly a matter of readability and personal preferences... As far as I'm concerned, I do use __call__ "every know and then". Usually, because I had to pass a callable to some API and needed to parameterize it (IOW, ad-hoc partial application). From bj_666 at gmx.net Thu Aug 23 17:14:48 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 23 Aug 2007 21:14:48 GMT Subject: Redo: Problem with dynamic creation of classes. References: Message-ID: <5j6bm8F3t3hraU1@mid.uni-berlin.de> On Thu, 23 Aug 2007 16:55:21 -0400, Steven W. Orr wrote: > So it looks like the IFRAMED2 class which inherits from D2 is starting out > with the same id value for Encode as SNRMD which inherits from D, even > though D2 defines its own Encode method. > > Is it me of is it the interpreter doing something wrong? Hard to tell without seeing where `IFRAMED2` is bound and without knowing what you actually want to do. Can you provide a self contained example that people here can actually try!? Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Fri Aug 31 21:50:34 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 31 Aug 2007 21:50:34 -0400 Subject: Parameter Passing - String Variable Truncated ? In-Reply-To: References: <1188604442.700651.94530@19g2000hsx.googlegroups.com> Message-ID: <46D8C56A.8020402@holdenweb.com> Steve Holden wrote: [...] >> in_featclass = sys.argv[1] > > Try > > in_featclass = sys.argv[1:] > Sorry, that should have been in_featclass = " ".join(sys.argv[1:])+"\n" regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From DustanGroups at gmail.com Tue Aug 28 21:09:46 2007 From: DustanGroups at gmail.com (Dustan) Date: Wed, 29 Aug 2007 01:09:46 -0000 Subject: Check for dict key existence, and modify it in one step. In-Reply-To: <1188324792.670603.208980@r29g2000hsg.googlegroups.com> References: <1188311810.226363.295500@w3g2000hsg.googlegroups.com> <1188324792.670603.208980@r29g2000hsg.googlegroups.com> Message-ID: <1188349786.261196.80580@d55g2000hsg.googlegroups.com> On Aug 28, 1:13 pm, rodrigo wrote: > evan, > > yes, it does help. Works like it should: > > class CountingDictionary(dict): > def increment(self, key, delta=1): > self[key] = self.get(key, 0) + delta > > d = CountingDictionary() > d.increment('cat') > d.increment('dog',72) > print d > > >>> {'dog': 72, 'cat': 1} > > Thanks! You responded to the answer that made the least use of already existing recourses in python. Just letting you know. From NikitaTheSpider at gmail.com Sun Aug 12 12:21:25 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Sun, 12 Aug 2007 12:21:25 -0400 Subject: LRU cache? References: <7x8x8ixomj.fsf_-_@ruckus.brouhaha.com> Message-ID: In article <7x8x8ixomj.fsf_-_ at ruckus.brouhaha.com>, Paul Rubin wrote: > Anyone got a favorite LRU cache implementation? I see a few in google > but none look all that good. I just want a dictionary indexed by > strings, that remembers the last few thousand entries I put in it. > > It actually looks like this is almost a FAQ. A well-written > implementation would probably make a good standard library module. This one works for me: http://www.webfast.com/~skip/python/Cache.py -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From rgilbert88 at comcast.net Tue Aug 28 07:50:22 2007 From: rgilbert88 at comcast.net (Richard B. Gilbert) Date: Tue, 28 Aug 2007 07:50:22 -0400 Subject: Let's Unite Against Jews and Mongrels! References: <1188198797.772672.60840@r29g2000hsg.googlegroups.com> <1188300284.507909.126770@57g2000hsv.googlegroups.com> Message-ID: <46D40BFE.2020301@comcast.net> Dustan wrote: > On Aug 27, 2:13 am, Nenad Milicevic - The Aryan Serb > wrote: > >>Let's break the chains of Jewish and black domination! > > > A) Why? > B) What chains? > Posting such as the one that started this thread are best ignored! Unless, of course, someone has a working "Killbot". If anyone has such a thing, please kill that "MI5victim" moron as well! From mcl.office at googlemail.com Thu Aug 23 10:23:20 2007 From: mcl.office at googlemail.com (mosscliffe) Date: Thu, 23 Aug 2007 07:23:20 -0700 Subject: Symbolic Link In-Reply-To: References: <1187475296.173269.263080@k79g2000hse.googlegroups.com> <1187555373.202634.163160@57g2000hsv.googlegroups.com> <1187646982.760523.195750@i38g2000prf.googlegroups.com> Message-ID: <1187879000.370831.118780@j4g2000prf.googlegroups.com> On 22 Aug, 00:05, Ian Clark wrote: > Hyuga wrote: > > On Aug 19, 4:29 pm,mosscliffe wrote: > >> The source file is in an area which python can see, but not the > >> browser. I am trying to make a link in a browser friendly area so I > >> can use it to display an image file. > > > You might want to try using an .htaccess file. Place a file > > called .htaccess in the "browser friendly area" and place in it the > > line: > > > Options +FollowSymLinks > > > Assuming your hosting service will allow that, then it should work. > > If not, then why not just copy the image files? Storage is cheap > > these days. > > > Hyuga > > My question would be why a symbolic link? Why not a hard link? Are the > two directories on different mount points? After the script finishes > does python need to see that image file again? Why not just move it? > > Ian I just imagined a symbolic link would be quicker. I have tested a hard link now and it seems to work fine. I am deleting the link/s at the end of the session/s. I think a link is better than a move, because there is always a possibility I might somehow delete the moved file and then I would lose the original one. Thanks for your help. Richard From http Sat Aug 4 17:59:36 2007 From: http (Paul Rubin) Date: 04 Aug 2007 14:59:36 -0700 Subject: the one python book References: Message-ID: <7xr6mjot9z.fsf@ruckus.brouhaha.com> "dhr" writes: > Is there a 'K&R" type of Python book? The book that you'd better have on > your shelf if you are going into Python? I don't think so, at least not if you are starting Python with experience in other languages. There are some books that are useful but none are really crucial. It's enough to just read the online documentation, which will let you transfer your experience onto Python, and then hang out here on clpy to soak up Python culture. If you're less experienced in programming but not a complete beginner, Dive Into Python looks pretty good and Python in a Nutshell also is supposed to be excellent. If you're a complete beginner, I'm not sure what to suggest. From jeff at jmcneil.net Wed Aug 15 09:06:10 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 15 Aug 2007 09:06:10 -0400 Subject: PyCon 2008 - Call for Tutorial Ideas In-Reply-To: References: Message-ID: <82d28c40708150606s1a5d06c4n29d0785df22344c2@mail.gmail.com> Now, I'm not sure if this has been covered in great detail anywhere, but I'd love to see something touching on interoperability with .Net web services. I've had a lot of success getting Python moved into our organization, but this is where it gets difficult. While I'm product focused, our business focused groups rely very heavily on .Net, WS-*, WCF, and SOAP. It's one thing to get ZSI working with simple SOAP calls, it's quite another to tie into a large-scale .Net based system. I've managed to get it working where I need to, but if I've found it difficult, I'm sure others have as well. Just an idea! Jeff On 8/15/07, Greg Lindstrom wrote: > It's hard to believe, but the planning for PyCon 2008 is underway. PyCon, > an annual gathering of Python enthusiasts -- nearly 600 in Dallas last year > -- will be held in Chicago next March 14-16, with one full "pre-conference" > day, March 13, set aside for tutorials; classes given by Python honchos on > various topics. These sessions last 3 hours (plus a break) and in general > are more detailed than the talks given during the actual conference. Right > now, we need to know what YOU want to see covered in these sessions. > Testing, GUI, web-apps, database, basic Python, advanced Python, objects, > anything and everything Python is on the table at this point. We have to > narrow the field down to 10 or 15 and then find qualified presenters, so now > is the time to start gathering ideas. > > What tutorials would you like to see offered? Please response to: > pycon-tutorials at python.org > > Thanks, > > Greg Lindstrom > Tutorial Coordinator, PyCon 2008 > -- > http://mail.python.org/mailman/listinfo/python-list > From tazmaster at rocketmail.com Tue Aug 7 07:28:22 2007 From: tazmaster at rocketmail.com (Jim Langston) Date: Tue, 7 Aug 2007 04:28:22 -0700 Subject: How to use C enum in Python CTypes? References: <1186462639.872254.25660@z24g2000prh.googlegroups.com> <5hqgogF3ldifeU1@mid.uni-berlin.de> <1186478018.409193.188130@e9g2000prf.googlegroups.com> Message-ID: "rozniy" wrote in message news:1186478018.409193.188130 at e9g2000prf.googlegroups.com... > On Aug 7, 2:11 pm, Marc 'BlackJack' Rintsch wrote: >> On Tue, 07 Aug 2007 04:57:19 +0000, rozniy wrote: >> > typedef enum olss_tag >> > { >> > OLSS_AD, >> > OLSS_DA, >> > OLSS_DIN, >> > OLSS_DOUT, >> > OLSS_SRL, >> > OLSS_CT >> > } >> > OLSS; >> >> > I managed to fudge the HDEV, UINT and PHDASS types as CTypes c_long(), >> > but I am not sure how translate a C enum into Python... >> >> > This site >> >http://python.net/crew/theller/ctypes/tutorial.html#bugs-todo-and-non... >> >> > says that enumeration types is not implemented, >> > "Enumeration types are not implemented. You can do it easily yourself, >> > using c_int as the base class." >> >> I would just define constants: >> >> (OLSS_AD, >> OLSS_DA, >> OLSS_DIN, >> OLSS_DOUT, >> OLSS_SRL, >> OLSS_CT) = map(ctypes.c_int, xrange(6)) >> >> Ciao, >> Marc 'BlackJack' Rintsch- Hide quoted text - >> >> - Show quoted text - > > > Wouldn't that assign integer values 0 to 5 to the things? I don't know > if it'll give me the correct results. Yes, that's how C's and C++'s enums work, unless an override is given (which I know you can do in C++ for sure). Otherwise, they are just numbers starting at 0. The size of the intergers (byte, 2 bytes, 4 bytes, etc..) is implemenation defined I believe, but an int normally works. From ptmcg at austin.rr.com Fri Aug 31 23:40:22 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 31 Aug 2007 20:40:22 -0700 Subject: HowTo Use Cython on a Windows XP Box? In-Reply-To: References: Message-ID: <1188618022.208258.15620@22g2000hsm.googlegroups.com> On Aug 31, 9:06 pm, David Lees wrote: > August 31, 2007 > > I just downloaded the current Cython release and have no problem running > the cpython.py translator on the demo code. But when I try compiling, I > get an error complaining that my version of Python (which is the current > 2.5.1 downloaded from python.org) was compiled with Visual C++ 2003. I > only have Visual C++ 2005 on my machine and am unable to find a download > of 2003 on the Microsoft site (no big surprise). I have never built > Python from source. Is it necessary or can someone suggest an alternative? > > TIA > > david lees Unless you are customizing Python (and you can accomplish a *lot* without doing so), it is not necessary to build Python from source. Download one of the pre-built Windows binaries and install it, or get the Win Python distribution from ActiveState and install that. Then start writing your own Python demo scripts. -- Paul From deets at nospam.web.de Mon Aug 6 09:26:49 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 06 Aug 2007 15:26:49 +0200 Subject: Scope question References: Message-ID: <5holspF3luclfU1@mid.uni-berlin.de> Nitro wrote: > Hello, > > today I wrote this piece of code and I am wondering why it does not work > the way I expect it to work. Here's the code: > > y = 0 > def func(): > y += 3 > func() > > This gives an > > UnboundLocalError: local variable 'y' referenced before assignment > > If I change the function like this: > > y = 0 > def func(): > print y > func() > > then no error is thrown and python apparently knows about 'y'. > > I don't understand why the error is thrown in the first place. Can > somebody explain the rule which is causing the error to me? The reason is that python's scoping rules have to somehow determine if a variable is local to a function or part of the surrounding context. Because python lacks variable declarations, what is does to infer the scope of a variable is to check if it is part of the left-side of an assignment. So in the first case, y is considered a func-local variable - which of course you didn't initialize. This behavior has been subject of quite a few critical discussions - yet you have to live with it. diez From deets at nospam.web.de Sun Aug 19 14:35:44 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 19 Aug 2007 20:35:44 +0200 Subject: ctypes and unsigned char* In-Reply-To: <1187545486.797017.308720@a39g2000hsc.googlegroups.com> References: <1187545486.797017.308720@a39g2000hsc.googlegroups.com> Message-ID: <5irgsbF3oi5dpU1@mid.uni-berlin.de> oliver.andrich at gmail.com schrieb: > Hi, > > can anybody with ctypes experience tell me, how to handle a C function > that returns an unsigned char*? Obviously it is not a restype of > c_char_p. From the docs: c_ubyte Represents the C unsigned char datatype, it interprets the value as small integer. The constructor accepts an optional integer initializer; no overflow checking is done. Diez From steve at holdenweb.com Thu Aug 9 18:10:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 09 Aug 2007 18:10:43 -0400 Subject: Puzzled by "is" In-Reply-To: <46BB7E08.4070809@wp.pl> References: <20070809194105.39BD11E400A@bag.python.org> <46BB7E08.4070809@wp.pl> Message-ID: Grzegorz S?odkowicz wrote: >> Why? Because. >> >> Seriously, it's just an optimization by the implementers. There is no >> need for more than one empty tuple, since tuples can never be modified >> once created. >> >> But they decided not to create (1, ) in advance. They probably knew that >> hardly anybody would want to create that tuple ;-) [Seriously: if you >> started trying to predict which tuples would be used you would go >> insane, but the empty tuple is the most likely candidate]. >> > That's just theorisation but I'd rather expect the interpreter simply > not to create a second tuple while there already is an identical one. > This could save some memory if the tuple was large (Although by the same > token comparison of large tuples can be expensive). Admittedly the empty > tuple is a special case but then 'Special cases aren't special enough to > break the rules'. > > A bit odd. > It's a trade-off, preferring to optimize time rather than memory usage. If tuples were "interned" like some strings then tuple creation would be more expensive due to the need to search the cache when creating them which, as you rightly point out, could be very expensive for large tuples. The integers under 100 are also, IIRC, special-cased: >>> x = 12 >>> y = 32676 >>> x is 12 True >>> y is 32676 False >>> I guess if you *make* the rules you can decide when it's reasonable to break them! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bert.heymans at gmail.com Mon Aug 20 17:59:47 2007 From: bert.heymans at gmail.com (Bert Heymans) Date: Mon, 20 Aug 2007 21:59:47 -0000 Subject: Any advice on ways for sharing a small Python application with the world? Message-ID: <1187647187.137812.158130@22g2000hsm.googlegroups.com> Hi, I made a Python cli application for resizing batches of images based on the PIL. You can find it here http://heymans.org/pyresize.html It's just an straight forward command line interface application but I guess many people would find a use for it, it can be used as a module as well. There's lots of comments in the code and a chunk of documentation. This post is a way to get the word out, I blogged about it (http:// blog.heymans.org) and submitted it to the Vaults of Parnassus (http:// py.vaults.ca/) does anyone know of other ways to share something that might just be too small for a sourceforge project but too big to be a snippet? Thanks! Cheers Bert Heymans From nih at nih.nildram.co.uk Mon Aug 20 07:15:51 2007 From: nih at nih.nildram.co.uk (nih) Date: Mon, 20 Aug 2007 12:15:51 +0100 Subject: building exe from script References: <1187602337.366419.92930@r29g2000hsg.googlegroups.com> Message-ID: A bit more information is clearly needed... 1. Create a file called py2exeSetup.py with the following contents: from distutils.core import setup import py2exe def compile(appName, console=False): OPTIONS = {"py2exe": {"compressed": 1, "optimize": 0, "bundle_files": 1, } } ZIPFILE = None if console: setup( options=OPTIONS, zipfile=ZIPFILE, console=[appName] ) else: setup( options=OPTIONS, zipfile=ZIPFILE, windows=[appName] ) 2. Create another file called setup.py with the following contents import py2exeSetup # to stop a wxPython program from loading a console window you just need to change the # file extension from .py to .pyw # change Filename to your XXXApp.pyw filename # change to py2exeSetup.compile('Filename.pyw', console=True) to show the console py2exeSetup.compile('Filename.pyw') 3. Create a file called Compile.bat with the following contents REM change Filename to your XXXApp.exe filename REM make sure that python is in your system path python setup.py py2exe copy dist\Filename.exe Filename.exe if errorlevel 1 pause 4. Put all these files in the same place as the program you want to convert to exe and run Compile.bat an *.exe file will now be in the same folder as your python files :) I have py2exeSetup.py in a separate 'Shared' folder so there is only one copy of it, so all my programs only have setup.py and compile.bat in them btw if you have a load of programs that you want to compile in one go the add a file CompileAll.bat in the root folder that all the programs are in, with the following contents: cd "ProgramOne" call py2exe.bat cd.. cd "ProgramTwo" call py2exe.bat cd.. # REM this part will execute if all programs compiled & copied ok echo all copied ok! pause I know hardly anything about ms-dos, but this works ok:/ gl! wrote in message news:1187602337.366419.92930 at r29g2000hsg.googlegroups.com... > Hello, > > Is there any solution for building exe file from python script > something like bbfreeze.When user write some script in > my program, it must compile script into exe without opening console > ( cmd ).I'am working on Windows XP SP2 and Python 2.5. > > > > Regards, > Vedran > From joejacob21 at gmail.com Mon Aug 13 07:16:48 2007 From: joejacob21 at gmail.com (joe jacob) Date: Mon, 13 Aug 2007 11:16:48 -0000 Subject: Configuring apache to execute python scripts using mod_python handler Message-ID: <1187003808.725705.56070@q3g2000prf.googlegroups.com> I configured apache to execute python scripts using mod_python handler. I followed below mentioned steps to configure apache. 1. In http.conf I added AddHandler mod_python .py PythonHandler mptest PythonDebug On 2. Then I added the line "LoadModule python_module modules/ mod_python.so" to http.conf. Then I tried execute the python script mentioned below from browser. from mod_python import apache def handler(req): req.content_type = 'text/plain' req.write("Hello World!") return apache.OK Then I am getting the following error Traceback (most recent call last): File "D:\softwares\Python25\Lib\site-packages\mod_python \importer.py", line 1537, in HandlerDispatch default=default_handler, arg=req, silent=hlist.silent) File "D:\softwares\Python25\Lib\site-packages\mod_python \importer.py", line 1202, in _process_target module = import_module(module_name, path=path) File "D:\softwares\Python25\Lib\site-packages\mod_python \importer.py", line 304, in import_module return __import__(module_name, {}, {}, ['*']) ImportError: No module named mptest I am using Apache 2.2.4, python 2.5 and mod_python-3.3.1.win32-py2.5- Apache2.2. I am able to execute python scripts by configuring apache to execute the cgi scripts. But I want to execute it using mod_python as it is faster compared to cgi mode. Someone please help me on this issue. From zyzhu2000 at gmail.com Wed Aug 1 13:59:30 2007 From: zyzhu2000 at gmail.com (beginner) Date: Wed, 01 Aug 2007 17:59:30 -0000 Subject: Assertion in list comprehension In-Reply-To: References: <1185982643.001546.138180@e16g2000pri.googlegroups.com> <1185988597.055293.106540@q3g2000prf.googlegroups.com> Message-ID: <1185991170.993822.175970@z24g2000prh.googlegroups.com> On Aug 1, 12:35 pm, "Chris Mellon" wrote: > On 8/1/07, beginner wrote: > > > > > > > On Aug 1, 11:28 am, "Chris Mellon" wrote: > > > On 8/1/07, beginner wrote: > > > > > Hi, > > > > > Does anyone know how to put an assertion in list comprehension? I have > > > > the following list comprehension, but I want to use an assertion to > > > > check the contents of rec_stdl. I ended up using another loop which > > > > essentially duplicates the functions of list comprehension. It just > > > > look like a waste of coding and computer time to me. > > > > > I just wish I could put the assertions into list comprehensions. > > > > > x=[(rec_stdl[0].st/10000.0, > > > > rec_stdl[0].cl, > > > > rec_stdl[0].bb, > > > > rec_stdl[0].bo, > > > > rec_stdl[1].bb, > > > > rec_stdl[1].bo, > > > > rec_stdl[0].ex > > > > ) > > > > for rec_stdl in rec_by_ex if len(rec_stdl)==2 > > > > ] > > > > > #duplicated loop > > > > if __debug__: > > > > for rec_stdl in rec_by_ex: > > > > l=len(rec_stdl) > > > > assert(l<=2 and l>0) > > > > if l==2: > > > > assert(rec_stdl[0].c=="C" and rec_stdl[1].c=="P") > > > > assert(rec_stdl[0].ex==rec_stdl[1].ex) > > > > assert(rec_stdl[0].st==rec_stdl[1].st) > > > > assert(rec_stdl[0].cp==rec_stdl[1].cp) > > > > First: All your asserts are wrong. Assert is a statement, not a > > > function. These specific ones will behave as expected, but it's easy > > > to accidentally write ones that always pass this way. > > > Do you mean I should not use the parentheses? > > Yes. > > > > > > Secondly: This is a waste of code, because if __debug__ is not defined > > > asserts will be skipped by the compiler. You could use the same loop > > > block for both branches. > > > I know. My original question was how. Dan suggested to write a checker > > function. > > Use the second block in all cases. In any situation where "if > __debug__" is False, the asserts are a noop and in fact won't even be > present in the bytecode. > > > > > > > > Thirdly: This sort of testing is precisely what unit tests and/or > > > doctests are for. > > > Agreed. > > > -- > >http://mail.python.org/mailman/listinfo/python-list- Hide quoted text - > > - Show quoted text -- Hide quoted text - > > - Show quoted text - I see. In fact I want to whole block surrounded by __debug__ to be optimized away in non-debug runs. If the logic of my program is correct, the asserts are guaranteed to be true, no matter what the input is. It is not input checking. From zyzhu2000 at gmail.com Sun Aug 19 12:35:42 2007 From: zyzhu2000 at gmail.com (beginner) Date: Sun, 19 Aug 2007 16:35:42 -0000 Subject: How to make a module function visible only inside the module? In-Reply-To: <5iqsbtF3qanv6U3@mid.individual.net> References: <1187484334.091530.90420@m37g2000prh.googlegroups.com> <1i32pg7.b0y3h92vjygwN%raims@dot.com> <1187488017.198905.242610@j4g2000prf.googlegroups.com> <5iqsbtF3qanv6U3@mid.individual.net> Message-ID: <1187541342.251682.307350@i13g2000prf.googlegroups.com> On Aug 19, 7:45 am, Bjoern Schliessmann wrote: > beginner wrote: > > Thanks a lot. I was using two underscores, __module_method() as my > > static method convention, and then I had some problems calling > > them from inside class methods. > > *Please* do yourself and other people that sometime may have to read > your code a favor and write code at least loosely oriented to > PEP 8. > > BTW, Python has no "static methods" at module level. And I suppose > what you call "class methods" actually aren't. > > Regards, > > Bj?rn > > -- > BOFH excuse #183: > > filesystem not big enough for Jumbo Kernel Patch I just started learning the language. I wasn't aware of the PEP. From bdesth.quelquechose at free.quelquepart.fr Wed Aug 1 16:28:07 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 01 Aug 2007 22:28:07 +0200 Subject: Pythonic way for missing dict keys In-Reply-To: References: <1185041243.323915.161230@x40g2000prg.googlegroups.com> <87lkd0eprj.fsf@pobox.com> Message-ID: <46b0ed0b$0$2257$426a74cc@news.free.fr> Steven D'Aprano a ?crit : (snip) > Instead of doing: > > > if callable(function): function() > > you should do: > > try: > function() > except TypeError: > pass There are time where you may want to know if you have a callable without calling it... > That should work for most uses of callable(), but isn't quite the same. > (What if function() has side-effects, or is expensive, and you want to > determine if it is callable, but not actually call it _now_?) Indeed. The 'correct' replacement would be: if hasattr(obj, '__call__'): # it's a callable but I don't find it so Pythonic to have to check for a __magic__ method. >>Also, what is the replacement of reduce? I think I remember seeing >>somewhere that lists comprehension would be (but also remember the >>advise that reduce will be quicker). > > > No, a list comprehension isn't equivalent to reduce(). There is no > replacement for reduce(). > > Guido has essentially done the functional equivalent of deciding that > because he personally doesn't like for loops, they can and should be > written out as: > > counter = 0 > while counter < len(sequence): > item = sequence[counter] > do_something_with_item > counter += 1 > > because it is "easier to read" than a for loop. > > And yes, if you think my example is extreme because nobody would be that > stupid, that's the point: removing reduce() _is_ that stupid (and it is > not often I say that about a language design decision by Guido!). Python > can, and probably will, get away with it only because reducing an iterable > to a single value is an uncommon operation, and the most common uses of it > (summing a sequence, finding the minimum and maximum) already have > workable replacements. > > It's especially stupid because map() and filter(), both of which do have > simple, easy to understand, completely functional replacements, are going > to stay. reduce() doesn't, and it is going. That's nuts. InMyArms(TM) ! (Guido, if you read us...) From enleverlesX.XmcX at XmclaveauX.com Mon Aug 27 05:12:04 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Mon, 27 Aug 2007 11:12:04 +0200 Subject: SCF released to GPL References: Message-ID: <46d29a6c$0$27404$ba4acef3@news.orange.fr> Salut ! Le deuxi?me envoi aurait pu ?tre en fran?ais. Cela aurait ?vit? le doublon, tout en maintenant le message. @+ Michel Claveau From einarwh at notreal.com Thu Aug 23 15:48:56 2007 From: einarwh at notreal.com (=?ISO-8859-1?Q?=22Einar_W=2E_H=F8st=22?=) Date: Thu, 23 Aug 2007 21:48:56 +0200 Subject: Newbie: List file system roots Message-ID: Hi, How would you list the file system roots in Python? That is, I'm looking for a way to list all connected drives (C:, D: etc) on a Windows box, or all /root, /tmp etc on a *nix box. In Java, there's a built-in API function to do this, File.listRoots(), but I couldn't find any equivalents in the Python libraries. Kind regards, Einar From steve at holdenweb.com Sun Aug 12 17:11:44 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 12 Aug 2007 17:11:44 -0400 Subject: wxPython - drawing without paint event In-Reply-To: <1186951326.218981.17820@b79g2000hse.googlegroups.com> References: <1186710391.148396.113490@d30g2000prg.googlegroups.com> <1186738813.373909.96230@x35g2000prf.googlegroups.com> <1186796567.331348.42450@q3g2000prf.googlegroups.com> <5i5l0dF2lortaU1@mid.individual.net> <1186883988.585048.16590@m37g2000prh.googlegroups.com> <5i8befF3o5no1U1@mid.individual.net> <1186928595.014008.61950@b79g2000hse.googlegroups.com> <5i98bsF3nmbavU1@mid.individual.net> <1186951326.218981.17820@b79g2000hse.googlegroups.com> Message-ID: 7stud wrote: > On Aug 12, 2:20 pm, Bjoern Schliessmann mail-0306.20.chr0n... at spamgourmet.com> wrote: >> But any suggestions what's >> better for a beginner? The (incomplete) tutorial surely not. >> > > Another GUI toolkit. > > Well if all you have to offer is fatuous advice you would be helping people more by keeping quiet. wxPython is a more-than-adequate GUI toolkit, as has been proved in many successful projects. What other toolkits have you used, and to what effect, and on what size of program? I suspect you are not particularly well-qualified to be answering this question in the first place, although as always you are entitled to your opinion. It's just that you appear to have an inflated value of its worth. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From orsenthil at gmail.com Sat Aug 4 22:43:56 2007 From: orsenthil at gmail.com (Phoe6) Date: Sun, 05 Aug 2007 02:43:56 -0000 Subject: Comparing RFC1123 based Dates Message-ID: <1186281836.970400.103490@i13g2000prf.googlegroups.com> I would like to parse RFC 1123 date format and compare two dates. I find that datetime module does not specifically confirms to any RFC. Any suggestions as how I can handle the RFC 1123 date format using standard libraries before I go to re based parsing? Thanks, Senthil From seandavi at gmail.com Thu Aug 23 22:00:25 2007 From: seandavi at gmail.com (Sean Davis) Date: Fri, 24 Aug 2007 02:00:25 -0000 Subject: Making a file-like object for manipulating a large file Message-ID: <1187920825.457886.7880@q4g2000prc.googlegroups.com> This should be a relatively simple problem, but I haven't quite got the idea of how to go about it. I have a VERY large file that I would like to load a line at a time, do some manipulations on it, and then make it available to as a file-like object for use as input to a database module (psycopg2) that wants a file-like object (with read and readlines methods). I could write the manipulated file out to disk and then read it back in, but that seems wasteful. So, it seems like I need a buffer, a way to fill the buffer and a way to have read and readlines use the buffer. What I can't do is to load the ENTIRE file into a stringio object, as the file is much too large. Any suggestions? Thanks, Sean From kib2 at free.fr Wed Aug 29 04:47:12 2007 From: kib2 at free.fr (tool69) Date: Wed, 29 Aug 2007 10:47:12 +0200 Subject: encoding problems In-Reply-To: References: <46d5215b$0$411$426a74cc@news.free.fr> Message-ID: <46d53391$0$14536$426a74cc@news.free.fr> Lawrence D'Oliveiro a ?crit : > In message <46d5215b$0$411$426a74cc at news.free.fr>, tool69 wrote: > >> p2.content = """Ce poste poss?de des accents : ? ? ? ?""" > > My guess is this is being encoded as a Latin-1 string, but when you try to > output it it goes through the ASCII encoder, which doesn't understand the > accents. Try this: > > p2.content = u"""Ce poste poss?de des accents : ? ? ? ?""".encode("utf8") > Thanks for your answer Lawrence, but I always got the error. Any other idea ? From mtobis at gmail.com Sun Aug 19 10:43:50 2007 From: mtobis at gmail.com (Michael Tobis) Date: Sun, 19 Aug 2007 14:43:50 -0000 Subject: Newbie question In-Reply-To: References: Message-ID: <1187534630.279129.279930@d55g2000hsg.googlegroups.com> http://diveintopython.org/ mt From riteshsarraf at gmail.com Sat Aug 11 23:18:02 2007 From: riteshsarraf at gmail.com (Ritesh Raj Sarraf) Date: Sun, 12 Aug 2007 03:18:02 -0000 Subject: Module imports during object instantiation In-Reply-To: References: Message-ID: <1186888682.860619.258610@19g2000hsx.googlegroups.com> On Aug 11, 3:17 am, James Stroud wrote: > You do realize your import statement will only be called for nt and dos > systems don't you? > Yes. I would like to load a Windows Python Module (which is, say a specific implementation for Windows only) in such a condition where I find that the platform is Dos/NT. Loading it globally doesn't make sense because when from the same class an object is created on a non-windows platfom, it would be waste. It would either ImportError or else just load the module and never use it. As per my understanding __init__ is executed only once during object creation. For such situations (that I've explained above), I think __init__() is the correct place to put imports. Ritesh From rcdailey at gmail.com Wed Aug 1 13:12:41 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 1 Aug 2007 12:12:41 -0500 Subject: Checking object types Message-ID: <496954360708011012p20f2dd3cu74f0ff34deb5505f@mail.gmail.com> Hi, I'm currently interested in creating an __add__() operator for one of my classes. This class handles both integers and objects its own type, however I don't know how I can perform special add operations depending on which is passed in. Since I haven't seen any evidence of function overloading, I'm assuming I'll have to check the types of the variables passed in inside of my __add__() method. Take the two following examples: vector3(3,4,2) + 5 = vector3(8,9,7) vector3(3,2,1) + vector3(4,5,6) = vector3(7,7,7) Any tips? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ca.allen at gmail.com Fri Aug 3 17:27:04 2007 From: ca.allen at gmail.com (Chris Allen) Date: Fri, 03 Aug 2007 14:27:04 -0700 Subject: Global package variable, is it possible? In-Reply-To: <46b39748$0$17945$4fafbaef@reader1.news.tin.it> References: <1186160415.065108.139160@e9g2000prf.googlegroups.com> <46b36b31$0$10622$4fafbaef@reader2.news.tin.it> <46b39748$0$17945$4fafbaef@reader1.news.tin.it> Message-ID: <1186176424.683344.49370@m37g2000prh.googlegroups.com> > Only for knowing more about modules: is there a way to dinamically reload > an already imported module? > > bye > Fabio Yeah you can reload modules with the reload builtin function. From ttkk1024 at gmail.com Mon Aug 27 07:47:47 2007 From: ttkk1024 at gmail.com (smalltalk) Date: Mon, 27 Aug 2007 04:47:47 -0700 Subject: how setup a dll file as a module? In-Reply-To: <5jfo9jF3tdo90U1@mid.uni-berlin.de> References: <1188185095.421047.195770@q3g2000prf.googlegroups.com> <5jfo9jF3tdo90U1@mid.uni-berlin.de> Message-ID: <1188215267.468717.240310@i13g2000prf.googlegroups.com> On Aug 27, 6:45 pm, "Diez B. Roggisch" wrote: > smalltalk wrote: > > > in arcgis , arcgisscripting is a dll file > > there is a script as following: > > > import arcgisscripting > > gp = arcgisscripting.create() > > > why can the script run? > > how can we setup a dll file as a module? > > There can be python-extension that are essentially C-modules. You can write > them your own, or using various wrapper technologies. See > > http://docs.python.org/ext/ext.html > > for starters, and google > > SIP > boost::python > SWIG > PyRex > > for more information. > > Diez thank you very much From steve at holdenweb.com Wed Aug 22 00:28:46 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 22 Aug 2007 00:28:46 -0400 Subject: File Read Cache - How to purge? In-Reply-To: <87ir781afk.fsf@mulj.homelinux.net> References: <1187669203.698637.81990@i38g2000prf.googlegroups.com> <87veb9xb7y.fsf@mulj.homelinux.net> <87ir781afk.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: > Nick Craig-Wood writes: > >> If you are running linux > 2.6.18 then you can use >> /proc/sys/vm/drop_caches for exactly that purpose. >> >> http://www.linuxinsight.com/proc_sys_vm_drop_caches.html > > That URL claims that you need to run "sync" before dropping the cache, > and so do other resources. I wonder if that means that dropping the > cache is unsafe on a running system. Good grief. Just let the operating system do its job, for Pete's sake, and go find something else to obsess about. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From rcdailey at gmail.com Fri Aug 24 13:35:20 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 24 Aug 2007 12:35:20 -0500 Subject: optparse - required options In-Reply-To: References: <496954360708201251r137dfaedqe632361891eae343@mail.gmail.com> <46C9F7D1.9040506@jayloden.com> <496954360708201353v19ea266cr50f144d1d71d5912@mail.gmail.com> <46CA0814.6050200@jayloden.com> Message-ID: <496954360708241035r3956c106l169e58aa16847695@mail.gmail.com> Thank you VERY much for mentioning argparse- this is EXACTLY what I needed! Thank you! On 8/23/07, Steven Bethard wrote: > > Omari Norman wrote: > > On Mon, Aug 20, 2007 at 05:31:00PM -0400, Jay Loden wrote: > >> Robert Dailey wrote: > >>> Well, I don't know what is wrong with people then. I don't see how > >>> required arguments are of bad design. > > > >> I tend to agree...while "required option" may be an oxymoron in > >> English, I can think of quite a few scripts I've written myself (in > >> various languages) that needed at least some kind of user input to > >> operate. > > > > The idea with optparse is not that programs should not require certain > > information on the command line; rather, the idea is that this > > information should be positional arguments, not 'options'. > > > > That is, to use the compiler example: > > > > compiler file > > > > is preferred if a file argument is necessary. > > > > compiler --file file > > > > is not preferred. > > I agree with the optparse philosophy, but Practicality Beats Purity. > That's why I was convinced to add "required options" to argparse -- > there are too many applications that want that kind of interface. > *I* don't write applications with interfaces like that, but enough > people do that the use case should really be supported. > > STeVe > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick at craig-wood.com Tue Aug 21 12:30:08 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 21 Aug 2007 11:30:08 -0500 Subject: File Read Cache - How to purge? References: <1187669203.698637.81990@i38g2000prf.googlegroups.com> <87veb9xb7y.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: > Signal writes: > > > 2. Is there anyway to somehow to take advantage of this "caching" by > > initializing it without reading through the entire file first? > > > > 3. If the answer to #2 is No, then is there a way to purge this > > "cache" in order to get a more accurate result in my routine? That > > is without having to read another large file first? > > On a Unix system the standard way to purge the cache is to unmount the > file system and remount it. If you are running linux > 2.6.18 then you can use /proc/sys/vm/drop_caches for exactly that purpose. http://www.linuxinsight.com/proc_sys_vm_drop_caches.html Eg # free total used free shared buffers cached Mem: 1036396 954404 81992 0 33536 347384 # echo 1 > /proc/sys/vm/drop_caches # free total used free shared buffers cached Mem: 1036396 658604 377792 0 348 91240 # echo 2 > /proc/sys/vm/drop_caches # free total used free shared buffers cached Mem: 1036396 587296 449100 0 392 91284 # echo 3 > /proc/sys/vm/drop_caches # free total used free shared buffers cached Mem: 1036396 588228 448168 0 692 91808 -- Nick Craig-Wood -- http://www.craig-wood.com/nick From kyosohma at gmail.com Wed Aug 29 14:56:41 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 29 Aug 2007 11:56:41 -0700 Subject: copying files In-Reply-To: References: <93066C069973ED448DC2BCEA9C44A7383BE30C@efmailx> Message-ID: <1188413801.904992.292690@w3g2000hsg.googlegroups.com> On Aug 29, 1:51 pm, Ricardo Ar?oz wrote: > Brian McCann wrote: > > Hi, > > > with the code below I set a variable TEST_HOME to a path and the > > variable m to a path > > in my current dir. > > I have a symbolic link setting m---->lib > > when I run the script I get no errors and the lib dir with its 20 files > > does not get copied to /v01/test_home > > any help would be greatly appreciated > > > --Brian > > > #!/usr/bin/python > > import string > > import os > > import sys > > import errno > > import shutil > > import tarfile > > > TEST_HOME = "/v01/test_home" > > m = "./lib" > > os.system("cp -r m TEST_HOME") > > #os.system("tar -cvf viziant-ingestion.tar /v01/") > > Sorry, meant : os.system("cp -r " + m + " " + TEST_HOME) Did you try using the shutil module? Mike From stefan at 3niemann.de Tue Aug 28 18:00:49 2007 From: stefan at 3niemann.de (Stefan Niemann) Date: Wed, 29 Aug 2007 00:00:49 +0200 Subject: Haskell like (c:cs) syntax Message-ID: Hi, sorry that I'm relatively new to Python. But the syntax and semantics of Python already fascinate me, because I'm familiar with functional languages like Haskell. Is there a pattern matching construct in Python like (head : tail), meaning 'head' matches the first element of a list and 'tail' matches the rest? I could not find this in the Python documentation. Regards, Stefan From sickcodemonkey at gmail.com Fri Aug 24 16:06:14 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Fri, 24 Aug 2007 16:06:14 -0400 Subject: POP3 - Saving an image attachment only. Message-ID: <2adc542f0708241306l7105c80kbbdc26ad3ea4c8f1@mail.gmail.com> I wrote some code below (Code1 block) which will read a pop3 email account and will open each email in the inbox. What I want my code to do is only pull the attachment; as you see below I basically output everything. Is there an easy way to just pull attachments? (NOTE, the only attachements that I want to pull are images) =========================================================== I also tried this, but for some reason the part.get_filename Always equal "None" msg = email.message_from_string(mstring) for part in msg.walk(): fn = part.get_filename() if fn <>None: filenames.append(fn) attachedcontents.append(part.get_payload()) print "im here" *..::CODE1:.. ===========================================================* for email in items: id, size = string.split(email) resp, text, octets = server.retr(id) text = string.join(text, "\n") file = StringIO.StringIO(text) message = rfc822.Message(file) print message.fp.read() *..::OUTPUT1::.. ===========================================================* --__CONTENT_64564_PART_BOUNDARY__33243242__ Content-Type: text/plain Content-Transfer-Encoding: quoted-printable X-MIME-Autoconverted: from 8bit to quoted-printable by njbrmotmta9.vzwpix.com id l7LIT1GZ008951 Some email text --__CONTENT_64564_PART_BOUNDARY__33243242__ Content-Type: image/jpeg; name="0815071408.jpg" Content-ID: <0815071408.jpg> Content-Location: 0815071408.jpg Content-Transfer-Encoding: base64 /9j/4AkjSkZYWAAQ/9j/2wCEABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdA SFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2MBERISGBUYLxoaL2NCOEJjY2NjY2NjY2Nj Y2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY//EAaIAAAEFAQEBAQEB AAAAAAAAAAABAgMEBQYHCAkKCxAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJx FDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZ WmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLD xMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6AQADAQEBAQEBAQEBAAAAAAAA AQIDBAUGBwgJCgsRAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGx wQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdo aWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJ ytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/AABEIAHgAoAMBIQACEQEDEQH/2gAMAwEA AhEDEQA/AMead5GxnJ9KjaPYuTy1YtnQlYqk7ZM1dgl3Lg1b2MzZ02TMZX0qvr97cR2AtIjt idsvjq1EZWkRKPMZ2j2U9xcIqxts/i4rv7SwW2gVFGB1NKb1HcfNEGXBFZstlDz8xBqAM+8Q QoTnIrmtQuQcgGriJk3hqXF1IPUV10T5FWySXNJmkA1z8prjPEHf/eo6jRhir9r0q2NGnDG XqNc5frnPrULMMk/NgdqkMoTB+XjrzVO4uBgDlyfQUpWa2KS7H//2Q== --__CONTENT_64564_PART_BOUNDARY__33243242__-- -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Fri Aug 31 09:58:51 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 31 Aug 2007 13:58:51 GMT Subject: reload(sys) References: <1188521143.421431.119100@l22g2000prc.googlegroups.com> <1188564816.430863.219560@w3g2000hsg.googlegroups.com> Message-ID: <5jql4rFh543U4@mid.uni-berlin.de> On Fri, 31 Aug 2007 12:53:36 +0000, S?nmez Kartal wrote: > On 31 A ustos, 04:24, Steven Bethard wrote: >> Snmez Kartal wrote: >> > I've had an encoding issue and solved it by >> > "sys.setdefaultencoding('utf-8')"... >> >> > My first try wasn't successful since setdefaultencoding is not named >> > when I imported sys module. After, I import sys module, I needed to >> > write "reload(sys)" also. >> >> > I wonder why we need to call "reload(sys)" to get setdefaultencoding >> > named? >> >> sys.setdefaultencoding is purposely deleted from the sys module after >> it's loaded because you really shouldn't be using it. The reload() call >> restores the deleted attribute. >> >> If you'd like a less brittle solution to your encoding issue, explain >> what the issue was, and people here can probably help you find a better >> solution. > > I was using the XMLBuilder(xmlbuilder.py). I'm writing XML files as > "f.write(str(xml))". At execution of that line, it gives error with > description, configure your default encoding... This doesn't help us that much. What is `f` here and what is `xml`? > This is the part of xmlbuilder.py which raises the error. > > try: > if self.pretty: > # tabs are evil, so we will use two spaces > outstr = self._dom.toprettyxml(" > ",encoding=self.encoding) > else: > outstr = self._dom.toxml(encoding=self.encoding) > except UnicodeDecodeError: > sys.stderr.write('Decoding Error: You must configure > default encoding\n') > sys.exit() So there is an attribute `self.encoding` on that object. Is it set? What encoding is it? And do you put byte strings with values outside ASCII into your XML or unicode strings? Ciao, Marc 'BlackJack' Rintsch From duprez at hinet.net.au Mon Aug 27 20:20:57 2007 From: duprez at hinet.net.au (Mick Duprez) Date: Mon, 27 Aug 2007 17:20:57 -0700 Subject: Error with Simplemapi.py In-Reply-To: References: <1187938985.165186.300780@i38g2000prf.googlegroups.com> <1188194730.024877.120880@q5g2000prf.googlegroups.com> Message-ID: <1188260457.269412.13350@q3g2000prf.googlegroups.com> On Aug 27, 4:46 pm, "Gabriel Genellina" wrote: > En Mon, 27 Aug 2007 03:05:30 -0300, Mick Duprez > escribi?: > > > Thank you very much Gabriel, changing the NULL to None did the trick > > (it also helps if I reload the changed module after editing!:( ). > > Glad to see it worked. > > > Yes > > that is an old script and I will look into your suggestions. Basically > > I'd just like to use the default mail client (windows or Unix/Linux) > > to send simple mail with attachments, this way I can log the > > attachments I send to a db for example for document transmittal/ > > register reports etc. > > Hmmm... altough you may find some MAPI implementation for Linux, it's very > uncommon; consider using sendmail instead, or ask for an outbound SMTP > server and use the smtplib module. > > -- > Gabriel Genellina Will do, thanks for your time, Mick. From johnmasters at oxtedonline.net Mon Aug 13 16:54:30 2007 From: johnmasters at oxtedonline.net (John K Masters) Date: Mon, 13 Aug 2007 21:54:30 +0100 Subject: negative polar axis In-Reply-To: References: <1186999666.642856.16820@19g2000hsx.googlegroups.com> Message-ID: <20070813205430.GA3865@spookie1.spookiegate> On 10:58 Mon 13 Aug , Erik Max Francis wrote: > Steve Holden wrote: > > > About the best interpretation I can think of is to add 180 degrees to > > the angle and reverse the sign of the magnitude, but this would be a > > hack. Where are those coordinates coming from? > > Well, sometimes in polar coordinates (r, theta), r is allowed to be > negative. The usual translation from polar to Cartesian coordinates > makes this meaningful, albeit weird, so in effect the resulting > positions are just reflections around the origin. > > Which I suppose is what the original poster was asking about, but it's > still not clear. > Many years ago when I started programming machine tools (on punched paper tape) if you wished to specify a cutter path around a radius as being more than 180 degrees you programmed it as a negative r value. There are 2 possible paths from x1y1 to x2y2 along a radius r and going in the same direction; that less than 180 deg and that more than 180 deg, unless the radius is exactly 180. But this was rarely used, the other method of specifying the end point as an incremental value in relation to the radius centre is less error prone when the arcs are close to 180. Sorry about the slight diversion but I'm getting nostalgic. Regards, John -- War is God's way of teaching Americans geography Ambrose Bierce (1842 - 1914) From musiccomposition at gmail.com Tue Aug 21 11:21:51 2007 From: musiccomposition at gmail.com (Benjamin) Date: Tue, 21 Aug 2007 15:21:51 -0000 Subject: IDE for Python In-Reply-To: References: Message-ID: <1187709711.175483.86780@x35g2000prf.googlegroups.com> On Aug 21, 5:00 am, Joel Andres Granados wrote: > Hello list: > > I have tried various times to use an IDE for python put have always been > disapointed. > I haven't revisited the idea in about a year and was wondering what the > python people > use. > I have also foundhttp://pida.co.uk/mainas a possible solution. Anyone > tried it yet? > > suggestions. I like PyDev + Eclipse mostly because I develop Java, PHP, and C/C++, so I like having a consistent interface between the languages. Besides, the Eclipse updater makes updating and installing new features really easy. > Regards > Joel Andres Granados > > joel.granados.vcf > 1KDownload From hancock.robert at gmail.com Tue Aug 14 08:24:11 2007 From: hancock.robert at gmail.com (milan_sanremo) Date: Tue, 14 Aug 2007 12:24:11 -0000 Subject: chmod g+ Equivalent In-Reply-To: References: <1187042290.821786.178420@19g2000hsx.googlegroups.com> Message-ID: <1187094251.540591.308320@g4g2000hsf.googlegroups.com> On Aug 13, 8:06 pm, Steve Holden wrote: > milan_sanremo wrote: > > I've read the documentation on os.chmod() and can implement all the > > standard commands, but what is the syntax for the equivalent of chmod g > > + to set the group id? > > I assume when you say "to set the group id" you actually mean "to assert > the setgid bit"? I further presume that when you say "chmod g+" you > actually mean "chmod g+s". The g+s was an omission on my part. I can see how it would confuse the issue. I'm not sure if I mean "to assert the setgid bit". My SUN docs refer to it being 'on'. http://docs.sun.com/app/docs/doc/819-3321/6n5i4b767?l=en&a=view&q=setgid+bit > > You can't have read the documentation very thoroughly. It says right at > the top: > > S_ISUID > S_ISGID I did see this in the documentation: Change the mode of path to the numeric mode. mode may take one of the following values (as defined in the stat module) or bitwise or-ed combinations of them: * S_ISUID * S_ISGID Which refers to: http://docs.python.org/lib/module-stat.html After which it was still unclear. My question is in the command os.chmod(myDirectory, ?) what is the value for ? to turn on the setgid bit. Contrary to your presumption, I did read the documentation thoroughly. It is inability to understand the concept which prompted me to post the question here. > > Of course, your process needs to have root privilege in order to be able > to do that. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- From bignose+hates-spam at benfinney.id.au Wed Aug 1 04:33:11 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 01 Aug 2007 18:33:11 +1000 Subject: Python end of file marker similar to perl's __END__ References: <1185940391.135261.130950@i38g2000prf.googlegroups.com> Message-ID: <87ir7zd588.fsf@benfinney.id.au> beginner writes: > In perl, I can write __END__ in a file and the perl interpreter will > ignore everything below that line. IIRC, this Perl feature is specifically intended to work with its feature of reading data from the same file, as all the lines following that marker. > This is very handy when testing my program. If my understanding above is correct, then your use of it is a happy repurposing of the feature, and not an intended use. > Does python have something similar? Since it doesn't have the behaviour that inspired that feature in Perl, I doubt it. -- \ "Everything is futile." -- Marvin of Borg | `\ | _o__) | Ben Finney From S.Mientki-nospam at mailbox.kun.nl Mon Aug 6 13:51:26 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 06 Aug 2007 19:51:26 +0200 Subject: is it possible to improve traceback messages ? Message-ID: <46B75F9E.5020309@mailbox.kun.nl> hello, Most of time I get an error message, it is sufficient to solve to problem. Sometimes it's not clear to me what the problem is like this one: N = int (log10(self.Value)) + 1 TypeError: int() argument must be a string or a number In order to solve it, in general I put some print statements, before the line with the problem, printing values and types of all variables. I think it would be much more convenient, if the traceback or error exception ( don't know how it works exactly), would print the type and value of all variables and constants used in the last line. Can this be done (in a easy way). thanks, Stef Mientki From dstromberg at datallegro.com Wed Aug 29 19:17:35 2007 From: dstromberg at datallegro.com (Dan Stromberg - Datallegro) Date: Wed, 29 Aug 2007 23:17:35 GMT Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> Message-ID: On Tue, 28 Aug 2007 23:45:28 -0700, Russ wrote: > On Aug 28, 10:58 pm, Michele Simionato > wrote: > >> Why do you think that would ad a strong positive capability? >> To me at least it seems a big fat lot of over-engineering, not >> needed in 99% of programs. In the remaining 1%, it would still not >> be needed since Python provides out of the box very powerful >> metaprogramming capabilities so that you can implement >> yourself the checks you need, if you really need them. > > I get the strong impression you don't really understand what > programming by contract is. > > I have not yet personally used it, but I am interested in anything > that can help to make my programs more reliable. If you are > programming something that doesn't really need to be correct, than you > probably don't need it. But if you really need (or want) your software > to be correct and reliable as possible, I think you you should be > interested in it. You might want to read this: > > http://archive.eiffel.com/doc/manuals/technology/contract/ariane/page.html I agree with Chris - there's no need to be condescending. However, I agree with you that this is a valuable addition to a language. It's not that Eiffel, by having preconditions and postconditions, is doing anything that cannot be done in python already. It's more that by making these things a formal part of the language, or at least a module that facilitates them, one gives a sort of stamp of approval to adding a ton of assertions about how your code is supposed to work /when/working/in/that/language, which makes debugging a relative snap. Isn't that something people should want for python? Sturdy code and easy debugging? I've been trying to write my python code with tons of "unnecessary" if statements that check out my assumptions, and I'm finding more or less what the Eiffel people claim: I'm investing a little bit of upfront time, and getting a huge payoff in the backend as my code starts to debug itself. But I likely never would've started taking my error checking to such extremes if I hadn't been curious about Eiffel for a while. Throwing in tons of error and assumption checking mostly eliminates silly tracing from procedure to function to procedure to function, trying to find the ultimate root cause of a problem. Usually, the root cause is identified in an error on stderr or similar. Keep in mind that debugging usually takes far longer than the initial coding. Programming by contract seems to balance that out, relatively speaking. Granted, we could just say "You should check for these things anyway", or "You should know what you're doing", but... Isn't that kind of what assembler programmers used to say to Lisp, FORTRAN and COBOL programmers? And what about the case where you've written a piece of code, and someone else has written another, and the two pieces of code need to interact? Odds are pretty good that if this code has much substance, there'll be opportunity for subtly different assumptions about what should be happening in each (yes, "well abstracted" code will be misassumption-resistant, but even the best OOP programmers will run afoul of this /sometimes/). Perhaps both these programmers "Know what they're doing", but they don't necessarily know what the other is doing! IMO, putting Programming by Contract into python as part of the language itself, or as a simple module, is a little bit like a company or department coming up with a mission statement. It's easy to say that it's meaningless, and some will ignore it, but it still kind of sets the tone for how things "should be done". From has.temp3 at virgin.net Sun Aug 5 05:31:45 2007 From: has.temp3 at virgin.net (has) Date: Sun, 05 Aug 2007 02:31:45 -0700 Subject: xlrd question In-Reply-To: References: Message-ID: <1186306305.693234.266390@w3g2000hsg.googlegroups.com> On Aug 4, 1:48 am, JYOUN... at kc.rr.com wrote: > I ran your code which gave me this: > > >>> import sys, xlrd; print sys.version; print xlrd.__file__ > > 2.3.5 (#1, Jan 30 2006, 13:30:29) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1819)] > /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site -packages/ > xlrd/__init__.pyc Note that: /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/ site-packages is actually just a symlink to: /Library/Python/2.3/site-packages While third-party modules do usually go in python2.x/site-packages, Apple don't like users messing about in /System so their stock Python installation keeps third-party modules under /Library instead. The exact location varies depending on OS version: on 10.3 it's / Library/Python/2.3; on 10.4 it's /Library/Python/2.3/site-packages. Modules installed via DistUtils/EasyInstall will be placed in the appropriate location automatically. For more information on installing DistUtils packages, see: http://docs.python.org/inst/inst.html > and as far as I can tell, the runxlrd.py file is located here (where I had drug this folder > originally): > > Macintosh HD/xlrd-0.6.1/scripts/runxlrd.py Nope, DistUtils will copy all modules to site-packages as part of the installation procedure. If you're a developer you'll probably want to keep the original distribution around as it'll contain documentation, examples, etc. which you'll want to refer to when writing your own scripts. End-users of your scripts won't need it though. ([OT] Tip: dumping user files under / is poor etiquette; that's what your home directory under /Users is for.) > While I'm talking about Excel, is there any other program (for Python) that can edit Excel files? You can script Excel directly from Python via appscript which talks to scriptable Mac apps via the same API as AppleScript: http://appscript.sourceforge.net I don't do any Excel scripting myself, but Matt Neuburg includes a nice example in this article on the Ruby version of appscript (which has a similar syntax): http://www.oreillynet.com/pub/a/mac/2007/02/27/replacing-applescript-with-ruby.html If you need more info just ask. HTH has -- http://appscript.sourceforge.net http://rb-appscript.rubyforge.org From bignose+hates-spam at benfinney.id.au Sat Aug 4 10:10:00 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 05 Aug 2007 00:10:00 +1000 Subject: Relative-importing * References: <1185559874.299008.167010@x40g2000prg.googlegroups.com> <871weth2gg.fsf@benfinney.id.au> <46ae3894$0$19609$426a34cc@news.free.fr> <1186200218.666444.254200@q3g2000prf.googlegroups.com> Message-ID: <87vebv9yrr.fsf@benfinney.id.au> rbygscrsepda at gmail.com writes: > Yes, I'm importing * for a reason, a good one, I think. Reading your description, I must say I don't see a good reason. > I have a set of modules (the number planned to reach about 400) that > would be dynamically loaded by my program as needed, and they're > somewhat similar to each other. I wish each of them to import * from > a certain "parent" module, so that they'll receive whatever > functions and variables I want all of them to share (using the > parent module's __all__), which may be overrided by the "child" > modules at their discretion. Sort of like class inheritance, but I'm > not doing that because implementing that would be a lot more tedious > and less elegant. It seems to me, based only on this description, that class inheritance would be far *more* elegant, and much easier to follow when reading the code. If all these functions and other objects are so closely-related that they form the core of some inheritance-like system, what's so inelegant about wrapping them in a class so that the inheritance is explicit in the module where it happens? -- \ "The only tyrant I accept in this world is the still voice | `\ within." -- Mahatma Gandhi | _o__) | Ben Finney From ldo at geek-central.gen.new_zealand Sun Aug 26 05:55:37 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 26 Aug 2007 21:55:37 +1200 Subject: Making a file-like object for manipulating a large file References: <1187920825.457886.7880@q4g2000prc.googlegroups.com> Message-ID: In message <1187920825.457886.7880 at q4g2000prc.googlegroups.com>, Sean Davis wrote: > I have a VERY large file that I would > like to load a line at a time, do some manipulations on it, and then > make it available to as a file-like object for use as input to a > database module (psycopg2) that wants a file-like object (with read > and readlines methods). I could write the manipulated file out to > disk and then read it back in, but that seems wasteful. If your consumer doesn't need to seek, how about having it read from a pipe? From frikker at gmail.com Wed Aug 15 11:11:40 2007 From: frikker at gmail.com (frikk) Date: Wed, 15 Aug 2007 08:11:40 -0700 Subject: Python, Sharepoint, .NET, NTLM Message-ID: <1187190700.127033.98060@19g2000hsx.googlegroups.com> Hey everyone, I need to authenticate with a Sharepoint server. It looks to be using 'NTLM' authentication. I've looked on the newsgroup and it looks like there has been talk of using python and NTLM but no definite solutions are apparent. Can anyone provide me with any kind of help on this issue? URLLIB2 keeps getting a 401 error when I try any kind of authentication. I am trying to use python here in my company (for obvious reasons - python is awesome!) and this is the first major project that would use it. Unfortunately if I cannot talk to Sharepoint (I am just trying to get a list of .xml files and data from a form library) I cannot use python. The other solution would be: Does anyone know how to get xml files from a sharepoint library in python? The worst case would be using another language to compile just the xml file downloader. This is not the optimal solution. Thank you, Blaine From zyzhu2000 at gmail.com Sat Aug 18 20:49:19 2007 From: zyzhu2000 at gmail.com (beginner) Date: Sun, 19 Aug 2007 00:49:19 -0000 Subject: "constructor" or initialization function for module Message-ID: <1187484559.935316.125050@j4g2000prf.googlegroups.com> Hi Everyone, An extended module (.pyd) written in C have an init function that is called when the module is imported. Does anyone know if there is a way to provide an init function for a module written in python? Thanks, Geoffrey From stef.mientki at gmail.com Tue Aug 14 08:39:26 2007 From: stef.mientki at gmail.com (stef mientki) Date: Tue, 14 Aug 2007 14:39:26 +0200 Subject: LEGB rule, totally confused ... Message-ID: <46C1A27E.1080206@gmail.com> hello, I've thought many times I finally understood the import / namespace rules, but again I'm totally lost :-( This is my library file # Module lib_test.py X = 1 def Init(): global X X = 3 print 'Init', X def Run (): print X <=== UnboundLocalError: local variable 'X' referenced before assignment X = X + 1 print ' Run', X And this my main program in another file: import lib_test lib_test.Init() print lib_test.X lib_test.Run() print lib_test.X Why do I get the error ? Printing isn't assigning anything or am I missing something. Now if I remove "X = X + 1" I don't get an error ??? Is this a problem of the traceback procedure or the IDE, or is Python not completely an interpreter, that reads line by line ??? Please explain this to me. thanks, Stef Mientki From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Aug 30 03:42:04 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 30 Aug 2007 09:42:04 +0200 Subject: list index() In-Reply-To: <1188456273.102334.48660@50g2000hsm.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> Message-ID: <46d674c2$0$417$426a34cc@news.free.fr> zzbbaadd at aol.com a ?crit : > What's with the index() function of lists throwing an exception on not > found? Let's hope this is rectified in Python 3. If nothing else, add > a function that doesn't throw an exception. There are a million > situations where you can have an item not be in a list and it is not > an exception situation. What's with using your brain instead of whining ? From gperumal at gmail.com Mon Aug 20 04:02:16 2007 From: gperumal at gmail.com (gperumal at gmail.com) Date: Mon, 20 Aug 2007 01:02:16 -0700 Subject: Where we need to use Python ? Message-ID: <1187596936.136499.200280@l22g2000prc.googlegroups.com> Hi Iam new to Python I know Perl, JScript,C,C++,Java But i want to know where excatly this python come in to picture And Is it a interpreted language or a programming language It comes in which category I very keen to know this please tell Regards Ganesh P From kyosohma at gmail.com Fri Aug 24 15:40:50 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 24 Aug 2007 12:40:50 -0700 Subject: How to replace a method in an instance. In-Reply-To: <46cf2ba2$0$30562$426a74cc@news.free.fr> References: <1187971953.261328.219000@q3g2000prf.googlegroups.com> <46cf2ba2$0$30562$426a74cc@news.free.fr> Message-ID: <1187984450.138147.62780@e9g2000prf.googlegroups.com> On Aug 22, 12:48 am, Bruno Desthuilliers wrote: > kyoso... at gmail.com a ?crit : > > > > > On Aug 24, 11:02 am, "Steven W. Orr" wrote: > > >>In the program below, I want this instance to end up calling repmeth > >>whenever inst.m1 is called. As it is now, I get this error: > > >>Hello from init > >>inst = <__main__.CC instance at 0x402105ec> > >>Traceback (most recent call last): > >> File "./foo9.py", line 17, in ? > >> inst.m1() > >>TypeError: repmeth() takes exactly 1 argument (0 given) > > >>#! /usr/bin/python > >>def repmeth( self ): > >> print "repmeth" > > >>class CC: > >> def __init__( self ): > >> self.m1 = repmeth > >> print 'Hello from init' > > >> def m1 ( self ): > >> print "m1" > > >>inst = CC() > >>inst.m1() > > >>TIA > > > Remove "self" from repmeth as it's not required in a function, only in > > functions that are defined within a class. > > Obviously wrong. 'self' (or whatever-you-name-it) as first arg is > mandatory for functions used as instance methods. The fact that a > function is defined outside a class doesn't mean it cannot be used as a > method... > > > Of course, a function in a > > class is also know as a method. > > Less obvious but still wrong !-) I wish the authors of the Python books would get a clue then. > > A function object, whereever (and however) it's defined, is a function > object, not a method objet. Now what happens is that functions defined > inside a class are wrapped in method (by default, instancemethod) objects. > > To be more accurate - and talking only about how it works for new-style > classes - function objects implements the descriptor protocol, so when a > function is a class attribute (which is what happens when the function > is defined in the class statement's body), and is looked up on an > instance, it returns an instancemethod object that has the instance and > the function as attributes. This instancemethod object is itself > callable, and when called returns the result of calling the function > with the instance as first argument. classmethods and staticmethods are > variants fo this scheme, calling the function with either the class as > first arg (for classmethods) or just as-is (for staticmethods). > > Now when you set a function as an *instance* (not class) attribute, the > descriptor protocol isn't invoked (it only works on class attributes), > so if you want to use the function as a method, you have to do the > wrapping by yourself (cf my other answer to the OP). > > HTH I'm not going to help with these class / instance / whatever any more and leave it to all you professionals. Yes, it you can use self in an outside method, but the way the OP asked the question and the nature of the traceback pointed to it just being a normal function, not a method since the OP wasn't passing an argument to the bugger. Oh well. Live and learn to unlearn what you learned. Mike From mcl.office at googlemail.com Sun Aug 19 04:50:15 2007 From: mcl.office at googlemail.com (mosscliffe) Date: Sun, 19 Aug 2007 01:50:15 -0700 Subject: 1)URL QueryString Parsing 2)Search Engine Spiders Message-ID: <1187513415.188232.187270@50g2000hsm.googlegroups.com> I am trying to create a back link, equivalent to the browser back action and I can not use java script. The target user does not allow java script. I am using HTTP_REFERER. I need to add the original Query String values. Is there a way to get the QueryString element other than by using cgi.FieldStorage, as I just want to return with the values that were current in the calling page. gv.orgQueryString = "" gv.BackButton = 'BACK' ---------------------------------------------------------------------------------------- Am I right in thinking Search Engine Spiders will never see my script pages as they exist only for the duration of the python script's execution ? And even then as they are xxx.py, they would not be seen. Thanks Richard From half.italian at gmail.com Mon Aug 27 20:19:09 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Mon, 27 Aug 2007 17:19:09 -0700 Subject: Socket - gaierror In-Reply-To: References: <1188242671.182072.130150@r23g2000prd.googlegroups.com> <1188244050.029920.314700@i13g2000prf.googlegroups.com> Message-ID: <1188260349.031088.69010@l22g2000prc.googlegroups.com> On Aug 27, 4:22 pm, s... at signature.invalid (Douglas Wells) wrote: > In article <1188244050.029920.314... at i13g2000prf.googlegroups.com>, > > > > half.ital... at gmail.com writes: > > On Aug 27, 12:32 pm, Larry Bates wrote: > > > Changing it to IP gives me the same exact error... > > > File "bin/prgram.py", line 123, in notify > > smtp = smtplib.SMTP("XXX.XXX.XXX.XXX") > > > File "/usr/lib/python2.4/smtplib.py", line 255, in __init__ > > addr = socket.gethostbyname(socket.gethostname()) > > > gaierror: (-2, 'Name or service not known') > > > Looks like the smtp port is closed on the client machine...doh Should > > have gotten to that! > > > ~Sean > > Note that the lookup is of your *local* system name > (socket.gethostname()). I suspect that the name of your client > system (the one running the python script) is not registered in > DNS. > > Try ping'ing your own system and see if that resolves in DNS. In > UNIX/Linux you can use the hostname command; in any system you can > write a python script to print the result of socket.gethostname(). > > - dmw > > -- > . Douglas Wells . Connection Technologies . > . Internet: -sp9804- -at - contek.com- . I found a solution...but still not sure why that happened. root at 00:17:08:5E:EF:0F:/usr/local/sw/program/bin# hostname 00:17:08:5E:EF:0F root at 00:17:08:5E:EF:0F:/usr/local/sw/program/bin# ping 00:17:08:5E:EF: 0F ping: unknown host 00:17:08:5E:EF:0F >>> socket.gethostname() '00:17:08:5E:EF:0F' Workaround: pass the 'local_hostname' arg to the smtplib.SMTP() call with "localhost" ie smtp.SMTP("some.computer", local_hostname="localhost") This is just overriding the socket.gethostname() call entirely. Did a bit of testing with the /etc/hosts file, and even with an entry to the hostname it can't resolve the ip. The problem is the name "00:17:08:5E:EF:0F" PS. I didn't choose to set the hostname that way. ~Sean From steve at holdenweb.com Fri Aug 17 01:40:35 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 17 Aug 2007 01:40:35 -0400 Subject: defaultdict of arbitrary depth In-Reply-To: <1187324831.082493.190970@w3g2000hsg.googlegroups.com> References: <1187321113.841198.195100@22g2000hsm.googlegroups.com> <1187324831.082493.190970@w3g2000hsg.googlegroups.com> Message-ID: Paul McGuire wrote: > On Aug 16, 11:19 pm, Carsten Haese wrote: >> On Thu, 2007-08-16 at 20:25 -0700, Paul McGuire wrote: >>> [...] >>> I've hacked out this recursivedefaultdict which is a >>> defaultdict(defaultdict(defaultdict(...))), arbitrarily deep depending >>> on the keys provided in the reference. >>> Please comment. >>> [...] >>> class recursivedefaultdict(object): >>> def __init__(self): >>> self.__dd = defaultdict(recursivedefaultdict) >>> def __getattr__(self,attr): >>> return self.__dd.__getattribute__(attr) >>> def __getitem__(self,*args): >>> return self.__dd.__getitem__(*args) >>> def __setitem__(self,*args): >>> return self.__dd.__setitem__(*args) >> This is shorter: >> >> from collections import defaultdict >> >> class recursivedefaultdict(defaultdict): >> def __init__(self): >> self.default_factory = type(self) >> >> -- >> Carsten Haesehttp://informixdb.sourceforge.net- Hide quoted text - >> >> - Show quoted text - > > Of course, very short and sweet! Any special reason you wrote: > self.default_factory = type(self) > instead of: > self.default_factory = recursivedefaultdict > ? It's more robust under subclassing. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From steve at holdenweb.com Thu Aug 30 13:21:53 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Aug 2007 13:21:53 -0400 Subject: Please assist- Python Consultant needed for 3-6 month project In-Reply-To: References: Message-ID: <46D6FCB1.4040709@holdenweb.com> Kelley McNeillie wrote: > I am contacting you from a company called Software Specialists, an IT Placement Firm based in Pittsburgh, PA. We are prepared to make a donation to your organization if you could please help us out with a referral. We are looking for a python developer with web-based application experience. If you know of anyone, or if you would be able to post this opportunity on your site, I would greatly appreciate it. I am finding this skill pretty much impossible to identify locally, and I really would like to be able to assist my client with this position. I am just trying to be creative in my search, I hope I am reaching the right person with this request. If not, I apologize. Thank you in advance for any assistance you may be able to provide. > Kelley: Please see http://www.python.org/community/jobs/ (which, by the way, is the first non-sponsored result for a Google search on "python jobs") and in particular http://www.python.org/community/jobs/howto/ which explains how you can submit jobs for inclusion on the Job Board. There is no fee for this service, though naturally donations to the Python Software Foundation are always gratefully received: http://www.python.org/psf/donations/ Good luck with your search. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From steve at holdenweb.com Thu Aug 16 07:31:36 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 16 Aug 2007 07:31:36 -0400 Subject: ploting issues in program In-Reply-To: References: <1187250500.571837.196940@19g2000hsx.googlegroups.com> Message-ID: Peter Otten wrote: > yadin wrote: > >> can you please help me to fix these polar plot in db's >> so that the center is at the minimun negative number in voltagedb >> about [-50] >> and the maximun is at zero and how can i see values on the axis like >> showing that the axes start at -50 -40 -30 .....and end at zero > > You posted this question several times now and got no response that you > liked enough to abstain from reposting. > > Now your options are: > > - Try another forum (the matplotlib mailing list would be a good candidate) > - Show some initiative: add 50 to the dB values and be done > >> here is the program > > [...] > >> voltagedb = [-48.7906044 ,-11.51244516, -5.58650713, -2.34604603, >> -0.56767793, 0. , >> -0.60034598, -2.41427014, >> -5.7042726 ,-11.75411924,-48.7906044 , >> -11.51244516, -5.58650713, -2.34604603, -0.56767793, >> 0. , >> -0.60034598, -2.41427014, -5.7042726 ,-11.75411924,] > > voltagedb = [v+50 for v in voltagedb] > >> polar(angteta,voltagedb) >> >> show() > The better the advice the worse it's wasted ... I might ask just exactly what is being plotted to give those answers. It sounds like field strength, but I am having difficulty envisaging a field that is weakest at its center - is this some sort of alternative universe you are plotting :-) ? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From kyosohma at gmail.com Fri Aug 17 17:12:10 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 17 Aug 2007 14:12:10 -0700 Subject: wxpython log redirect In-Reply-To: <1187292591.151231.41440@b79g2000hse.googlegroups.com> References: <1187292591.151231.41440@b79g2000hse.googlegroups.com> Message-ID: <1187385130.720910.77210@q4g2000prc.googlegroups.com> On Aug 16, 2:29 pm, vedrandeko... at v-programs.com wrote: > Hello, > > Why this wx example don't return \nHELLO WORLD and other text in same > window: > > import wx > import logging > import sys > > def nekaj(): > print "\nHELLO WORLD" > > class WxLog(logging.Handler): > def __init__(self, ctrl): > logging.Handler.__init__(self) > self.ctrl = ctrl > def emit(self, record): > self.ctrl.AppendText(self.format(record)+"\n") > > class MainFrame(wx.Frame): > def __init__(self): > wx.Frame.__init__(self, None, title="logging test") > sizer = wx.BoxSizer(wx.VERTICAL) > > log = wx.TextCtrl(self, style=wx.TE_MULTILINE) > > rootLogger = logging.getLogger('') > rootLogger.setLevel(logging.DEBUG) > hdlr = WxLog(log) > hdlr.setFormatter(logging.Formatter('%(levelname)s | %(name)s | > %(message)s [@ %(asctime)s in %(filename)s:%(lineno)d]')) > rootLogger.addHandler(hdlr) > rootLogger.debug(str(sys.stdout)) > nekaj() # goes to the function nekaj > > if __name__ =="__main__": > app = wx.App(0) > frame = MainFrame() > frame.Show() > app.MainLoop() > > Regards, > Vedran Why are you using the logging module? All you need to do is redirect stdout. See below: Give this a try: class XPinst(wx.App): def __init__(self, redirect=False, filename=None): wx.App.__init__(self, redirect, filename) def OnInit(self): self.frame = wx.Frame(None, -1, title='Redirect Test', size=(620,450), style=wx.STAY_ON_TOP| wx.DEFAULT_FRAME_STYLE) panel = wx.Panel(self.frame, -1) self.log = wx.TextCtrl(panel, -1, size=(500,400), style = wx.TE_MULTILINE|wx.TE_READONLY| wx.HSCROLL) redir=RedirectText(self.log) sys.stdout=redir print 'test' self.frame.Show() return True class RedirectText: def __init__(self,aWxTextCtrl): self.out=aWxTextCtrl def write(self,string): self.out.WriteText(string) If you use wx.App, you can also just set the "redirect" parameter to True as well. Mike From __peter__ at web.de Wed Aug 8 12:18:22 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 08 Aug 2007 18:18:22 +0200 Subject: 'Advanced' list comprehension? query References: <1186588812.006107.185570@o61g2000hsh.googlegroups.com> Message-ID: pyscottishguy at hotmail.com wrote: > I'm playing around with list comprehension, and I'm trying to find the > most aesthetic way to do the following: > > I have two lists: > > noShowList = ['one', 'two', 'three'] > > myList = ['item one', 'item four', 'three item'] > > I want to show all the items from 'myList' that do not contain any of > the strings in 'noShowList'. >>> no_show_list = ["one", "two", "three"] >>> my_list = ["item one", "item four", "three item"] >>> [item for item in my_list if not any(x in item for x in no_show_list)] ['item four'] Peter From bj_666 at gmx.net Thu Aug 30 08:35:06 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Aug 2007 12:35:06 GMT Subject: SAXParseException: not well-formed (invalid token) References: Message-ID: <5jnrrqFdmbcU5@mid.uni-berlin.de> On Thu, 30 Aug 2007 13:46:47 +0200, Pablo Rey wrote: > The page is > https://lcg-voms.cern.ch:8443/voms/cms/services/VOMSCompatibility?method=getGridmapUsers > and the line with the invalid character is (the invalid character is the > final ? of Universit?): The URL doesn't work for me in a browser. (Could not connect?) Maybe you can download that XML file and use `xmllint` to check if it is well formed XML!? Ciao, Marc 'BlackJack' Rintsch From alexandre.badez at gmail.com Fri Aug 31 04:14:21 2007 From: alexandre.badez at gmail.com (Alexandre Badez) Date: Fri, 31 Aug 2007 08:14:21 -0000 Subject: Setting a read-only attribute In-Reply-To: <1188509700.915517.178440@z24g2000prh.googlegroups.com> References: <1188509700.915517.178440@z24g2000prh.googlegroups.com> Message-ID: <1188548061.663133.273160@q5g2000prf.googlegroups.com> On Aug 30, 11:35 pm, "tleeuwenb... at gmail.com" wrote: > I have an object and wish to set an attribute on it which, > unfortunately for me, is read-only. > > How can I go about this? > > Cheers. > -T Could you show the object you want to set his attribute? Until that, it's difficult to answer to you. PS: If the attribut is on read only, their must a good reason for that ;) From bdesth.quelquechose at free.quelquepart.fr Thu Aug 30 08:07:39 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 30 Aug 2007 14:07:39 +0200 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188504811.019632.186580@x35g2000prf.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> <1188430887.481586.106760@l22g2000prc.googlegroups.com> <1188504811.019632.186580@x35g2000prf.googlegroups.com> Message-ID: <46d75116$0$401$426a74cc@news.free.fr> Russ a ?crit : (snip) > I don't see how you can avoid adding some new syntax, given that > Python does not > currently have syntax for specifying invariants and pre- and post- > conditions. class Parrot(object): @pre(lambda x : x != 42) @post(lambda result: result != 42) @invariant(lambda self: self.x == 42) def reliable_method(self, x): # your code here return something From steve at holdenweb.com Fri Aug 3 15:10:01 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 03 Aug 2007 15:10:01 -0400 Subject: downloading files In-Reply-To: <1186166920.757662.269340@o61g2000hsh.googlegroups.com> References: <1186166920.757662.269340@o61g2000hsh.googlegroups.com> Message-ID: Ehsan wrote: > I foundd this code in ASPN Python Cookbook for downloading files in > python but when it finished downloading files the files became > corrupted and didn't open, the files in internet havn't any problem: > > > def download(url,fileName): > """Copy the contents of a file from a given URL > to a local file. > """ > import urllib > webFile = urllib.urlopen(url) > localFile = open(fileName, 'w') > localFile.write(webFile.read()) > webFile.close() > localFile.close() > download('http://www.2shared.com/download/1839752/cd520048/ > xpersia14.3gp?tsid=20070803-143313-49566ea2', 'xpersia4.3gp' ) > I'm guessing there are binary files and you are running on Windows, which is inserting a carriage return before ebery newline. Try localFile = open(fileName, 'wb') to avoid thus behavior. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From jjl at pobox.com Mon Aug 20 15:46:45 2007 From: jjl at pobox.com (John J. Lee) Date: Mon, 20 Aug 2007 19:46:45 GMT Subject: desperately in need of a tool References: <1187560418.339131.283470@i38g2000prf.googlegroups.com> Message-ID: <87hcmuxa3e.fsf@pobox.com> yagyala writes: > I recently started working for a company that has just implemented its > first set of software standards. So far, so good. Here's the problem: > one of those standards is that the comments for each routine must > indicate every other routine that it calls. As I try to keep my Oh dear. > I'm sure some will wonder about the reasoning of this standard. The > company primarily has experience writing scientific alogorythms which > can get rather long. It makes a bit more sense to document all > routines called for a very long routine, but for short routines that > primarily call other routines, as most mine do, well.... Perhaps you can reason with them. Perhaps suggest the possibility that parts of the standard be waived or modified for the area of work you're involved with (rather than asking them for special personal dispensation, or asking them to throw away or rewrite their standards). John From fukazawa at gmail.com Sun Aug 19 05:21:27 2007 From: fukazawa at gmail.com (Andy) Date: Sun, 19 Aug 2007 09:21:27 -0000 Subject: Development for dual core machine Message-ID: <1187515287.226791.186700@j4g2000prf.googlegroups.com> Hi guys, I'm sorry, I'm not sure this is the correct group to be asking this kind of question... I'm going to develop a software package that includes a web server (and PHP code) , a database, and some Python code of course. I am being strongly suggested to make it to work on a dual- or multi-core computer, but I'm confused on how to take advantage of the multiple CPUs. >From what I read, I think that simply by making the package run in several separate processes (web server, database server, Python interpreter, etc.), and/or using multiple threads (which I will anyway) the package should be able to use multiple CPUs. Is my understanding correct? So actually, all I have to do is just write my multi-threaded Python code as usual? And how is it decided which process and which threads go to CPU 1, CPU 2, etc.? Perhaps the BIOS? Any advice greatly appreciated. Andy From gagsl-py2 at yahoo.com.ar Mon Aug 20 23:32:17 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 20 Aug 2007 20:32:17 -0700 Subject: Retrieving a variable's name. In-Reply-To: <1187658202.236626.93600@50g2000hsm.googlegroups.com> References: <1187658202.236626.93600@50g2000hsm.googlegroups.com> Message-ID: <1187667137.290457.314060@d55g2000hsg.googlegroups.com> On 20 ago, 22:03, rodrigo wrote: > How would I go about retrieving a variable's name (not its value)? I > want to write a function that, given a list of variables, returns a > string with each variable's name and its value, like: > > a: 100 > b: 200 > > I get the feeling this is trivial, but I have been unable to find an > answer on my own. Try using dir(), dir(xxx), vars(), vars(xxx), locals(), globals() -- Gabriel Genellina From gherron at islandtraining.com Sat Aug 18 14:54:59 2007 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 18 Aug 2007 11:54:59 -0700 Subject: sort dictionary by specific values In-Reply-To: References: Message-ID: <46C74083.4050307@islandtraining.com> dorje tarap wrote: > Hi, > > I need to perform some horrible functions in python I need to do, > using sort in a similar way that Excel can. > > With a dictionary like: > Code: ( text ) > > 1. > >>> d > 2. > {8: (99, 99), 9: [(55, 67), (77, 66), (67, 88)], 4: [(45, 78), > (56, 78), (99, 78)], 5: (67, 77)} > > > I want to sort the entire dictionary based on the last values in each > line. First for [-1][0] and then[-1][0]. > > So sorted descending I would like the output to look like: > Code: ( text ) > > 1. > >>> d > 2. > {8: (99, 99), 4: [(45, 78), (56, 78), (99, 78)], 9: [(55, 67), > (77, 66), (67, 88)], 5: (67, 77)} > > > Many thanks I can't make any sense of your requirements or your example, but perhaps I can help somewhat. You CANNOT sort a (standard Python) dictionary. You CAN find some alternative implements of dictionaries on the web that allow ordering, and you CAN extract the key,value pairs from a dictionary into a list, and sort that list (by any criteria you want). Gary Herron From gherron at islandtraining.com Thu Aug 30 10:48:50 2007 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 30 Aug 2007 07:48:50 -0700 Subject: strings (dollar.cents) into floats In-Reply-To: <12B58F2B-2F4F-4F6A-9F75-7444427B8CA8@email.it> References: <12B58F2B-2F4F-4F6A-9F75-7444427B8CA8@email.it> Message-ID: <46D6D8D2.2030102@islandtraining.com> luca bertini wrote: > Hi, > > i have strings which look like money values (ie 34.45) > is there a way to convert them into float variables? > everytime i try I get this error: "numb = float(my_line) ValueError: > empty string for float()" > " > here's the code > > ************ > > import sys > import re > > for line in sys.stdin.readlines(): > my_line = line.rstrip() > numb = float(my_line) > print numb > The clue "empty string for float" must mean that the value of my_line is an empty string. And that would seem to mean you have an empty line in your input. So... Either remove the empty lines, or test my_line before calling float on it. Gary Herron From sdavis.webb at gmail.com Fri Aug 3 13:53:47 2007 From: sdavis.webb at gmail.com (Stephen Webb) Date: Fri, 3 Aug 2007 13:53:47 -0400 Subject: Strange set of errors Message-ID: Greetings all, I've recently begun using Python to do scientific computation, and I wrote the following script to find approximate eigenvalues for a semi-infinite matrix: from pylab import * from numpy import * from scipy import * def bandstructure(N,s): b = s/4.0 jmax = 10 + N**2 spectrum1 = [0]*2*N spectrum2 = [0]*2*N spectrum3 = [0]*2*N for k in arange(1, 2*N+1, 1): A = zeros( (jmax,jmax) ) i = 0 while i <= jmax-1: if i <= jmax-2: A[i,i+1] = b A[i+1,i] = b A[i,i] = ((k + 2.0*i*N)/N)**2 i = i+1 else: A[i,i] = ((k + 2.0*i*N)/N)**2 i = i+1 #This portion of the code builds a matrix twice as large to check against B = zeros( (2*jmax,2*jmax) ) i = 0 while i <= 2*jmax-1: if i <= 2*jmax-2: B[i,i+1] = b B[i+1,i] = b B[i,i] = ((k + 2.0*i*N)/N)**2 i = i+1 else: B[i,i] = ((k + 2.0*i*N)/N)**2 i = i+1 x = linalg.eigvals(A) y = linalg.eigvals(B) j = 1 while j<=3: if abs(y[j]-x[j]) <= 10.0**(-5): j = j + 1 else: print 'jmax not large enough to obtain accurate results' spectrum1[k-1] = x[0] + 0.5*s spectrum2[k-1] = x[1] + 0.5*s spectrum3[k-1] = x[2] + 0.5*s plot (k, spectrum1, k, spectrum2, k, spectrum3) xlabel('k (energy level)') ylabel('E/E_r') title('Finite Size Band Structure, N = %d, s = %f' % (N, s)) grid(true) When I run this script, I get the following message, which I can't figure out: Traceback (most recent call last): File "", line 1, in File "bandstruc.py", line 61, in bandstructure plot (k, spectrum1, k, spectrum2, k, spectrum3) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib/pylab.py", line 2028, in plot ret = gca().plot(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib/axes.py", line 2535, in plot for line in self._get_lines(*args, **kwargs): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib/axes.py", line 437, in _grab_next_args for seg in self._plot_2_args(remaining[:2], **kwargs): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib/axes.py", line 337, in _plot_2_args x, y, multicol = self._xy_from_xy(x, y) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib/axes.py", line 266, in _xy_from_xy nrx, ncx = x.shape ValueError: need more than 0 values to unpack Also, I've been having trouble with the plot function in matplotlib. For example, I enter the following in the terminal: >>> from pylab import * >>> plot([1,2,3]) [] I'm reasonably sure that the issue in the first big error message is just an indexing error on my part, but I have no idea what the second thing means. Every time I run the plot([1,2,3]) I get a different ending number that seems to vary randomly. Could anybody please help me out with these problems? Thanks, Stephen -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at divmod.com Thu Aug 2 19:36:43 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 2 Aug 2007 19:36:43 -0400 Subject: python 3.0, pywin32 and scipy In-Reply-To: <5hevcaF3kia6jU1@mid.uni-berlin.de> Message-ID: <20070802233643.4947.706164934.divmod.quotient.17708@ohm> On Thu, 02 Aug 2007 23:07:12 +0200, "Diez B. Roggisch" wrote: >Jean-Paul Calderone schrieb: >> On Thu, 02 Aug 2007 21:16:04 +0200, "Diez B. Roggisch" >> wrote: >>> vml schrieb: >>>> Hello, >>>> >>>> >>>> I am trying to promote python in my job, my collegue only see matlab >>>> and microsoft scripting language. >>>> I understood that there willl be no backward compatibility between >>>> python 2.x and 3.0, does it means that: >>>> >>> [snip] >>> >>> You mean C#, the language that has seen 3 major revisions in the last 6 >>> years of existence, with C# 3 being announced already? And the .NET SDK, >>> that happily strode along with that? Compared to python, that has been >>> started in 1991 and now approaches it's third incarnation, I'd say >>> python has a record of steadiness that surpasses that of MS-based tools >>> by any means. >> >> This is not a valid comparison. In fact, C# 3 is completely backwards >> compatible with C# 2, just as C# 2 was backwards compatible with C# 1. > >Does that also apply to the SDK? > I'm not really sure what the answer to that is. I presume so, but perhaps someone who has more C# experience can chime in. Jean-Paul From kyosohma at gmail.com Thu Aug 9 16:24:48 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 09 Aug 2007 13:24:48 -0700 Subject: Puzzled by "is" In-Reply-To: References: <20070809194105.39BD11E400A@bag.python.org> Message-ID: <1186691088.090783.93810@z24g2000prh.googlegroups.com> On Aug 9, 2:53 pm, Steve Holden wrote: > Dick Moores wrote: > > At 10:46 AM 8/9/2007, Bill Scherer wrote: > >> Dick Moores wrote: > [...] > >> There is only one empty tuple. > >> Does that clear it up for you? > > > But isn't that the same as saying, "That's just the reality of > > Python; it is what it is."? I want to know why there is only one > > empty tuple, but more than one (1,). > > Why? Because. > > Seriously, it's just an optimization by the implementers. There is no > need for more than one empty tuple, since tuples can never be modified > once created. > > But they decided not to create (1, ) in advance. They probably knew that > hardly anybody would want to create that tuple ;-) [Seriously: if you > started trying to predict which tuples would be used you would go > insane, but the empty tuple is the most likely candidate]. > > > Also, > > >>> [] is [] > > False > > In that case it would definitely NOT make sense to have them the same > list. Python always ensures that the [] constructor creates a new list, > since that list may be bound to one or more variables and mutated. You > wouldn't want > > a = [] > b = [] > a.append("boo!") > > to change b so it was no longer an empty list. If you wanted a and b to > reference the same list you would change the second statement to > > b = a > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- Steve, I thought you'd probably weigh in on this esoteric matter. Very illuminating, as usual. Mike From bignose+hates-spam at benfinney.id.au Thu Aug 30 04:04:50 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 30 Aug 2007 18:04:50 +1000 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <87hcmhebwv.fsf@benfinney.id.au> Message-ID: <874pihe9ct.fsf@benfinney.id.au> Ben Finney writes: > def get_an_index_even_if_not_found(the_list, the_item): Bah. Should be "?(the_list, the_value):". -- \ "Don't worry about people stealing your ideas. If your ideas | `\ are any good, you'll have to ram them down people's throats." | _o__) -- Howard Aiken | Ben Finney From spam at spam.com Wed Aug 15 13:53:18 2007 From: spam at spam.com (daz.diamond) Date: Wed, 15 Aug 2007 17:53:18 GMT Subject: ming on win32 anyone ? [help a noob] In-Reply-To: <1187189695.581003.317920@q4g2000prc.googlegroups.com> References: <%QCwi.14541$rr5.1213@newsfe1-win.ntli.net> <1187189173.036327.65360@r29g2000hsg.googlegroups.com> <1187189695.581003.317920@q4g2000prc.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Aug 15, 9:46 am, "programmer... at gmail.com" > wrote: >> On Aug 15, 8:03 am, "daz.diamond" wrote: >> >>> hoping someone can help ... >>> how do I install ming (with python) on win32? have downloaded the tar.gz >>> of ming-0.3.0 which doesn't have a handy self-installer, and I'm >>> absolutely foxed as to what to do next ... the install instructions in >>> the package seem to be linux oriented, which to me may as well be in greek >>> any clues much appreciated, thx >>> daz >> I don't know what you've downloaded, but it does not sound like the >> right thing, err ming. The installer found here is 5.1.3.http://sourceforge.net/project/showfiles.php?group_id=2435 >> >> Maybe you should consider cygwin? >> >> jw > > I think the OP is referring to this: http://ming.sourceforge.net/ > > If so, it looks like it needs manual compilation using a C/C++ > compiler of some sort. > > Mike > yup, ming as in the ability to make swf files ... got it running with php no problem, but python seems another story ... manual compilation using c/c++ sounds complicated - is this the sort of thing i could do without knowledge of c/c++ or am i just barking at lamp-posts ? thx daz From gagsl-py2 at yahoo.com.ar Thu Aug 2 19:32:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 02 Aug 2007 20:32:23 -0300 Subject: Best way to capture output from an exec'ed (or such) script? References: <1186084086.212050.264270@q3g2000prf.googlegroups.com> Message-ID: En Thu, 02 Aug 2007 16:48:06 -0300, escribi?: > In any case. I've added some minor scripting support, so that you can > write dynamic pages in Python. To do this, I use execfile(), and pass > the script a dictionary with some basic variables. The script then > sets a "ret" variable that's sent back to the browser. That's some > major ugliness right there! If I do a "print" inside the script, then > it'll end up on the server console. I want it to end up in the web > browser. If `print` were a function, this would be easy: just provide a replacement into the dictionary you pass to the script. But print is a statement, and this becomes a bit harder. If your web server only processes a single request at a time, you can replace sys.stdout (and perhaps sys.stderr) with a suitable object having a write() function: a true open file, or a StringIO instance, or even a custom object that collects "printed" lines into a list. If your web server is multithreaded (or you use some other way to process many simultaneous requests) you have to be more careful - remember that sys.stdout is global, you must find a way to distinguish between output from different processes all going into the same collector. -- Gabriel Genellina From fukazawa at gmail.com Sun Aug 19 22:45:50 2007 From: fukazawa at gmail.com (Andy) Date: Mon, 20 Aug 2007 02:45:50 -0000 Subject: Development for dual core machine In-Reply-To: <5irrbdF3r2m8aU3@mid.individual.net> References: <1187515287.226791.186700@j4g2000prf.googlegroups.com> <7x3ayfsagr.fsf@ruckus.brouhaha.com> <5irrbdF3r2m8aU3@mid.individual.net> Message-ID: <1187577950.231283.254950@i38g2000prf.googlegroups.com> Thanks guys for the suggestions. Andy From ianare at gmail.com Mon Aug 13 01:01:04 2007 From: ianare at gmail.com (=?iso-8859-1?B?aWFuYXLp?=) Date: Mon, 13 Aug 2007 05:01:04 -0000 Subject: Colored text In-Reply-To: <1186970751.435970.189900@q3g2000prf.googlegroups.com> References: <1186970751.435970.189900@q3g2000prf.googlegroups.com> Message-ID: <1186981264.235988.40260@k79g2000hse.googlegroups.com> On Aug 12, 10:05 pm, Rohan wrote: > Hello, > Can some one tell me how do I get colored text. Say when I want to > write something in a text file , how do I get it colored. Plain text files don't have color. You could output in html ... From listserver at tdw.net Mon Aug 20 15:13:38 2007 From: listserver at tdw.net (Tim Williams) Date: Mon, 20 Aug 2007 20:13:38 +0100 Subject: reading a line in file In-Reply-To: References: <93066C069973ED448DC2BCEA9C44A7383BE2B2@efmailx> <2dc0c81b0708201029k5909d919vcf0deebae74a79c7@mail.gmail.com> <9afea2ac0708201159t4602fe3fpfb738a22f063f37@mail.gmail.com> Message-ID: <9afea2ac0708201213j505aa188t6ef079e4bf07cb37@mail.gmail.com> On 20/08/07, Brian McCann wrote: > > > > ________________________________ > From: tdwdotnet at gmail.com on behalf of Tim Williams > Sent: Mon 8/20/2007 2:59 PM > To: Brian McCann > Cc: python-list at python.org > Subject: Re: reading a line in file > > > > > On 20/08/07, Brian McCann wrote: > > > > Hi, > > > > I can read in the whole file build.number which has the following lines > > how do I just capture the value of build.number and assign it to a > variable > > Thanks, > > Brian > > > > contents of file build.number: > > #Build Number for ANT. Do not edit! > > #Mon Aug 20 04:04:51 EDT 2007 > > build.number=1 > > buildinfo.py > > ################################## > > #!/usr/bin/python > > import string > > import os > > import sys > > import time > > import errno > > import shutil > > buildinfo = "build.number" > > input = open(buildinfo, 'r') > > for line in input: > > print line > > ######################################### > > > > command line when script is run > > $ buildinfo.py > > #Build Number for ANT. Do not edit! > > > > #Mon Aug 20 04:04:51 EDT 2007 > > build.number=1 > > > > > > This is preferred nowadays > > for line in open(buildinfo): > print line > > Without a sample of the data, no-one can help you further. If this > is homework, you should say so, people will give you guidance :) > > Hi Tim, > The sample data is in file build.number > > contents of file build.number: > > #Build Number for ANT. Do not edit! > #Mon Aug 20 04:04:51 EDT 2007 > build.number=1 > > Thanks, > Brian > (bottom posting is preferred here :) ) Brian, can you expand on this a bit? A single entry doesn't give much to go on. 20-ish lines would be better. Anyone looking at this would need to see whether each entry was on its own line, whether there are duplicates, whether delimiters are always the same etc. From kyosohma at gmail.com Thu Aug 9 09:03:34 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 09 Aug 2007 06:03:34 -0700 Subject: wxPython before MainLoop In-Reply-To: <13bl9a75laqcm70@corp.supernews.com> References: <13bl9a75laqcm70@corp.supernews.com> Message-ID: <1186664614.771337.198570@x40g2000prg.googlegroups.com> On Aug 9, 12:25 am, "[david]" wrote: > I'd like to refresh the display before I start the main loop. > > I have code like this: > > app = App() > app.Show() > app.long_slow_init() > app.MainLoop() > > The main frame partly loads at Show, but because the mainloop has not > started yet, the display does not update until long_slow_init() finishes. > > Alternatively, I could code > > app = App() > app.long_slow_init() > app.Show() > app.MainLoop() > > Which would give me a crisp Show, but there would be a long slow wait > before the app showed any activity at all. I would need a splash screen. > > I'd rather not have a splash screen (and I don't know how anyway). I'd > like to just make app.Show() finish correctly before running > long_slow_init. > > Is there a wx internal method that I can use to give Windows the > opportunity to finish painting the frame before I run long_slow_init()? > > Or is there a better idea? > > (david) Yeah, I think 7stud's thread is the way to go. It's what I do with long running tasks, see also: http://wiki.wxpython.org/LongRunningTasks If your screen doesn't load correctly, be sure to call the Layout() method. Mike From zyzhu2000 at gmail.com Wed Aug 1 12:42:58 2007 From: zyzhu2000 at gmail.com (beginner) Date: Wed, 01 Aug 2007 16:42:58 -0000 Subject: Awkward format string In-Reply-To: References: <1185984697.605529.157110@g12g2000prg.googlegroups.com> Message-ID: <1185986578.527619.314310@e9g2000prf.googlegroups.com> On Aug 1, 11:31 am, "Chris Mellon" wrote: > On 8/1/07, beginner wrote: > > > Hi, > > > In order to print out the contents of a list, sometimes I have to use > > very awkward constructions. For example, I have to convert the > > datetime.datetime type to string first, construct a new list, and then > > send it to print. The following is an example. > > > x=(e[0].strftime("%Y-%m-%d"), e[1].strftime("%Y-%m-%d"))+e[2:] > > print >>f, "%s\t%s\t%d\t%f\t%f\t%f\t%d" % x > > > e is a tuple. x is my new tuple. > > > Does anyone know better ways of handling this? > > You seem to be doing quite complicated things with your magical e > tuple. Do you have some specific aversion to classes? e is not complicated. It is a record that have 7 fields. In my program a function outputs a list of tuples, each is of type e, and now I just need to send them to a text file. I have no problem using classes and I do use them everywhere. But using classes does not solve my problem here. I will probably find myself doing: print >>f, "%s\t%s\t%d\t%f\t%f\t%f\t%d" % (x.field1..strftime("%Y-%m- %d"), x.field2..strftime("%Y-%m-%d"), x.field3, x.field4, x.field5, x.field.6, x.field7) This is also tedious and error-prone. From mccredie at gmail.com Mon Aug 27 19:06:28 2007 From: mccredie at gmail.com (Matt McCredie) Date: Mon, 27 Aug 2007 16:06:28 -0700 Subject: an eval()-like exec() In-Reply-To: <1188241165.418263.165730@k79g2000hse.googlegroups.com> References: <1188241165.418263.165730@k79g2000hse.googlegroups.com> Message-ID: <9e95df10708271606i707272c1y84bfbce2f82b487c@mail.gmail.com> > A python interactive interpreter works by having the user type in some > code, compiling and running that code, then printing the results. For > printing, the results are turned into strings. > > I would like make an interpreter which does this, without the last > part: i.e. where the results are returned as objects, instead of as > strings. I.e. have I would like to see something that behaves like > this: > > >>> ip = MyInterpreter() > # this started a new interpreter > >>> ip.run("import math") is None > True > >>> ip.run("math.pi") is math.pi > True > > Neither exec() or eval() is usable for this, as far as I see, because > eval can't handle arbitrary python code (eval("import math") ), and > exec() doesn't return the results. > > Subclassing an code.InteractiveInterpreter or code.InteractiveConsole > seems like a usable idea, but I couldn't find out what to do to get > the results before they are turned into strings. > > Using compile() and then eval() didn't seem usable either. > > Any ideas? Well, my first thought is that exec and eval serve two different purposes, and you should just have both of them and use the appropriate one based on the situation. However, I think it is possible to enable the behavior you want: [code] def myeval(statement, globals_=None, locals_=None): try: return eval(statement, globals_, locals_) except SyntaxError: if locals_ is None: import inspect locals_ = inspect.currentframe().f_back.f_locals exec statement in globals_, locals_ [/code] It seems to work for me. Matt From Shawn at Milochik.com Tue Aug 28 11:22:04 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Tue, 28 Aug 2007 11:22:04 -0400 Subject: Asking all python programmers. In-Reply-To: References: Message-ID: <2dc0c81b0708280822t70bf0528s4f80fe926cbb91bf@mail.gmail.com> On 8/27/07, Lamonte Harris wrote: > Okay, I know you've guys told me millions of times to read the manual I've > read a lot of it. What do you recommend studying the most? Python is my > goal for the next year in the half. :) > > -- > http://mail.python.org/mailman/listinfo/python-list > Some notes on your question: "You've guys" is nonsensical. Your first sentence is a run-on sentence. Your e-mail address identifies you as an immature script-kiddie. "Year in the half" is nonsensical. Okay, so why am I "picking on you"? Because I want to help. Present yourself in this way, and you're not going to get as much help from intelligent people as you would if they saw you were worth their time. You are either going to get angry at me or you're going to think about this. If you're angry then I can't help you. If you actually care how people see you, you will get further in life in general. To answer the question I think you were trying to ask, a combination of "The Python Cookbook" and "Dive Into Python" should get you started in doing amazing things with Python. The latter is available for free online. Take some pride in the way you write. It will pay off. Shawn From lasses_weil at klapptsowieso.net Thu Aug 30 15:18:06 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Thu, 30 Aug 2007 21:18:06 +0200 Subject: subclassing Python types In-Reply-To: <1188500442.434722.157350@q5g2000prf.googlegroups.com> References: <1188500442.434722.157350@q5g2000prf.googlegroups.com> Message-ID: <46d717f5$0$30367$9b4e6d93@newsspool4.arcor-online.net> zzbbaadd at aol.com wrote: > I have read that you can derive from the base classes such as str, > list, dict. > > I guess this would look like: > > def MyString(str): > def MyList(list): > def MyDict(dict): > > Well, replace 'def' with 'class' and you're right. > How do you access the data that is contained in the super class? > This way: >>> class MyList(list): ... def do_something(self): ... self.append(3) ... print self ... >>> l = MyList((1, 2)) >>> l [1, 2] >>> l.do_something() [1, 2, 3] That is: Whenever you want to refer to the value refer to self (that is, refer to the instance of your class). /W From bj_666 at gmx.net Thu Aug 9 09:04:49 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Aug 2007 13:04:49 GMT Subject: check if regeular expression has results References: <1186664302.050036.302670@g4g2000hsf.googlegroups.com> Message-ID: <5i0hnhF3kuhitU1@mid.uni-berlin.de> On Thu, 09 Aug 2007 05:58:22 -0700, shahargs wrote: > I'm looking for the best way to check if regular expression return > true (it's mean - there is a match). for example, i want "if" that > check if this regular expression: .*born.*to.* has a match. > > What's the way to do that simply? Simply use an ``if`` on the result of the search or match. If the regular expression doesn't match `None` is returned, which is `False` in a boolean context, otherwise a match object is returned, which is `True` in a boolean context. Ciao, Marc 'BlackJack' Rintsch From robert.kern at gmail.com Thu Aug 30 16:42:15 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 30 Aug 2007 15:42:15 -0500 Subject: Biased random? In-Reply-To: References: Message-ID: Ivan Voras wrote: > Jeffrey Barish wrote: > >> If you take the difference between two uniformly distributed random >> variables, the probability density function forms an isosceles triangle >> centered at 0. Take the absolute value of that variable and the pdf is a >> straight line with maximum value at 0 tapering to 0 at max. Thus, >> >> z = abs(randint(0, max) - randint(0, max)) >> >> ought to do the trick. > > It's elegant :) > > I've noticed something interesting in my test: the value 0 appears less > often than other values (which behave as they should). The distribution of the difference (before the abs()) looks like this (max=4): # ### ##### ####### ---0+++ 321 123 Taking the absolute value doubles up the non-zero masses, but there's no "negative 0" to add to the 0s stack. # # ### ### #### #### 0123 The method does not work because of that. -- 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 debl2NoSpam at verizon.net Wed Aug 1 00:50:41 2007 From: debl2NoSpam at verizon.net (David Lees) Date: Wed, 01 Aug 2007 04:50:41 GMT Subject: Scipy and Mcafee Site Advisor? Message-ID: I know scipy.org is legit and supplies widely used and useful python packages. Can someone explain why my McAfee SiteAdvisor software, flags scipy.org as a dangerous site? Pardon my ignorance, but is this a temporary error in the SiteAdvisor database or is there some privacy consideration involved? I am wondering if I should remove the SiteAdvisor software, because it is not particularly reliable. Puzzled. david lees From kyosohma at gmail.com Tue Aug 28 11:08:29 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 28 Aug 2007 08:08:29 -0700 Subject: wxpython:how to minimize to taskbar In-Reply-To: <1188312614.463169.93890@k79g2000hse.googlegroups.com> References: <1188310247.587456.103440@i13g2000prf.googlegroups.com> <1188312614.463169.93890@k79g2000hse.googlegroups.com> Message-ID: <1188313709.301024.193960@y42g2000hsy.googlegroups.com> On Aug 28, 9:50 am, "programmer... at gmail.com" wrote: > On Aug 28, 9:10 am, Jimmy wrote: > > > I'm kinda newbie to python and wxPython. Now I'm confronting a thorny > > problem: how can I make my program minimize to the taskbar > > represented as an ico, and when there is some message from network > > coming, it will pop out? > > Warning. I have not tested this. I happened to have some old code > that would iconify to the system tray. Here's what I think you need > to do. (If it does not work, just yell and I'll try to hack something > together for you.) > > Inside the ctor of your mainframe, you'll need to construct a > wxTaskBarIcon (I derive from it). This is my code that derives from > wxTaskBarIcon. The comments should give you a good idea of how this > thing works. I *think* this will shove the icon in the system tray, > even if you're not `iconified` -- so only create it if you want to > show up in the system tray. > > ## My wxTaskBarIcon derived object... > """ > Taskbar icon. > > Not much functionality here, not even a menu. In the future, this > will be a > good place to allow dclient functionality from the systray. > """ > > from wx import TaskBarIcon, EVT_TASKBAR_LEFT_DCLICK > > class ddTaskBarIcon(TaskBarIcon): > def __init__(self, icon, tooltip, frame): > TaskBarIcon.__init__(self) > self.SetIcon(icon, tooltip) > self.frame = frame > > # > # At the very least, restore the frame if double clicked. Add > other > # events later. > # > self.Bind(EVT_TASKBAR_LEFT_DCLICK, self.on_left_dclick) > > def on_left_dclick(self, e): > if self.frame.IsIconized(): > self.frame.Iconize(False) > if not self.frame.IsShown(): > self.frame.Show(True) > self.frame.Raise() > > def CreatePopupMenu(self): > """ > Override with menu functionality, later. > """ > return None > > Next is where I use it in my wxFrame derived object. This is the code > in my ctor. > # ddTaskBarIcon is defined above... > self.trayicon = ddTaskBarIcon(self.frame_icon, "Dap Daemon", self) > > # Handle the window being `iconized` (err minimized) > self.Bind(wx.EVT_ICONIZE, self.on_iconify) > > # This is the event handler referenced in the ctor above > def on_iconify(self, e): > """ > Being minimized, hide self, which removes the program from the > taskbar. > """ > self.Hide() > > So how does this work? Well, the ddTaskBarIcon (err, i realize this > is a misnomer) is constructed, which puts an icon in the system tray. > The icon has a dbl-click event handler that will `raise` and show the > window if necessary. > > The iconify event handler will hide the window if a minimize event > occurs. This keeps the window from showing up in the windows taskbar. > > Thats the magic. YMMV. > > FWIW - the code I reference is over 5 years old and still runs with > wxPython 2.8ish... Kudos to Robin Dunn and crew. Great job. > > jw I've been dinking around with getting one of my programs to minimize to the system tray for quite a while. I could get the icon, but I could not get an event to fire when I minimized. Thanks for the code. Now it works. Mike From aleax at mac.com Sun Aug 12 02:04:39 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 11 Aug 2007 23:04:39 -0700 Subject: LRU cache? References: <7x8x8ixomj.fsf_-_@ruckus.brouhaha.com> Message-ID: <1i2peoe.18eos9adkclkcN%aleax@mac.com> Paul Rubin wrote: > Anyone got a favorite LRU cache implementation? I see a few in google > but none look all that good. I just want a dictionary indexed by > strings, that remembers the last few thousand entries I put in it. So what's wrong with Evan Prodromou's lrucache.py module that's in pypi? Haven't used it, but can't see anything wrong at a glance. Alex From cbfalconer at yahoo.com Thu Aug 30 09:45:50 2007 From: cbfalconer at yahoo.com (CBFalconer) Date: Thu, 30 Aug 2007 09:45:50 -0400 Subject: Important Research Project References: <13ddcvm1bsu3s94@corp.supernews.com> Message-ID: <46D6CA0E.E66ED5C8@yahoo.com> "E.D.G." wrote: > > This report is being posted to a number of Internet Newsgroups to > see if there are any experienced computer programmers who would > like to provide some assistance with an effort to develop a Perl > language computer program. Where is Perl described in the C standard? This seems rather OT. -- Chuck F (cbfalconer at maineline dot net) Available for consulting/temporary embedded and systems. -- Posted via a free Usenet account from http://www.teranews.com From skawaii at gmail.com Mon Aug 27 17:02:25 2007 From: skawaii at gmail.com (skawaii at gmail.com) Date: Mon, 27 Aug 2007 21:02:25 -0000 Subject: Help on resizing a custom widget In-Reply-To: References: <1188240870.457859.207670@57g2000hsv.googlegroups.com> Message-ID: <1188248545.231227.284760@w3g2000hsg.googlegroups.com> On Aug 27, 4:40 pm, Phil Thompson wrote: > On Monday 27 August 2007, skaw... at gmail.com wrote: > > > Ok, here's what's going on. I've just created a custom widget. it > > works great. I'm having some trouble, however, figuring out how to > > allow the said widget to resize. For example, when I throw the widget > > into a new dialog (using Qt Designer), I want to be able to drag it > > larger/smaller and have widget expand/shrink to that size. Right now, > > I can drag the widget bigger/smaller all I want, but it doesn't > > actually change size. > > > I'm pretty new to PyQt (and therefore, Qt), so I'm pretty sure that > > the answer is a property that needs to be set somewhere. I'm just not > > sure which one. So you know, I'm using Python 2.4.3 and PyQt 3.1.6. > > > Any help and suggestions would be appreciated. Thanks. > > Probably best to start with the following... > > http://doc.trolltech.com/4.3.0/layout.html#custom-widgets-in-layouts > > Phil Thanks for pointing me in the right direction. I'll take a look at it. From wpdster at gmail.com Tue Aug 7 10:38:32 2007 From: wpdster at gmail.com (Patrick Doyle) Date: Tue, 7 Aug 2007 10:38:32 -0400 Subject: Importing * From a Package In-Reply-To: References: <20070806143253.4947.1097304571.divmod.quotient.19513@ohm> Message-ID: On 7 Aug 2007 13:54:21 GMT, Duncan Booth wrote: > "Patrick Doyle" wrote: > > > Why does Python include the submodules that were explicitly loaded by > > previous imports? Does it go out of it's way to do so? If so, why? > > What purpose does it serve? Or, is it a natural fallout of the manner > > in which imports are processed? If so, could somebody guide my > > intuition as to why this would be such a natural fallout? > > > > It is a natural fallout of the manner in which imports are processed. > When you explicitly load a submodule a reference to the submodule is > stored in the parent module. When you do 'from module import *' and the > imported module doesn't define __all__, you create a reference in the > current module to everything referenced by the imported module (except > for variables beginning with '_'). > Ahhh, I see it now >>> import SDRGen >>> dir() ['SDRGen', '__builtins__', '__doc__', '__name__'] >>> dir(SDRGen) ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] >>> from SDRGen import * >>> dir() ['SDRGen', '__builtins__', '__doc__', '__name__'] >>> dir(SDRGen) ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] (notice, no changes) >>> from SDRGen.TFGenerator import TFGenerator >>> dir() ['SDRGen', 'TFGenerator', '__builtins__', '__doc__', '__name__'] >>> TFGenerator (as expected) >>> dir(SDRGen) ['TFGenerator', '__builtins__', '__doc__', '__file__', '__name__', '__path__'] >>> SDRGen.TFGenerator and that's what led to my confusion... when my script later did a >>> from SDRGen import * The 'TFGenerator' name got changed from a reference to the 'TFGenerator' class to a reference to the 'SDRGen.TFGenerator' module. and now it makes sense. Thanks. --wpd From ldo at geek-central.gen.new_zealand Thu Aug 30 22:36:01 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 31 Aug 2007 14:36:01 +1200 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <87hcmhebwv.fsf@benfinney.id.au> Message-ID: In message <87hcmhebwv.fsf at benfinney.id.au>, Ben Finney wrote: > zzbbaadd at aol.com writes: > >> What's with the index() function of lists throwing an exception on not >> found? > > It's letting you know that the item isn't in the list. There's no > sensible return value from an "index" function in that condition. How about returning None? That's what's already done by the dict.get method by default. From hugh_jmptn at yahoo.com Fri Aug 31 15:27:24 2007 From: hugh_jmptn at yahoo.com (Hugh Jampton) Date: Fri, 31 Aug 2007 12:27:24 -0700 Subject: Horace Lives! Message-ID: <1188588444.816874.22000@r29g2000hsg.googlegroups.com> http://horace-vitreouschina.blogspot.com/ From duprez at hinet.net.au Mon Aug 27 02:05:30 2007 From: duprez at hinet.net.au (Mick Duprez) Date: Sun, 26 Aug 2007 23:05:30 -0700 Subject: Error with Simplemapi.py In-Reply-To: References: <1187938985.165186.300780@i38g2000prf.googlegroups.com> Message-ID: <1188194730.024877.120880@q5g2000prf.googlegroups.com> On Aug 27, 2:00 pm, "Gabriel Genellina" wrote: > En Fri, 24 Aug 2007 04:03:05 -0300, Mick Duprez > escribi?: > > > I have a small problem. I get an error I don't know how to resolve, > > any help would be much appreciated. > > I'm using Python25 on winXP pro and the script from the link above. > > Here's the error - > > >>>> mailtest.SendMail('no... at somewhere.net','test','test > >>>> string','c:\dbs.txt') > > That should be 'c:\\dbs.txt' or r'c:\dbs.txt' > > > Traceback (most recent call last): > > File "", line 1, in > > mailtest.SendMail('no... at somewhere.net','test','test string','c: > > \dbs.txt') > > File "C:\Python25\mailtest.py", line 135, in SendMail > > cast(NULL, lpMapiRecipDesc), RecipCnt, recip, > > File "C:\Python25\lib\ctypes\__init__.py", line 478, in cast > > return _cast(obj, obj, typ) > > ArgumentError: argument 1: : wrong type > > I'm unsure what those cast(NULL, ...) are supposed to do, but they look > all wrong. NULL, as defined on that script, is *not* a C NULL pointer (use > None for that). > (In fact the whole script doesn't look well at all - do you *have* to use > MAPI? can't use SMTP instead? Even if you must use MAPI, try the pywin32 > package from Mark Hammond, it has MAPI support and a demo script for > sending mail) > > > I have had a brief look at the C api for these structs and functions > > but I can't resolve it, it is probably something simple. > > The piece of code I don't understand though is this - > > > MapiRecipDesc_A = MapiRecipDesc * len(RecipWork) #size of struct?? > > This declares a new type, an array of len(RecipWork) items, each of type > MapiRecipDesc > > > rda = MapiRecipDesc_A() # isn't it MapiRecipDesc as declared?? > > This creates an instance of the above array. > > -- > Gabriel Genellina Thank you very much Gabriel, changing the NULL to None did the trick (it also helps if I reload the changed module after editing!:( ). Yes that is an old script and I will look into your suggestions. Basically I'd just like to use the default mail client (windows or Unix/Linux) to send simple mail with attachments, this way I can log the attachments I send to a db for example for document transmittal/ register reports etc. Thanks also for the code explanations, Cheers, Mick. From steveo at syslang.net Wed Aug 22 15:10:54 2007 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 22 Aug 2007 15:10:54 -0400 (EDT) Subject: Redo: How to create a function dynamically. Message-ID: I have this which works: #! /usr/bin/python strfunc = """ def foo( a ): print 'a = ', a """ exec strfunc globals()['foo'] = foo foo( 'Hello' ) and this which does not: #! /usr/bin/python import new strfunc = """ def foo( a ): print 'a = ', a """ co = compile ( strfunc, '', 'exec' ) exec co nfunc = new.function( co, globals(), 'foo' ) globals()['foo'] = nfunc foo( 'Hello' ) When I try to run this one I get: Traceback (most recent call last): File "./m2.py", line 13, in ? foo( 'Hello' ) TypeError: ?() takes no arguments (1 given) I need the second case to work because I want to be able to end up with a function in a seperate module to do the work of function creation. The caller will pass in globals() so that the resulting function will end up in the directory?/dictionary? of that caller. [And my apologies for overcomplicating the question on my first try.] -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From cdleary at gmail.com Thu Aug 2 10:36:05 2007 From: cdleary at gmail.com (cdleary at gmail.com) Date: Thu, 02 Aug 2007 14:36:05 -0000 Subject: Case study: library class inheritance with property declarations In-Reply-To: <1186063694.311416.133390@i13g2000prf.googlegroups.com> References: <1186062582.975223.230270@g12g2000prg.googlegroups.com> <1186063694.311416.133390@i13g2000prf.googlegroups.com> Message-ID: <1186065365.546545.184840@i13g2000prf.googlegroups.com> On Aug 2, 7:08 am, cdle... at gmail.com wrote: > On Aug 2, 6:49 am, cdle... at gmail.com wrote: > > > > > Hi all, > > > It's possible that I'm missing the obvious -- I've been up for over 24 > > hours and I'm most likely dehydrated from mass coffee intake, but I > > figure many people in similar circumstances will be searching > > comp.lang.python one day, so here goes! > > > class LibraryClass(object): > > > """ > > A class whose implementation is out of my hands. > > """ > > > def __init__(self): > > """ > > Follows good dynamic-language form and binds all instance > > variables at initialization time. > > """ > > # Omitted: complex initialization functionality. > > self.useful_attr = None > > > class MyInheritedClass(LibraryClass): > > > """ > > My refinement of the functionality offered by the LibraryClass. I > > now want the instance to initialize with a reference to an > > external > > object, and the useful_attr defined in the superclass will now > > reference an attribute of that external object via fget. > > > Changing the attribute of the external object has undefined > > behavior, so I want to omit an fset in the property declaration; > > however, I have to provide some way for the superclass to > > initialize useful_attr -- I can't change the superclass' code, as > > it > > resides in a library that is out of my hands. > > """ > > > def __init__(self, external_obj): > > LibraryClass.__init__(self) > > self._external_obj = external_obj > > > def get_useful_attr(self): > > return self._external_obj.proxy_useful_attr > > > useful_attr = property(fget=get_useful_attr) > > > def test(): > > class _Fake(object): > > pass > > external_obj = _Fake() > > external_obj.proxy_useful_attr = 12 > > spam = MyInheritedClass(external_obj) > > > if __name__ == '__main__': > > test() > > EOF > > > If you're one of those people who doesn't like laboriously reading > > contrived examples (elitists ;) I'll boil it down for you: Library > > class initializes some attribute, but derived class wants to eliminate > > fsets for said attribute. As a result, our ideal solution > > > Of course, this means that the derived class will raise an error in > > some circumstances where the base class wouldn't (when you're setting > > that attribute), but one can assume that the inheritance is > > worthwhile. > > > How do I come up with silly solutions to circumvent this? Let me count > > the ways... > > > 1. So-and-so: make an fset that does nothing. This ignores (what > > should be) errors in code that uses MyInheritedClass in an attempt to > > accommodate a useless statement in the base class -- surely non-ideal. > > 2. The ugly one: since you can probably view the library, copy and > > paste the complex initialization functionality in the above, but leave > > out the bad statement. This not only forfeits the ideals of > > inheritance, but makes you totally incompatible with future library > > changes. > > 3. Cheerleader: Pure evil. On top of the ugliness of 2, you assume > > that across library revisions the indenting won't change and that the > > troublesome statement will remain on the same line, and pull off one > > of these babies: > > > def super_evil_test(): > > from inspect import getsourcelines > > exec(''.join([line[4:] for line in > > getsourcelines(LibraryClass.__init__)[0][:-1]])) > > LibraryClass.__init__ = __init__ > > test() # Passes, but several angels no longer get their wings > > > Totally kidding, everybody! I hope Guido doesn't read this thread... > > > And this concludes the sleep deprived rambling that follows the > > somewhat interesting case in point. Thoughts? > > I'm sorry -- the solution was not /enough/ coffee. Got another cup and > sat down with the type/class unification doc, and found this thought- > stimulating portion: > > http://www.python.org/download/releases/2.2/descrintro/#property > If you want to override the __get__ operation for properties when used > as a class attribute, you can subclass property - it is a new-style > type itself - to extend its __get__ method, or you can define a > descriptor type from scratch by creating a new-style class that > defines __get__, __set__ and __delete__ methods. > ... > The get method won't be called when the property is accessed as a > class attribute (C.x) instead of as an instance attribute (C().x). > > Seeing as how property is just a wrapper class, we don't need to > declare it in the class body, though it /is/ the convention and the > way it's done in all the docs I've seen. We fix our inherited class to > be the following: > > [snip] > class MyInheritedClass(LibraryClass): > > """ > My refinement of the functionality offered by the LibraryClass. I > now want the instance to initialize with a reference to an > external > object, and the useful_attr defined in the superclass will now > reference an attribute of that external object via fget. > > Changing the attribute of the external object has undefined > behavior, so I want to omit an fset in the property declaration; > however, I have to provide some way for the superclass to > initialize useful_attr -- I can't change the superclass' code, as > it > resides in a library that is out of my hands. > """ > > def __init__(self, external_obj): > LibraryClass.__init__(self) > self.useful_attr = property(fget=self.get_useful_attr) > self._external_obj = external_obj > > def get_useful_attr(self): > return self._external_obj.proxy_useful_attr > [snip] > > And it tests like a charm. Last post -- I swear. I failed to realize that it's all part of an extremely well defined attribute resolution protocol, and handled via the descriptor specification. Discussing descriptors was on the TODO list for the type/class unification document, but there's a very fulfilling explanation by Raymond Hettinger: http://users.rcn.com/python/download/Descriptor.htm Also, the official doc is here: http://docs.python.org/ref/descriptors.html Maybe the documentation for the property builtin should make reference to the descriptor specification? If nobody thinks this is silly, I'll submit a documentation patch in a few days. Sorry for the spam -- hope someone besides me learns from it! - Chris From llasram at gmail.com Wed Aug 15 15:14:23 2007 From: llasram at gmail.com (Marshall T. Vandegrift) Date: Wed, 15 Aug 2007 15:14:23 -0400 Subject: encrypting files + filestreams? References: <1187186797.579680.206820@19g2000hsx.googlegroups.com> Message-ID: <87absspq40.fsf@seneca.iss.local> per9000 writes: > I am trying to figure out the best way to encrypt files in python. Looking at your code and questions, you probably want to pick up a cryptography handbook of some sort (I'd recommend /Practical Cryptography/) and give it a read. > But I have some thoughts about it. By pure luck (?) this file happened > to be N*512 bytes long so I do not have to add crap at the end - but > on files of the size N*512 + M (M != 521) I will add some crap to make > it fit in the algorithm. BTW, AES has a block size of 16, not 512. > When I later decrypt I will have the stuff I do not want. How do > people solve this? (By writing the number of relevant bytes in > readable text in the beginning of the file?) There are three basic ways of solving the problem with block ciphers. Like you suggest, you can somehow store the actual size of the encrypted data. The second option is to store the number of padding bytes appended to the end of the data. The third is to use the block cipher in cipher feedback (CFB) or output feedback (OFB) modes, both of which transform the block cipher into a stream cipher. The simplest choice coding-wise is to just use CFB mode, but the "best" choice depends upon the requirements of your project. > Also I wonder if this can be solved with filestreams (Are there > streams in python? The only python file streams I found in the evil > search engine was stuff in other forums.) Try looking for information on "file-like objects." Depending on the needs of your application, one general solution would be to implement a file-like object which decorates another file-like object with encryption on its IO operations. > crptz = AES.new("my-secret_passwd") I realize this is just toy code, but this is almost certainly not what you want: - You'll get a much higher quality key -- and allow arbitrary length passphrases -- by producing the key from the passphrase instead of using it directly as the key. For example, taking the SHA-256 hash of the passphrase will produce a much higher entropy key of the correct size for AES. - Instantiating the cipher without specifying a mode and initialization vector will cause the resulting cipher object to use ECB (electronic codebook) mode. This causes each identical block in the input stream to result in an identical block in the output stream, which opens the door for all sorts of attacks. Hope this helps! -Marshall From stateroad at gmail.com Mon Aug 27 15:02:14 2007 From: stateroad at gmail.com (Nicholas Amorim) Date: Mon, 27 Aug 2007 16:02:14 -0300 Subject: Image.open( "C:\test.jpg") is this wrong ? In-Reply-To: <9afea2ac0708270941u2c9dad3eyb9877de04e76d6f7@mail.gmail.com> References: <9afea2ac0708270941u2c9dad3eyb9877de04e76d6f7@mail.gmail.com> Message-ID: <7c1ab7e20708271202k21d34ecbl133391518392ec5d@mail.gmail.com> Ah.... "My problem is that I don't know what my active directory is so I am putting an absolute path name in quotes." import os os.getcwd() # it returns your current directory -------------- next part -------------- An HTML attachment was scrubbed... URL: From lucaberto at libero.it Fri Aug 24 10:29:05 2007 From: lucaberto at libero.it (luca72) Date: Fri, 24 Aug 2007 07:29:05 -0700 Subject: csv module Message-ID: <1187965745.959855.95530@q3g2000prf.googlegroups.com> Hello at all i have a problem with the csv module, really i don't undestud the writerows: if i have to write only one row i do as follow: def scrivo_csv(self): import csv q_righe = self.tableWidget.rowCount() for row in range(q_righe) : e_vuota = self.tableWidget.item(row, 5) if e_vuota == None : ultima = row break writerdocs = open("some.csv", "wb") scritt = csv.writer(writerdocs, delimiter='|') q_colonne = self.tableWidget.columnCount() ss = 0 while ss < row : riga = [] for val in range(q_colonne): esiste = self.tableWidget.item(ss, val) if esiste == None : luca = '' else : luca = str(QtGui.QTableWidgetItem.text(esiste)) riga.append(luca) scritt.writerow(riga) ss+=1 This work only with one row in the tablewidget, but if i have more than one row how i have to proceed? Thanks for the help Luca From stef.mientki at gmail.com Mon Aug 13 20:14:04 2007 From: stef.mientki at gmail.com (stef mientki) Date: Tue, 14 Aug 2007 02:14:04 +0200 Subject: import * is not allowed ?? Message-ID: <46C0F3CC.1050704@gmail.com> hello, can anyone explain a little bit more what this error message means: import * is not allowed in function 'JAL_MAIN_RUN' because it contains a nested function with free variables (JAL_simulation_file.py, line 22) what are "free variables" ? thanks, Stef Mientki From robert.rawlins at thinkbluemedia.co.uk Fri Aug 3 09:38:17 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 3 Aug 2007 14:38:17 +0100 Subject: File Handling & TRY/EXCEPT In-Reply-To: References: <33119.3366124809$1186129744@news.gmane.org> Message-ID: <00e001c7d5d3$8edafb00$ac90f100$@rawlins@thinkbluemedia.co.uk> Thanks for your ideas guys, I'm unfortunately tied to 2.4 so don't have the full try except status, but I'm now working with the following code: def addApp(self, event): try: logfile = open('/pblue/new/Logs/Application.csv','a') now = datetime.datetime.now() logstring = '%s,%s \n' % (event, str(now)) try: logfile.write(logstring) finally: logfile.close() except: self.addApp(event) I'm trying to slowly debug my app and get rid of all the memory leaks, but its pain staking work, any help you can offer on that stuff would be a god send, I'm a little reluctant about posting all my app code on the lists as I'd like to keep some of it private. How does that new version look? A little tidier? Thanks guys, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Steve Holden Sent: 03 August 2007 14:20 To: python-list at python.org Subject: Re: File Handling & TRY/EXCEPT Robert Rawlins - Think Blue wrote: > Hello Guys, > > > > I'm looking for some advice on how best to handle file read/write errors > with try/except as i'm a little vague on this, I have a small memory > leak in my app and I'm starting to think its generated by my log file > write. For an example of the function look below. > > > > def addAppLog(self, event): > try: > logfile = open('/pblue/new/Logs/Application.csv','a') > now = datetime.datetime.now() > logstring = '%s,%s \n' % (event, str(now)) > logfile.write(logstring) > except: > self.addAppLog(event) > It seems somewhat perverse, when the logging code raises an exception, to recursively log - presumably the same exception will be raised again? > else: > > logfile.close() > Remember that in 2.5 you can use try ... except ... finally > > Now I'm looking for some help to sort this out as I'm sure it's pretty > untidy, I want to make it as air tight as possible. The basic concept > was that if it tries writing to the log file and it fails, then it needs > to reattempt it, right? > Wrong. The one thing you can't log is a logging attempt error! > > > What's the best way to handle this to ensure that there are not any > memory leaks caused when the file is open() but not followed by a > close(). I'm running 2.4 and I know some of these newer versions don't > need you to explicitly close() the file objects, but I would certainly > feel a lot better. > > > > Any advice? > This is just a quick on-the-fly look at what you did, I am sure you will receive other, probably more helpful, comments. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- -- http://mail.python.org/mailman/listinfo/python-list From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Aug 30 07:17:11 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 30 Aug 2007 13:17:11 +0200 Subject: Python doesn't see the directories I create In-Reply-To: References: <46d6856b$0$17674$426a74cc@news.free.fr> Message-ID: <46d6a72c$0$20532$426a74cc@news.free.fr> Steve Holden a ?crit : > Bruno Desthuilliers wrote: (snip) >> You can avoid all escaping by using raw strings: >> >> mypath = r"C:\enhancement\rawfiles\" >> > Please note that the above is a well-known syntax error. A string > literal cannot end with a single backslash, as it escapes the closing > quote. oops ! My bad :( Thanks for the correction... (snip) >> Also and IIRC, using slash instead should also work, ie: >> >> mypath = r"C:/enhancement/rawfiles/" >> > That does indeed work in most situations, but ideally (i.e. for maximum > code portability) paths should be constructed using os.path.join(), or > collected from the environment somehow. Indeed. But I doubt a path starting with 'C:' will work fine on a unix-like environment anyway !-) From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Aug 2 04:38:58 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 02 Aug 2007 10:38:58 +0200 Subject: a dict trick In-Reply-To: <1186036331.304916.304020@e9g2000prf.googlegroups.com> References: <1186036331.304916.304020@e9g2000prf.googlegroups.com> Message-ID: <46b19822$0$25348$426a74cc@news.free.fr> james_027 a ?crit : > hi > > for example I have this dictionary > > dict = {'name':'james', 'language':'english'} > > value = 'sex' in dict and dict['sex'] or 'unknown' > > is a right pythonic of doing this one? No. The first problem is that using 'dict' as an identifier, you're shadowing the builtin dict type. The second problem is that you're reinventing the square wheel. > I am trying to get a value from > the dict, but if the key doesn't exist I will provide one. d = {'name':'james', 'language':'english'} d.get('sex', 'unknown') From jeremy+complangpython at jeremysanders.net Fri Aug 17 15:39:45 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Fri, 17 Aug 2007 20:39:45 +0100 Subject: best GUI library for vector drawing program References: <1187357244.883516.79840@j4g2000prf.googlegroups.com> <1187370262.861439.259680@q3g2000prf.googlegroups.com> Message-ID: chewie54 wrote: > I looked at your application, Veusz (it looks very nice), and I see > you have binary distrubitions > for each os. Is is difficult to build these binaries for each > system. Could > you tell me how that is done? I use pyinstaller to make the binaries (see the veusz_pyinst.spec file), and NSIS to make a Windows installer from the Windows binary (see veusz.nsi). The Linux binary, unfortunately, isn't 100% compatible, as I've found trying to run on 64 bit systems. I assume it's some sort of glibc mismatch. Making the linux binaries on an old distribution helps the compatibility (I use centos 3 in a virtual environment). jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From grante at visi.com Fri Aug 24 11:30:01 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 24 Aug 2007 15:30:01 -0000 Subject: Socket recv(1) seems to block instead of returning end of file. References: <13cr4u8mimniub4@corp.supernews.com> Message-ID: <13ctubpc2je3ue0@corp.supernews.com> On 2007-08-24, Hendrik van Rooyen wrote: > "Grant Edwards" wrote: > >> On 2007-08-23, Hendrik van Rooyen wrote: >> >> > While doing a netstring implementation I noticed that if you >> > build a record up using socket's recv(1), then when you close >> > the remote end down, the recv(1) hangs, >> >> I don't see that behavior running 2.4 on Gentoo. > > I express myself badly - when I say "close down" I don't mean > "close down as in socket.close" I mean "close down as in click on the > tkinter window, or with keyboard interrupt" - sorry for the confusion A FIN is a FIN is a FIN. It shouldn't matter whether the app called close() or the c library called close() or the OS called close(). >> > despite having a short time out of 0.1 set. >> >> What time out? A socket's recv method doesn't do timeouts. > > If I set a time out, then the recv does not block, > but gives me a timed out exception. My aplogies -- my question was prompted by my ignorance of the fact that a timeout feature had been added to the socket module since the last time I worked on it. > I am now frustrated - its not as simple as I thought - my > application still only detects EOF if I do more than recv(1), > but I cannot demonstrate simply - anyway, I have modified your > code to look more like my program's code, and it follows below > - if it does nothing else, it should convince you that recv() > *does* time out... Yes. > The receiver code below detects if I close the sending console window, > as well as control-c - Rats! Same here. -- Grant Edwards grante Yow! Am I having fun yet? at visi.com From S.Mientki-nospam at mailbox.kun.nl Fri Aug 3 05:45:17 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 03 Aug 2007 11:45:17 +0200 Subject: (no) fast boolean evaluation ? missing NOT In-Reply-To: <1186096979.397596.36640@e16g2000pri.googlegroups.com> References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> <1186096979.397596.36640@e16g2000pri.googlegroups.com> Message-ID: John Machin wrote: > On Aug 3, 8:55 am, Ian Clark wrote: >> Stef Mientki wrote: >>> hello, >>> I discovered that boolean evaluation in Python is done "fast" >>> (as soon as the condition is ok, the rest of the expression is ignored). >>> Is this standard behavior or is there a compiler switch to turn it on/off ? >>> thanks, >>> Stef Mientki >> It's called short circuit evaluation and as far as I know it's standard >> in most all languages. This only occurs if a conditional evaluates to >> True and the only other operators that still need to be evaluated are >> 'or's or the condition evaluates to False and all the other operators >> are 'and's. The reason is those other operators will never change the >> outcome: True or'd with any number of False's will still be True and >> False and'ed to any number of Trues will still be False. >> >> My question would be why would you *not* want this? >> >> > > Why? Perhaps under some compound condition like this: > > (you_are_confused and/or > function_returns_bool_but_has__side_effects()) > Thanks guys, Yes this is exactly what's going wrong ... Sorry, my question missed the essential "NOT", here is an example, that behaves different in Delphi, (so I guess Delphi is not a real language ;-) def Some_Function (const): print 'Ive been here', const return True A = True if A and Some_Function (4 ): print 'I knew it was True' else: print 'I''ll never print this' Ive been here 4 I knew it was True or_test ::= and_test | or_test "or" and_test >> A = 4 >>> B = 5 >>> A and B 5 >>> A & B 4 >>> A or B 4 >>> A | B 5 So if I use the bitwise operation on integers, "and" changes into (bitwise) "or" and vise versa. Is there some way to prevent / detect these kind of errors ( as I'm building a micro-controller simulator in Python, I need both logical and bitwise operators very frequently). cheers, Stef Mientki From erik at myemma.com Tue Aug 28 18:30:47 2007 From: erik at myemma.com (Erik Jones) Date: Tue, 28 Aug 2007 17:30:47 -0500 Subject: Haskell like (c:cs) syntax In-Reply-To: <4866bea60708281512q31635803x1b025274c94caf7e@mail.gmail.com> References: <4866bea60708281512q31635803x1b025274c94caf7e@mail.gmail.com> Message-ID: <16C5BEC8-3D8E-494D-B96F-04286A93EDBC@myemma.com> On Aug 28, 2007, at 5:12 PM, Chris Mellon wrote: > On 8/28/07, Stefan Niemann wrote: >> Hi, >> >> sorry that I'm relatively new to Python. But the syntax and >> semantics of >> Python already fascinate me, because I'm familiar with functional >> languages >> like Haskell. >> >> Is there a pattern matching construct in Python like (head : >> tail), meaning >> 'head' matches the first element of a list and 'tail' matches the >> rest? I >> could not find this in the Python documentation. >> >> Regards, >> Stefan >> >> > > Python does not have haskell like pattern matching. Things are written > and done in a different way. > > When working with lists, Python has a slice syntax (which is rather > more powerful than Haskells limited head->tail linked list syntax) > that you can use to chop a sequence up into various parts. That is extremely arguable (in fact, Haskell's list semantics are extremely powerful as they are not limited to just head/tail). But, rather than debate the merits of one language over the other, to the OP: no, Python doesn't have any pattern matching facilities. Binding statements must be explicit, so you could do something along the lines of (using parallel assignment): head, tail = l[0], l[1:] or, front, last = l[:len(l) - 1], l[len(l) - 1] Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From deets at nospam.web.de Fri Aug 24 09:41:54 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 24 Aug 2007 15:41:54 +0200 Subject: Unequal Length Maze In-Reply-To: <1187941996.333191.323540@z24g2000prh.googlegroups.com> References: <1187941996.333191.323540@z24g2000prh.googlegroups.com> Message-ID: <5j85h5F3t20idU1@mid.uni-berlin.de> tomtim20 at gmail.com schrieb: > Hi All, > what's the best algorithm to solve such problem ? > http://www.stetson.edu/~efriedma/unequal/ > > I will really appreciate some pieces of code (python). If you pay me 100$ (really a bargain), you get a solution in python. Diez From jensthiede at gmail.com Sat Aug 11 08:33:33 2007 From: jensthiede at gmail.com (Jens Thiede) Date: Sat, 11 Aug 2007 05:33:33 -0700 Subject: Metaclass v.s. Property function. Message-ID: <1186835613.178733.81210@q75g2000hsh.googlegroups.com> I don't like the property function, usable in the new-style classes, because having to remember to manage a list of "foo = property(...)" assignments just plain sucks, so I wrote a metaclass that does things a little differently. Please have a look and tell me whether this is useful or impractical. The metaclass is here: http://pastebin.com/m5b06b571 and some simple testcode is here: http://pastebin.com/m382f2ae9. Notice the first line though. Thanks for any replies, Jens Thiede. From steve at holdenweb.com Thu Aug 16 20:40:10 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 16 Aug 2007 20:40:10 -0400 Subject: Pass by reference or by value? In-Reply-To: <200708170120.07645.thomas@jollans.com> References: <496954360708161402x58faba47x7a6eae6e68f81d4@mail.gmail.com> <200708170120.07645.thomas@jollans.com> Message-ID: Thomas Jollans wrote: > On Thursday 16 August 2007, Robert Dailey wrote: >> Hi, >> >> I previously created a topic named "Pass by reference or by value" where I >> inquired on how python's function parameters work. I received a lot of nice >> responses, however I'm still confused on the topic. Note that I come from a >> C++ background to Python, so any comparisons to C++ would be very helpful. > > Very short answer: > > Think of normal objects as always-pointers. There are no references. param = 5 > sets the local variable "param" (be that of imaginary type int* or int, I > don't care) to whatever 5 is. This does not call an operator=, this plain > overwrites the variable. > On the contrary, objects in Python are very strictly typed, and your thinking is a little sloppy. All names and container items are references. The local variable "param" doesn't *have* a type, and can be a reference to a value of any type. You are right in saying that assignment isn't an operator in the classical sense, but don't forget that its use with qualified names (e.g. thing.attr = value) can result in calls to __setattr__(), which can be overridden under suitable circumstances. > If you want to change arguments in that way, you can use a list as an ugly > hack: > > def foo(param): > param[0] = 5 > print param[0] > > a = [4] > > foo(a) > > yeah, I said ugly. That hack makes sure that a method of the passed object is > called instead of of the local namespace dict. (please note that I'm throwing > around abstract concepts without caring about an implementation). > > Well please stop. Some of them are bound to fall, and if you damage them the PSF will have to make you pay for them. Abstract concepts don't grow on trees, you know ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From zyzhu2000 at gmail.com Wed Aug 1 09:57:36 2007 From: zyzhu2000 at gmail.com (beginner) Date: Wed, 01 Aug 2007 13:57:36 -0000 Subject: Python end of file marker similar to perl's __END__ In-Reply-To: <1185940391.135261.130950@i38g2000prf.googlegroups.com> References: <1185940391.135261.130950@i38g2000prf.googlegroups.com> Message-ID: <1185976656.753817.27980@x40g2000prg.googlegroups.com> On Jul 31, 10:53 pm, beginner wrote: > Hi All, > > This is just a very simple question about a python trick. > > In perl, I can write __END__ in a file and the perl interpreter will > ignore everything below that line. This is very handy when testing my > program. Does python have something similar? > > Thanks, > Geoffrey Thanks everyone for responding. It doesn't look like python has it. I would definitely miss it. As Steve said, the nice thing about __END__ is that things below __END__ do not have to have legit syntax. That let me focus on the lines of code I am debugging and do not have to worry about some bad syntax down the line. This feature is especially handy if I am, saying, replacing modoules or changing data structures. From tavares at fe.up.pt Thu Aug 2 09:33:51 2007 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Thu, 02 Aug 2007 06:33:51 -0700 Subject: IWCIA 08 - USA, 7-9 April 2008: Invitation Message-ID: <1186061631.031381.222330@22g2000hsm.googlegroups.com> Dear Colleague, I would like to bring to your attention information about a forthcoming conference and to strongly encourage you to submit a paper or papers to it. This is the 12th International Workshop on Combinatorial Image Analysis (IWCIA 08) which will take place in Buffalo, USA, 7-9 April 2008. Comprehensive information about the conference is available at its website http://www.cs.fredonia.edu/iwcia08 (or google IWCIA 08). >From there you will see that IWCIA 08 will be a very top conference, with distinguished keynote speakers (one of them a Nobel Laureate, the other four are of the highest possible rank and recognition as well). The proceedings will be published by Springer (LNCS) and by Taylor and Francis (for submissions to the Special Track on Applications). The extended versions of the best papers will be published in special issues of Pattern Recognition, Elsevier (for theoretical papers) and in the International Journal of Imaging Systems and Technology, Wiley (for papers of the Special Track on Applications). I am involved in the organization of the Special Track on Applications of IWCIA 08, and can assure you that it will provide the authors with an exceptional opportunity to present their work and publish it by a reputable publisher and possibly in a journal (indexed by Science Citation Index Expanded and several other indexes), to discuss topics of common interest with scientists from all over the world as well as with representatives of the industry from the US and possibly other countries. Having in mind the area of your research and experience, I would like to invite you to submit a paper (or papers) to IWCIA 08 and especially to its Special Track on Applications. I am certain that both your and the conference will benefit from your submission. Best regards, Joao Manuel R. S. Tavares (IWCIA 08 co-organizer) From __peter__ at web.de Tue Aug 14 09:20:46 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 14 Aug 2007 15:20:46 +0200 Subject: how to move cursor in Interactive Interpreter References: <1187072484.626674.157200@x40g2000prg.googlegroups.com> <1187090548.811916.124450@x40g2000prg.googlegroups.com> Message-ID: yan.python at gmail.com wrote: > what am i supposed to do to install the module GNU readline correctly > then? > by the way,my linux is Mandriva 10 Use the package manager of your distribution to install the readline development package -- after some struggle with Mandriva's website I came to suppose that it's libreadline5-devel for you: urpmi libreadline5-devel.rpm After you have successfully installed that package unpack the python archive into a fresh directory and do the configure/make/install dance. No manual changes should be necessary. Peter From pyth0nc0d3r at gmail.com Wed Aug 22 16:51:08 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Wed, 22 Aug 2007 15:51:08 -0500 Subject: Import question Message-ID: can I import more then one modules like this: import module,module2 ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Thu Aug 30 13:47:57 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Aug 2007 13:47:57 -0400 Subject: Python doesn't see the directories I create In-Reply-To: References: <46d6856b$0$17674$426a74cc@news.free.fr> Message-ID: Steve Holden wrote: [...] > The fact is that some strings are always going to cause trouble. > Unfortunately programming itself is a task that requires a little more > knowledge to be applied to the task. Just learn the rules and move on. As a quick follow-up, I had intended to comment on the usefulness of "verbatim literals". string a = "hello, world"; // hello, world string b = @"hello, world"; // hello, world string c = "hello \t world"; // hello world string d = @"hello \t world"; // hello \t world string e = "Joe said \"Hello\" to me"; // Joe said "Hello" to me string f = @"Joe said ""Hello"" to me"; // Joe said "Hello" to me string g = "\\\\server\\share\\file.txt"; // \\server\share\file.txt string h = @"\\server\share\file.txt"; // \\server\share\file.txt string i = "one\r\ntwo\r\nthree"; The @ character introduces a verbatim literal, and you can see from the examples given that they are implement a mixture of raw-string and triple-quote capabilities (even allowing multi-line string constants). I haven't fired up Visual Studio to verify, but I imagine you can even end a verbatim literal with a back-quote. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From stanc at al.com.au Tue Aug 7 00:20:21 2007 From: stanc at al.com.au (Astan Chee) Date: Tue, 07 Aug 2007 14:20:21 +1000 Subject: get position is scrolled wxScrolledWindow Message-ID: <46B7F305.7060405@al.com.au> Hi, I have a wxScrolledWindow, and some things drawn on it. I've hooked the left click event to a certain function I've got. Anyway, everytime I do a event.GetPosition() on the position of the mouse on the wxScrolledWindow, it returns the physical location or position of the mouse. Does anyone have any examples or advice on how to get the real or position of the window including where it has been scrolled? Thanks Astan From software at ginstrom.com Wed Aug 29 22:00:56 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Thu, 30 Aug 2007 11:00:56 +0900 Subject: How to use os.putenv() ? In-Reply-To: <1188436871.549201.315170@g4g2000hsf.googlegroups.com> References: <1188436871.549201.315170@g4g2000hsf.googlegroups.com> Message-ID: <02ea01c7eaa9$9ace4350$0303a8c0@MOUSE> > On Behalf Of google at tyeon.com > What am I doing wrong? How do I change the value of an > environment variable? You'll have to go through the Windows registry. Please have a look at the following recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/55993 I also have my own routines based on that for getting and setting the path: ################## import _winreg as winreg import win32gui import win32con REG_KEY_PATH = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' def set_path(pathval): """Set the PATH environment variable""" try: reg = winreg.ConnectRegistry(None, win32con.HKEY_LOCAL_MACHINE) key = winreg.OpenKey(reg, REG_KEY_PATH, 0, win32con.KEY_ALL_ACCESS) winreg.SetValueEx(key, 'path', 0, win32con.REG_EXPAND_SZ, pathval) win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment') finally: winreg.CloseKey(key) winreg.CloseKey(reg) def get_path(): """Get the PATH environment variable""" try: reg = winreg.ConnectRegistry(None, win32con.HKEY_LOCAL_MACHINE) key = winreg.OpenKey(reg, REG_KEY_PATH, 0, win32con.KEY_ALL_ACCESS) return winreg.QueryValueEx(key, 'path')[0] finally: winreg.CloseKey(key) winreg.CloseKey(reg) ################## Regards, Ryan Ginstrom From info at wingware.com Fri Aug 3 15:28:11 2007 From: info at wingware.com (Wingware) Date: Fri, 03 Aug 2007 15:28:11 -0400 Subject: Announcing Wing IDE 101 for teaching intro programming courses Message-ID: Hi, We're pleased to announce the first public beta release of Wing IDE 101, a free scaled back edition of Wing IDE that was designed for teaching introductory programming courses. We are releasing Wing IDE 101 to the general public in the hopes that it may help others teach with or learn Python. Wingware also offers educational pricing for Wing IDE Professional, including steep discounts for class room use. If you are interested in teaching Python with Wing IDE, please email support at wingware.com for more information. Key features of Wing IDE 101 include: * Powerful Editor -- Syntax highlighting, goto-definition, navigation menus, error indicators, auto-indent, and keyboard emulation for Visual Studio, VI/Vim, Emacs, and Brief. * Python Shell -- Evaluate files and selections in the integrated Python shell. * Graphical Debugger -- Set breakpoints and view stack and program data. Note that Wing IDE 101 omits auto-completion and most other code intelligence features found in the other Wing IDE products. This was by design, so that students are more conscious of the details of the language and the modules that they are learning about. Wing IDE 101 is available on Windows, Linux, and Mac OS X. It is free for all non-commercial uses and does not require a license code to run. Wing 101 is not, however, open source. The current release is 3.0 beta1 and is available here: http://wingware.com/downloads/wingide-101 General information for beta testers is here: http://wingware.com/wingide/beta More details on Wing 101's features are here: http://wingware.com/wingide-101 http://wingware.com/wingide/features Please direct bug reports and suggestions to support at wingware.com. Thanks! The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Aug 2 12:02:35 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 02 Aug 2007 18:02:35 +0200 Subject: standalone process to interact with the web In-Reply-To: <1186059016.461925.295520@e16g2000pri.googlegroups.com> References: <1185899130.331170.151980@e16g2000pri.googlegroups.com> <1185904623.754078.198910@e9g2000prf.googlegroups.com> <1185909098.952860.217190@j4g2000prf.googlegroups.com> <46b05aac$0$31743$426a74cc@news.free.fr> <1186059016.461925.295520@e16g2000pri.googlegroups.com> Message-ID: <46b20019$0$18576$426a74cc@news.free.fr> beginner a ?crit : > On Aug 1, 5:04 am, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> beginner a ?crit : >> (snip) >> >>> Yes exactly. I just don't want to reinvent the wheel as I imagine >>> there are already tons of libraries and frameworks that support RPC or >>> the like functions. >> Why go thru the pain of RPC, SOAP or such bloated horrors ? Why not just >> use plain old HTTP with a RESTful API ? Then you just need to make your >> app wsgi compliant. > > I am not familiar with RESTful API. I will look into it. > It's nothing else than the correct use of the HTTP protocol. And it's much more simpler than all those XMLRPC, SOAP and whatnot monstruosities. From michael at jedimindworks.com Thu Aug 16 23:14:31 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 16 Aug 2007 20:14:31 -0700 Subject: clarification In-Reply-To: References: Message-ID: <7659926D-6282-4FD7-9E0B-B5FE7FAF44BE@jedimindworks.com> On Aug 16, 2007, at 2:42 AM, Beema shafreen wrote: > hi every body, > i have compared two files: > code: > > fh = open('HPRD_MAIN_20.txt','r') > for line in fh.readlines(): > data = line.strip().split('#') > fh1 = open('NOMENCLATURE_MAIN_20.txt','r') > for line1 in fh1.readlines(): > data1 = line1.strip().split('#') > if data1[0] == data[0]: > result = data[0] +'#'+data[3]+'|'+ data[4] > +'|'+data[9]+'|'+ data1[3] > print result > the result was as given below: > > > 00017#ACTG1|actin, gamma 1|Actin gamma 1|ACTG > 00017#ACTG1|actin, gamma 1|Actin gamma 1|Actin gamma > 00017#ACTG1|actin, gamma 1|Actin gamma 1|Cytoskeletal gamma actin > > > but i need the result to be like this : > > > 00017#ACTG1|actin, gamma 1|Actin gamma 1|ACTG,Actin > gamma,Cytoskeletal gamma, actin > > > with out redundancy and the name in the same line separated by > commas.. > please suggest what should i do for this to get the result like this. # untested fh = open('HPRD_MAIN_20.txt','r') for line in fh.readlines(): data = line.strip().split('#') hprd = '%s#%s|%s|%s|' % (data[0], data[3], data[4], data[9]) nomenclature = [] fh1 = open('NOMENCLATURE_MAIN_20.txt','r') for line1 in fh1.readlines(): data1 = line1.strip().split('#') if data1[0] == data[0]: nomenclature.append(data1[3]) print '%s%s' % (hprd, ','.join(nomenclature)) hth, Michael --- "I would rather use Java than Perl. And I'd rather be eaten by a crocodile than use Java." ? Trouser -------------- next part -------------- An HTML attachment was scrubbed... URL: From webusa2007 at gmail.com Tue Aug 14 14:38:00 2007 From: webusa2007 at gmail.com (web24) Date: Tue, 14 Aug 2007 11:38:00 -0700 Subject: Webcool24.com : Biggest worldwide Asian free Video multi language web , Travel, Sports, Racing cars , Massages techniques, Games , Fashions, Jokes , Top models , Free online IT learning , 5000 links, 250 free online TV , 50000 music video, nice landscapes , Health , Flowers , etc ... Message-ID: <1187116680.674044.200030@l70g2000hse.googlegroups.com> Hi , I'd like to introduce you a biggest Asian free Video multi language entertainment website : http://www.webcool24.com/ Best regards. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Aug 1 08:45:13 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 01 Aug 2007 14:45:13 +0200 Subject: wxPython version question References: <1185970526.612299.277930@o61g2000hsh.googlegroups.com> Message-ID: <5hbdipF3k35tqU1@mid.individual.net> The Max wrote: > Hi have need of testing the version of wxPython in use .... at the > moment I use wxversion, but I don't can find a method for testing > version like this: > > if versionOfWX() <= 2.8: > > or > > if versionOfWX() >= 2.8: > > ( versioneOfWX is a pseudo-function create for this example ) > > Someone know a solution for this ? >>> import wx >>> wx.VERSION (2, 8, 1, 1, '') >>> Regards, Bj?rn -- BOFH excuse #298: Not enough interrupts From crobc at BOGUS.sbcglobal.net Sun Aug 19 19:20:03 2007 From: crobc at BOGUS.sbcglobal.net (CC) Date: Sun, 19 Aug 2007 16:20:03 -0700 Subject: Can I add methods to built in types with classes? Message-ID: Hi: I've gotten through most of the "9. Classes" section of the tutorial. I can deal with the syntax. I understand the gist of what it does enough that I can play with it. But am still a long way from seeing how I can use this OOP stuff. But I have one idea. Not that the functional approach isn't workable, but I have a situation where I need to test if all the characters in a string are in the set of hexadecimal digits. So I wrote: ------------------------------------------ from string import hexdigits def ishex(word): for d in word: if d not in hexdigits: return(False) else return(True) ------------------------------------------ Then I can do this to check if a string is safe to pass to the int() function without raising an exception: if ishex(string): value = int(string, 16) But can I create a class which inherits the attributes of the string class, then add a method to it called ishex()? Then I can do: if string.ishex(): value = int(string, 16) The thing is, it doesn't appear that I can get my hands on the base class definition/name for the string type to be able to do: --------------------------------------- class EnhancedString(BaseStringType): def ishex(self): for d in word: if d not in hexdigits: return(False) else return(True) --------------------------------------- Thanks. -- _____________________ Christopher R. Carlen crobc at bogus-remove-me.sbcglobal.net SuSE 9.1 Linux 2.6.5 From bj_666 at gmx.net Thu Aug 30 16:03:48 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Aug 2007 20:03:48 GMT Subject: Pivy problem and some other stuff References: <1188501707.593319.23330@m37g2000prh.googlegroups.com> Message-ID: <5jom54Fh543U2@mid.uni-berlin.de> On Thu, 30 Aug 2007 19:21:47 +0000, azrael wrote: > And there is anoher question in my mind. > Is there a way to make a list in python which contains a series of > functions. I did'n try it. Something like: Why don't you just try!? >>>>def a(): >>>> return 1 > >>>>def b(): >>>> return 2 > >>>>def c(): >>>> return 3 > >>>>def d(): >>>> return 4 > >>>> list=[a(),b(),c(),d()] >>>> list > [1,2,3,4] This isn't a list of functions but a list of results of function calls. If you want the functions in that list then leave off the parentheses, because those are the "call operator". In [55]: def a(): ....: return 1 ....: In [56]: def b(): ....: return 2 ....: In [57]: funcs = [a, b] In [58]: funcs Out[58]: [, ] In [59]: funcs[0]() Out[59]: 1 In [60]: funcs[1]() Out[60]: 2 Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Tue Aug 14 19:30:01 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 14 Aug 2007 19:30:01 -0400 Subject: chmod g+ Equivalent In-Reply-To: <1187094251.540591.308320@g4g2000hsf.googlegroups.com> References: <1187042290.821786.178420@19g2000hsx.googlegroups.com> <1187094251.540591.308320@g4g2000hsf.googlegroups.com> Message-ID: <46C23AF9.3020107@holdenweb.com> milan_sanremo wrote: > On Aug 13, 8:06 pm, Steve Holden wrote: >> milan_sanremo wrote: >>> I've read the documentation on os.chmod() and can implement all the >>> standard commands, but what is the syntax for the equivalent of chmod g >>> + to set the group id? >> I assume when you say "to set the group id" you actually mean "to assert >> the setgid bit"? I further presume that when you say "chmod g+" you >> actually mean "chmod g+s". > > The g+s was an omission on my part. I can see how it would confuse > the issue. > > I'm not sure if I mean "to assert the setgid bit". My SUN docs refer > to it being 'on'. > http://docs.sun.com/app/docs/doc/819-3321/6n5i4b767?l=en&a=view&q=setgid+bit > >> You can't have read the documentation very thoroughly. It says right at >> the top: >> >> S_ISUID >> S_ISGID > > I did see this in the documentation: > > Change the mode of path to the numeric mode. mode may take one of the > following values (as defined in the stat module) or bitwise or-ed > combinations of them: > > * S_ISUID > * S_ISGID > > Which refers to: > http://docs.python.org/lib/module-stat.html > > After which it was still unclear. > > My question is in the command os.chmod(myDirectory, ?) what is the > value for ? to turn on the setgid bit. > > Contrary to your presumption, I did read the documentation > thoroughly. It is inability to understand the concept which prompted > me to post the question here. > Well, you don't tell us what (if anything) you have tried so far. Python has an interpreter that's very easy to use interactively. Why don't you try os.chmod(my_directory, os.S_ISGID) and see if it does what you want? You can often save time by trying such things for yourself. Though it needn't be a substitute for asking questions on this list, it can make your questions better-informed. In this particular case, now I understand your needs a little better, since you want to *add* a bit setting you will likely have to use something like current_permissions = os.fstat(my_directory).ST_MODE to read the directory's current permission bits. Then you will need to execute os.chmod(my_directory, current_permissions | stat.S_ISGID) Please don't take this as gospel, though, as I am currently on the road with only a Windows computer available, but I think it should get you closer to where you want to be. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From hadronquark at googlemail.com Thu Aug 2 06:49:32 2007 From: hadronquark at googlemail.com (Hadron) Date: Thu, 02 Aug 2007 12:49:32 +0200 Subject: Emacs + python References: Message-ID: Edward O'Connor writes: >> Could anyone put me on the right track to developing Python with emacs >> please : modes to consider, debugging etc hopefully all within emacs. > > Personally, I prefer the python.el that ships with Emacs 22 to the > python-mode.el from python.org. It seems more like other Emacs major > modes. > > > Ted Could you extrapolate a little more on what you see as the differences? I addition, I run pdb under emacs and the GUD menu appears but I cant set break points by clicking in the left column of the source display. Is there a way to get this working? From dickinsm at gmail.com Fri Aug 24 22:03:39 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 25 Aug 2007 02:03:39 -0000 Subject: Does shuffle() produce uniform result ? In-Reply-To: <1188005414.717674.320500@x40g2000prg.googlegroups.com> References: <878x81rt3d.fsf@mulj.homelinux.net> <1188005414.717674.320500@x40g2000prg.googlegroups.com> Message-ID: <1188007419.017370.72380@e9g2000prf.googlegroups.com> On Aug 24, 9:30 pm, Mark Dickinson wrote: > x = floor((n/2**53)*7) > > will produce 0, 1, 3 and 5 with probability (2**53//7+1)/2**53, and 2, > 4 and 6 with probability (2**53//7)/2*53. Oops---I lied; I forgot to take into account the rounding implicit in the (n/2**53)*7 multiplication. A bit of experimentation shows that it's 0, 2, 4 and 6 that occur more often, with 1, 3 and 5 less likely by a miniscule amount (at least on an IEEE-754 system). Mark From rpw3 at rpw3.org Mon Aug 20 01:25:26 2007 From: rpw3 at rpw3.org (Rob Warnock) Date: Mon, 20 Aug 2007 00:25:26 -0500 Subject: Xah's Edu Corner: Under the spell of Leibniz's dream References: <1187567809.896668.228650@z24g2000prh.googlegroups.com> <1187578927.945921.280180@q4g2000prc.googlegroups.com> Message-ID: <4ZKdnQVa65RbuFTbnZ2dnUVZ_qKgnZ2d@speakeasy.net> Twisted wrote: +--------------- | > "Under the spell of Leibniz's dream" (2000) By Edsger W | > Dijkstrahttp://www.cs.utexas.edu/~EWD/ewd12xx/EWD1298.PDF | | A link to a copy in a non-toxic format would be nice. +--------------- Well, the fact of the matter is that the bulk of Dijkstra's "EWD" papers were written *long* before the web existed, typed on a favorite manual typewriter which he continued using for the remainder of his professional life. has more details on the more than one thousand "EWD"s he wrote. Until very recently, the *only* source for these documents was either in hardback technical books (for the few that were published) or in the PDF bitmaps of scans of the original manually-typed pages, which the University of Texas at Austin has generously made [and even after Dijkstra's death continues to make] available on-line. However, a *few* but "growing number of the PDF bitmap documents have been transcribed to make them searchable and accessible to visitors who are visually impaired." If you would care to volunteer [as over sixty others have done] to contribute to the transcriptions, see . Otherwise, just count your blessings that these gems are available at all... -Rob ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From Astley.lejasper at gmail.com Tue Aug 28 06:09:15 2007 From: Astley.lejasper at gmail.com (Astley.lejasper at gmail.com) Date: Tue, 28 Aug 2007 10:09:15 -0000 Subject: National grid to lat long conversion Message-ID: <1188295755.877801.217710@r29g2000hsg.googlegroups.com> Hi, I have a load of British National Grid references that I want to convert to decimal degrees so I can create a google KML file. Does anyone know of a module to do this? I've looked at http://pygps.org/#LatLongUTMconversion but am not really up to speed with projections and all this other mapping stuff. I want to take something like x = 417512 y = 315098 (SK 17570 15100) and convert it to a google compatible decimal degrees lat: 52.733255N Long: -1.741239 Any help would be great From nospam at invalid.com Sun Aug 26 19:12:11 2007 From: nospam at invalid.com (Jack) Date: Sun, 26 Aug 2007 16:12:11 -0700 Subject: Parser Generator? References: <_6mdnZxbdNKTVFrbnZ2dnUVZ_tqtnZ2d@comcast.com> <1188003076.702532.241950@q3g2000prf.googlegroups.com> Message-ID: Good to know, thanks Paul. ! "Paul McGuire" wrote in message > Pyparsing was already mentioned once on this thread. Here is an > application using pyparsing that parses Chinese characters to convert > to English Python. > > http://pypi.python.org/pypi/zhpy/0.5 > > -- Paul From nitro at dr-code.org Mon Aug 6 09:37:26 2007 From: nitro at dr-code.org (Nitro) Date: Mon, 06 Aug 2007 15:37:26 +0200 Subject: Scope question Message-ID: Thanks a lot for clearing this up, Diez! -Matthias From gagsl-py2 at yahoo.com.ar Sun Aug 19 15:13:15 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 19 Aug 2007 12:13:15 -0700 Subject: How to make a module function visible only inside the module? In-Reply-To: <1187488017.198905.242610@j4g2000prf.googlegroups.com> References: <1187484334.091530.90420@m37g2000prh.googlegroups.com> <1i32pg7.b0y3h92vjygwN%raims@dot.com> <1187488017.198905.242610@j4g2000prf.googlegroups.com> Message-ID: <1187550795.085091.162400@57g2000hsv.googlegroups.com> On 18 ago, 22:46, beginner wrote: > On Aug 18, 8:27 pm, ra... at dot.com (Lawrence Oluyede) wrote: > > beginner wrote: > > > Is there any equivalent version of C's static function in Python. I > > > know I can make a class function private by starting a function name > > > with two underscores, but it does not work with module functions. > > > For exmaple, __func1 is still visible outside the module. > > > Yes, and _f() will also be. There's no such thing as enforcing > > encapsulation in Python, even the "__method()" trick can be easily > > bypassed if you have to. > > Thanks a lot. I was using two underscores, __module_method() as my > static method convention, and then I had some problems calling them > from inside class methods.- Ocultar texto de la cita - The convention is to use a single leading underscore _f to indicate private things. When you see something like: from some_module import _function you know you are messing with internal stuff. There is another form of import: from some_module import * that will import all public names defined in some_module, into the current namespace. By default, the public names are all names not beginning with "_" - but you can customize it defining __all__ which must be the list of public names. (Note that this form of import is strongly discouraged). For more info, see the Reference Manual: -- Gabriel Genellina From glenn.chappell at gmail.com Fri Aug 10 21:42:47 2007 From: glenn.chappell at gmail.com (glenn.chappell at gmail.com) Date: Sat, 11 Aug 2007 01:42:47 -0000 Subject: wxPython - drawing without paint event In-Reply-To: <1186738813.373909.96230@x35g2000prf.googlegroups.com> References: <1186710391.148396.113490@d30g2000prg.googlegroups.com> <1186738813.373909.96230@x35g2000prf.googlegroups.com> Message-ID: <1186796567.331348.42450@q3g2000prf.googlegroups.com> On Aug 10, 1:40 am, 7stud wrote: > On Aug 9, 7:46 pm, Matt Bitten wrote: > > > I've got a wxPython program that needs to do some drawing on a DC on a > > regular basis.... And there is no event, > > so my code doesn't get called. What do I do? > > Then the event is: "on a regular basis", i.e. the passage of time. > You can use a wx.Timer to create events at regular intervals, which > your code can respond to: > ... Thanks! On a related topic, it seems like it would be nice to do *all* drawing in response to paint events. When I get an event from the timer, I would just tell wx that part of the window needs redrawing, and depend on it to give me a paint even when nothing of higher priority needs to be done. I've seen this kind of logic recommended in other GUI tookits. Is it a good idea in wxPython, and, if so, how does one do it? From rdm at rcblue.com Wed Aug 8 14:20:56 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 08 Aug 2007 11:20:56 -0700 Subject: WinPdb? Message-ID: <20070808182108.C857D1E4007@bag.python.org> An HTML attachment was scrubbed... URL: From hat at se-162.se.wtb.tue.nl Mon Aug 20 08:39:45 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Mon, 20 Aug 2007 14:39:45 +0200 Subject: desperately in need of a tool References: <1187560418.339131.283470@i38g2000prf.googlegroups.com> Message-ID: On 2007-08-19, yagyala wrote: > Hi. > > one of those standards is that the comments for each routine must > indicate every other routine that it calls. As I try to keep my > to do this by hand. Does anyone know of a tool that could do this for > me, or at least a tool that can tell what other routines a given > routine calls that I could program against? (Preferably something that > works under pydev, but I'm not going to be choosy.) Wouldn't a regular expression be enough here? Something like # x.py import re, sys fcallpat = re.compile(r'\w+\(') data = sys.stdin.read() for match in fcallpat.findall(data): print match $ python x.py < x.py compile( read( findall( You may want to have a wider matching criterium than \w+ Albert From jstroud at mbi.ucla.edu Sun Aug 26 18:59:47 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 26 Aug 2007 22:59:47 GMT Subject: YOU MUST KNOW THIS MAN In-Reply-To: <1188153967.206797.224850@d55g2000hsg.googlegroups.com> References: <1188153967.206797.224850@d55g2000hsg.googlegroups.com> Message-ID: Would Muhammad, peace and blessings be upon him, want his followers to kill in his name? I know that other prophets would not. From pyscottishguy at hotmail.com Tue Aug 14 22:30:44 2007 From: pyscottishguy at hotmail.com (pyscottishguy at hotmail.com) Date: Tue, 14 Aug 2007 19:30:44 -0700 Subject: creating and appending to a dictionary of a list of lists Message-ID: <1187145044.394889.312590@x35g2000prf.googlegroups.com> Hey, I started with this: factByClass = {} def update(key, x0, x1, x2, x3): x = factByClass.setdefault(key, [ [], [], [], [] ]) x[0].append(x0) x[1].append(x1) x[2].append(x2) x[3].append(x3) update('one', 1, 2, 3, 4) update('one', 5, 6, 7, 8) update('two', 9, 10, 11, 12) print factByClass {'two': [[9], [10], [11], [12]], 'one': [[1, 5], [2, 6], [3, 7], [4, 8]]} I then 'upgraded' to this: def update(key, *args): x = factByClass.setdefault(key, [[], [], [], [] ]) for i, v in enumerate(args): x[i].append(v) Is there a better way? Cheers! From kyosohma at gmail.com Wed Aug 15 17:05:48 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 15 Aug 2007 14:05:48 -0700 Subject: Move files/directories to Recycle Bin using standard Python libs In-Reply-To: References: Message-ID: <1187211948.913922.197830@m37g2000prh.googlegroups.com> On Aug 15, 2:55 pm, Kevin D. Smith wrote: > On 2007-08-15 13:02:24 -0600, "Chris Mellon" said: > > > Not easily. The recycle bin is part of the shell, and the shell api > > calls have very complicated struct parameters that are cumbersome to > > use correctly from ctypes. If you do the work to map the fileop > > structs to ctypes you can call the shell API file operation functions > > in shell32.dll. This assumes that "standard" for you is Python 2.5, > > which has ctypes. Otherwise you are out of luck. > > Unfortunately, I need this to work on Python 2.4 as well... > > -- > Kevin D. Smith As I mentioned in my previous post, you can download ctypes from sourceforge for 2.4. Mike From info at wingware.com Fri Aug 3 15:28:11 2007 From: info at wingware.com (Wingware) Date: Fri, 03 Aug 2007 15:28:11 -0400 Subject: Announcing Wing IDE 101 for teaching intro programming courses Message-ID: <46B381CB.5000800@wingware.com> Hi, We're pleased to announce the first public beta release of Wing IDE 101, a free scaled back edition of Wing IDE that was designed for teaching introductory programming courses. We are releasing Wing IDE 101 to the general public in the hopes that it may help others teach with or learn Python. Wingware also offers educational pricing for Wing IDE Professional, including steep discounts for class room use. If you are interested in teaching Python with Wing IDE, please email support at wingware.com for more information. Key features of Wing IDE 101 include: * Powerful Editor -- Syntax highlighting, goto-definition, navigation menus, error indicators, auto-indent, and keyboard emulation for Visual Studio, VI/Vim, Emacs, and Brief. * Python Shell -- Evaluate files and selections in the integrated Python shell. * Graphical Debugger -- Set breakpoints and view stack and program data. Note that Wing IDE 101 omits auto-completion and most other code intelligence features found in the other Wing IDE products. This was by design, so that students are more conscious of the details of the language and the modules that they are learning about. Wing IDE 101 is available on Windows, Linux, and Mac OS X. It is free for all non-commercial uses and does not require a license code to run. Wing 101 is not, however, open source. The current release is 3.0 beta1 and is available here: http://wingware.com/downloads/wingide-101 General information for beta testers is here: http://wingware.com/wingide/beta More details on Wing 101's features are here: http://wingware.com/wingide-101 http://wingware.com/wingide/features Please direct bug reports and suggestions to support at wingware.com. Thanks! The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From uymqlp502 at sneakemail.com Thu Aug 30 19:37:30 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Thu, 30 Aug 2007 16:37:30 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <46d75116$0$401$426a74cc@news.free.fr> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> <1188430887.481586.106760@l22g2000prc.googlegroups.com> <1188504811.019632.186580@x35g2000prf.googlegroups.com> <46d75116$0$401$426a74cc@news.free.fr> Message-ID: <1188517050.174081.265900@x40g2000prg.googlegroups.com> Bruno Desthuilliers wrote: > Russ a ?crit : > (snip) > > > I don't see how you can avoid adding some new syntax, given that > > Python does not > > currently have syntax for specifying invariants and pre- and post- > > conditions. > > class Parrot(object): > @pre(lambda x : x != 42) > @post(lambda result: result != 42) > @invariant(lambda self: self.x == 42) > def reliable_method(self, x): > # your code here > return something That looks like new syntax to me. Did I miss your point? I have no strong leaning about what the exact syntax should be for programming by contract. The syntax you show above seems reasonable, except that I am not sure about requiring that everything be put inside parentheses. That seems a bit confining for more complex conditions. From cbarton at metavr.com Fri Aug 10 05:54:58 2007 From: cbarton at metavr.com (Campbell Barton) Date: Fri, 10 Aug 2007 19:54:58 +1000 Subject: Deleting objects on the fly In-Reply-To: <1186723571.250731.65040@q3g2000prf.googlegroups.com> References: <1186705500.227658.163170@q3g2000prf.googlegroups.com> <1186723571.250731.65040@q3g2000prf.googlegroups.com> Message-ID: <46BC35F2.4070600@metavr.com> Michele Simionato wrote: > On Aug 10, 2:25 am, Godzilla wrote: >> Hello, >> >> I wish to know whether I should delete objects created on the fly via >> the "del obj" statement. I noticed the RAM usage increased whenever >> the application is being run for a long time. I am creating lots of >> objects (messages) on the fly for communication between threads. >> >> Rather than having python's gc to do the work, does it make a >> difference if I force a deletion? >> >> Thanks. > > Probably not, 'del x' just decrements the reference count, but > it is the gc who does the real job. See http://docs.python.org/ref/customization.html#l2h-175 > > Do you have reference cycles in your application? You should > tell us something more. > > Michele Simionato > del x will remove x from memory if nothing else is refering to it, but this dosnt really take the load off the GC since the GC will still check the references and remove if there are none. In some cases you could use to save ram... a = 'really big string' ...do stuff with a... del a b = 'another really big string' ...do stuff with b... del b in the case that 'a' is not needed, after its used, and you dont want to re-use the variable name. then del will free some ram since they both wont need to exist at the same time. WHen I say free ram, python its self will probably keep the ram for later use but at least it wont need a and b in memory at once, so its likely not to use as much ram. But be careful using del in a loop since it can slow things down, its like adding and removing an item from a dictionary many times. your better off just redefining that variable or using del after the loops finished. From siddharthamca at yahoo.co.in Fri Aug 31 04:37:45 2007 From: siddharthamca at yahoo.co.in (siddhatha veedaluru) Date: Fri, 31 Aug 2007 14:07:45 +0530 (IST) Subject: Do you have any complete example for creating msi file(doing file copying) Message-ID: <103056.29674.qm@web7605.mail.in.yahoo.com> Thank you for the help that you are going to give me. I have a project where in which i want to create a msi file just as python-package while installing python on the system. Just copying the files to the user given target directory. i want to create similar msi file for my project that just copies the file. Can you please help me in providing the complete procedure of creating the msi file using the python. Does msilib library in the release 2.5 have this capability? Please help me Thanks Sid Get the freedom to save as many mails as you wish. Click here to know how. Once upon a time there was 1 GB storage in your inbox. To know the happy ending go to http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From hwg434 at yahoo.com Tue Aug 28 22:43:15 2007 From: hwg434 at yahoo.com (hwg) Date: Tue, 28 Aug 2007 19:43:15 -0700 Subject: Newbie question - sorting a slice Message-ID: <1188355395.424913.90480@19g2000hsx.googlegroups.com> I've searched the group and didn't see the answer to this... Why doesn't this work?: >>> letters = ['d', 'a', 'e', 'c', 'b'] >>> letters[1:3].sort() >>> This returns None. Why? letters[1:3] is ['a', 'e', 'c'] Sorting that should return ['a', 'c', 'e'] hwg From Junkeun.park at gmail.com Tue Aug 28 00:46:45 2007 From: Junkeun.park at gmail.com (Jun-geun Park) Date: Tue, 28 Aug 2007 00:46:45 -0400 Subject: Biased random? In-Reply-To: References: Message-ID: <46d3a8b5$0$478$b45e6eb0@senator-bedfellow.mit.edu> Jun-geun Park wrote: > Ivan Voras wrote: >> Hi, >> >> I have a list of items, and need to choose several elements from it, >> "almost random". The catch is that the elements from the beginning >> should have more chance of being selected than those at the end (how >> much more? I don't care how the "envelope" of probability looks like at >> this point - can be linear). I see that there are several functions in >> Python standard libraries for various distribution, but is there an easy >> pythonic way to make them do what I need? >> >> > > That's weird. random.randint(a,b) will be enough for most cases. Test > your system to see the distribution is uniform with something like: > > ---- > import random > > dist = {} > for z in xrange(100000): > u = random.randint(1,10) > try: > dist[u] = dist[u] + 1 > except KeyError: > dist[u] = 1 > > print dist > ---- I understood the question wrong.(Thanks, Grant and Robert.) To get the linear distribution, you can start from the following: a = (random.random() + random.random())/2.0 # Triangle distribution in [0,1) b = random.random() # Uniform in [0,1) c = b + (1-b)*a # Convolution u = int(100*(1-c)+1) # ceil(100*(1-c)) , then, because convolution of a rectangle function and a triangle function is a linear function under the valid domain, u is a random integer in [1,100] that follows (decreasing) linear distribution. Alternatively if I were in your case, I would go with an exponential random with a suitable lambda(by cutting its tail.) From jstroud at mbi.ucla.edu Fri Aug 17 17:49:03 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 17 Aug 2007 14:49:03 -0700 Subject: Python and Tkinter Programming--Expensive! In-Reply-To: References: Message-ID: W. Watson wrote: > Why is the book in Subject (author is Grayson) so expensive? $100 on > Amazon and $195 on ABE. Aren't there alternatives? Read the fine print. Its available as an ebook for about $25.00 at Manning. You can print out just the parts you need--or read it from your iphone. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From rozniy at gmail.com Tue Aug 7 00:57:19 2007 From: rozniy at gmail.com (rozniy) Date: Tue, 07 Aug 2007 04:57:19 -0000 Subject: How to use C enum in Python CTypes? Message-ID: <1186462639.872254.25660@z24g2000prh.googlegroups.com> I am using Python's CTypes module to import functions from a DLL into Python. Some of the DLL's functions take enum type arguments, eg: olDaGetDASS (HDEV hDev, OLSS OlSs, UINT uiElement, PHDASS phDass); //(this function is in C form) >From the header file, I found that type OLSS is an enum, like this: typedef enum olss_tag { OLSS_AD, OLSS_DA, OLSS_DIN, OLSS_DOUT, OLSS_SRL, OLSS_CT } OLSS; I managed to fudge the HDEV, UINT and PHDASS types as CTypes c_long(), but I am not sure how translate a C enum into Python... This site http://python.net/crew/theller/ctypes/tutorial.html#bugs-todo-and-non-implemented-things says that enumeration types is not implemented, "Enumeration types are not implemented. You can do it easily yourself, using c_int as the base class." How do I do this? I am fairly new to Python, coming in from C++ (of which I am utterly sick!) From vinay_sajip at yahoo.co.uk Mon Aug 13 08:25:36 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Mon, 13 Aug 2007 12:25:36 -0000 Subject: Extending logging module In-Reply-To: <1186675688.291944.299060@z24g2000prh.googlegroups.com> References: <1186675688.291944.299060@z24g2000prh.googlegroups.com> Message-ID: <1187007936.316025.168250@i13g2000prf.googlegroups.com> On Aug 9, 9:08 pm, jay wrote: > It actually worked, but this is not the way I would like to handle the > problem. I would prefer to extend the classes instead. However, I'm > not too familiar with that, and I had to change things in so many > places, I'm wondering if its even possible? I don't like changing the > standard libraries, what happens if I have to upgrade python? My > changes get overwritten. > > Can anyone offer some help or suggestions? Thanks > Where's the difficulty in extending the SyslogHandler class? Simply override the methods you need to provide the behaviour you want, then use your handler instead of the standard SyslogHandler. I'm travelling at the moment and cannot post a working example, but it should be easy enough to do. It's just the same as extending any other Python class - but remember to call the base class's __init__ from your own __init__, if you provide one. Best regards, Vinay Sajip From debl2NoSpam at verizon.net Fri Aug 31 22:06:15 2007 From: debl2NoSpam at verizon.net (David Lees) Date: Sat, 01 Sep 2007 02:06:15 GMT Subject: HowTo Use Cython on a Windows XP Box? Message-ID: August 31, 2007 I just downloaded the current Cython release and have no problem running the cpython.py translator on the demo code. But when I try compiling, I get an error complaining that my version of Python (which is the current 2.5.1 downloaded from python.org) was compiled with Visual C++ 2003. I only have Visual C++ 2005 on my machine and am unable to find a download of 2003 on the Microsoft site (no big surprise). I have never built Python from source. Is it necessary or can someone suggest an alternative? TIA david lees From nospam.themindstorm at gmail.com Sat Aug 4 19:25:16 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Sat, 4 Aug 2007 23:25:16 +0000 (UTC) Subject: how to run os.execv() to run command pslq dbname < gen.command References: <1186229986.707259.323130@19g2000hsx.googlegroups.com> Message-ID: Steve Holden wrote in news:f91uju$130$1 at sea.gmane.org: > Sonu wrote: >> hello all , >> > I want to watch my TV, but it's not working. Can you tell me how to > fix it? ... > I can help you... but only with a couple of channels :-). >> i need to run psql from my py file,, >> for that i am using : os.execv(path for psql ,['psql dbname < >> gen.command']) >> but its not working .......... I assume the problem relies in the execution pathes, but as Steve has mentioned: without further details nobody will be able to help you. ./alex -- .w( the_mindstorm )p. From geoff.bache at pobox.com Tue Aug 28 14:13:18 2007 From: geoff.bache at pobox.com (geoffbache) Date: Tue, 28 Aug 2007 11:13:18 -0700 Subject: Getting subprocesses to be hidden on Windows In-Reply-To: References: <1188246076.131276.292010@r34g2000hsd.googlegroups.com> Message-ID: <1188324798.742700.173970@w3g2000hsg.googlegroups.com> On 28 Aug, 18:18, Larry Bates wrote: > geoffbache wrote: > > Hi, > > > As part of my efforts to write a test tool that copes with GUIs > > nicely, I'm trying to establish how I can start a GUI process on > > Windows that will not bring up the window. So I try to hide the window > > as follows: > > > info = subprocess.STARTUPINFO() > > info.dwFlags |= subprocess.STARTF_USESHOWWINDOW > > info.wShowWindow = subprocess.SW_HIDE > > > proc = subprocess.Popen(..., startupinfo=info) > > > This works, in a way, but doesn't work recursively. I.e. if the > > started process itself starts a window, that second window will not be > > hidden. This even applies to dialog boxes within the application. So > > instead of a lot of windows popping up I now get a lot of disembodied > > dialogs appearing, which is a slight improvement but not much. > > > Also, certain processes (e.g. tkdiff) seem to ignore the directive to > > be hidden altogether. > > > This is dead easy on UNIX with virtual displays like Xvfb. Can someone > > shed any light if it's possible on Windows from python? > > > Regards, > > Geoff Bache > > While I'm not entirely sure I understand what you want, I think you can > accomplish it by using win32CreateProcess instead of subprocess. You can run > the application minimized or perhaps in a REALLY small window. If you have > modal dialog boxes, I don't think you can do anything as they don't run in the > parent windows frame but rather outside (I could be wrong about this). > > -Larry Hi Larry, I don't know if that would help. I've tried running minimized from the command line as suggested by Mike and that has the same issue (child windows and dialogs don't get minimized) So the question is moving away from how to technically achieve this in Python to whether Windows even supports it... Geoff From andmart at gmail.com Thu Aug 9 09:51:52 2007 From: andmart at gmail.com (=?ISO-8859-1?Q?Andr=E9_Martins?=) Date: Thu, 9 Aug 2007 10:51:52 -0300 Subject: tests In-Reply-To: References: <1186666919.456036.120270@d30g2000prg.googlegroups.com> Message-ID: Generate a hash of two files and compare -------------- next part -------------- An HTML attachment was scrubbed... URL: From max at alcyone.com Sun Aug 12 22:25:19 2007 From: max at alcyone.com (Erik Max Francis) Date: Sun, 12 Aug 2007 19:25:19 -0700 Subject: Fatest standard way to sum bytes (and their squares)? In-Reply-To: References: Message-ID: Duncan Booth wrote: > I haven't timed it, but at the very least I'd avoid going through all the > data twice: > > count = {} > for i in range(256): > count[chr(i)] = 0 > for x in data: > count[x] += 1 > > ordinalSum = sum(ord(c)*count[c] for c in count) > ordinalSumSquared = sum(ord(c)**2 * count[c] for c in count) This approach is definitely faster than using a generator in my tests, and was second fastest overall. I'm actually a bit surprised that it's as fast as it is; it never would have occurred to me to try it this way. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis It is morale that wins the victory. -- Gen. George C. Marshall From wildemar at freakmail.de Fri Aug 24 12:28:35 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 24 Aug 2007 18:28:35 +0200 Subject: Steve Holden is a moronic, self-indulgent BASTARD [WAS: Re: creating a tar file with python] In-Reply-To: <1187970552.537218.202160@x35g2000prf.googlegroups.com> References: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> <93066C069973ED448DC2BCEA9C44A7383BE2ED@efmailx> <46CE4D3D.7020106@holdenweb.com> <93066C069973ED448DC2BCEA9C44A7383BE2EE@efmailx> <1187969070.3385.20.camel@dot.uniqsys.com> <1187970552.537218.202160@x35g2000prf.googlegroups.com> Message-ID: <46CF0733.3040508@freakmail.de> kyosohma at gmail.com wrote: > I like Steve, but he seems pretty crabby/rude much of the time. > Now what is going on here? I've been on this list for quite some time now and over all of Steves very frequent posts this is the first thread that I recall in which he sort of snapped. All of the other times he managed insults with admirable grace (How's that for fan-mail? ;)). And his tone is usually much milder than that of most other regulars here (all of whom are very friendly albeit the concise, technical manner of communication, sprinkled of course with the occasional sarcastic remark). Steve, you might want to consider becoming more rude in your communication style; that way you don't get flamed for that *one time* you actually loose your cool. ;) Rhetorical closing-questions: Do people start flame wars like this so easily in the real world as well? Why do internet-discussions tend to burst into all-out battles so quickly? Why do people on the net tend to forget that a 1--10 scale actually contains 2--9? *sigh* /W From cpmishra.20 at gmail.com Thu Aug 2 02:37:58 2007 From: cpmishra.20 at gmail.com (cpmishra) Date: Thu, 02 Aug 2007 06:37:58 -0000 Subject: No module named DBUtils.PooledDB Message-ID: <1186036678.623372.221890@w3g2000hsg.googlegroups.com> Hi all I have used DBUtil with python2.4. when we run to program in dos command ,successfully run but when we run in apache server (locally)with modepython then given error.Pls help me error: No module named DBUtils.PooledDB cp mishra From ricaraoz at gmail.com Wed Aug 29 08:12:19 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 29 Aug 2007 09:12:19 -0300 Subject: Haskell like (c:cs) syntax In-Reply-To: References: Message-ID: <46D562A3.6030505@bigfoot.com> Marco Mariani wrote: > Ricardo Ar?oz ha scritto: > >> L = ['one', 'two', 'three', 'four', 'five'] >> >> print L[0] # This would be 'head' >> print L[1:] # This would be 'tail' >> >> Caution : L[0] and L[1:] are COPIES of the head and tail of the list. > > This might surprise people who see L[1:] = [], since changing a copy is > not supposed to change the original. > Sorry, should have written RETURN copies instead of ARE copies. From rcdailey at gmail.com Sun Aug 12 22:58:41 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Sun, 12 Aug 2007 21:58:41 -0500 Subject: Python script for mobile platforms -- suggested? Message-ID: <496954360708121958m170b6cd2j8419802dcdd35482@mail.gmail.com> Hi, I'm currently developing a game for a cell phone. The game has a GUI system that's currently using XML to define the individual menus. Basically this means that for every single menu the user goes to, it loads and parses an XML file. Would using Python Script instead of XML be a reasonable replacement, or would it be even slower? I've read various articles online but I'm still curious to hear what everyone has to say here. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fabioztessitore at libero.it Tue Aug 28 14:45:12 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 28 Aug 2007 18:45:12 GMT Subject: localhost, ?! References: Message-ID: <46d46d38$0$37200$4fafbaef@reader3.news.tin.it> Il Tue, 28 Aug 2007 18:27:31 +0200, Boris Ozegovic ha scritto: > Three machines, one at my home, other two at my job, in every machine > there is Win XP SP2 and Python 2.5 > > At home: > urllib2.urlopen("http://localhost"), everything is ok > > At job: > urllib2.urlopen("http://localhost") > raise BadStatusLine(line), after half a minute. > > urllib2.urlopen("http://127.0.0.1") > HTTP Error 503: Service Unavailable, immediately. > > Anybody have slightest clue wthat is going on? :-/ I think to have http://localhost working you need a web server (like apache). maybe you have it at your home. bye Fabio From vasudevram at gmail.com Fri Aug 24 12:56:25 2007 From: vasudevram at gmail.com (vasudevram) Date: Fri, 24 Aug 2007 16:56:25 -0000 Subject: How would I compile a Python file to a exe In-Reply-To: References: Message-ID: <1187974585.362430.272470@m37g2000prh.googlegroups.com> On Aug 24, 2:11 am, Charlie wrote: > Quoting Lamonte Harris : > > > Been a while and I'm wondering how I would go about doing it. > > py2exe seems to be a fairly good option for this, at least in the > world of Windows. Yes, py2exe looks good. I've tried it out. Make sure to test for the cases you'll need, though. - Vasudev ----------------------------------------- Vasudev Ram http://www.dancingbison.com http://jugad.livejournal.com http://sourceforge.net/projects/xtopdf ----------------------------------------- From dorjetarap at googlemail.com Sat Aug 18 14:43:13 2007 From: dorjetarap at googlemail.com (dorje tarap) Date: Sat, 18 Aug 2007 19:43:13 +0100 Subject: creating weblogo-like .png output Message-ID: Hi, For the new program I am creating I want to display some data in a format similar to weblogo. Basically I want to create .png output of a table I have that shows percentage of DNA. There is a python implementation for this, but I can only seem to install it under linux and I want to make this in xp so I can use the psyco module. Also the weblogo version contains a lot more complexity than I need. Any points to tutorials, or other advice would be helpful. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From s.rappard at gmail.com Fri Aug 31 03:55:39 2007 From: s.rappard at gmail.com (Sjoerd) Date: Fri, 31 Aug 2007 07:55:39 -0000 Subject: MySQLdb ImportError Message-ID: <1188546939.086855.204670@q5g2000prf.googlegroups.com> Hello! When I try to import the MySQLdb lib python generates an error: Traceback (most recent call last): File "", line 1, in import MySQLdb File "C:\Python25\lib\site-packages\MySQLdb\__init__.py", line 19, in import _mysql ImportError: DLL load failed with error code 193 This is on a AMD64 bit machine, when I import it on a 32 bit machine it works fine. Is there anyway to fix this? Is there a build for AMD64 bit machines or is there simply no way that I can get MySQLdb working on it? Thanks in advance, Sjoerd From stefan.behnel-n05pAM at web.de Wed Aug 22 02:47:32 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 22 Aug 2007 08:47:32 +0200 Subject: urllib2.urlopen(url) pulling something other than HTML In-Reply-To: <1187753421.798422.9570@q3g2000prf.googlegroups.com> References: <1187635452.841155.88720@a39g2000hsc.googlegroups.com> <1187641080.516885.122350@g4g2000hsf.googlegroups.com> <87ejhwr2mi.fsf@pobox.com> <1187753421.798422.9570@q3g2000prf.googlegroups.com> Message-ID: <46CBDC04.5020309@web.de> Gabriel Genellina wrote: > On 21 ago, 18:36, j... at pobox.com (John J. Lee) wrote: >> Gabriel Genellina writes: >> >> [...]> Don't even try to understand it - it's a mess. Use the HTMLParser >>> module instead. >> [...] >> >> Module sgmllib (and therefore module htmllib also) is more tolerant of >> bad HTML than module HTMLParser. > > I had the impression it was the opposite; anyway, neither of them can > handle really bad html. > I just don't *like* htmllib.HTMLParser - but that's only a matter of > taste. lxml.html handles bad HTML and it's a powerful tool that is very easy to use. And if one day you have to deal with really, *really* broken tag soup, it also comes with BeautifulSoup parser integration. Stefan From rcdailey at gmail.com Fri Aug 17 14:19:13 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 17 Aug 2007 13:19:13 -0500 Subject: Problem with directory recursion! In-Reply-To: <496954360708171116t4370c2ddra3d7905bc956c7eb@mail.gmail.com> References: <496954360708171116t4370c2ddra3d7905bc956c7eb@mail.gmail.com> Message-ID: <496954360708171119g66564ecas3134aed0b3916f8@mail.gmail.com> Here's part of the output that's incorrect: models\W_BoomerEdge BYOS_C.entity.xml BYOS_C_Collision.entity.xml Notice that the file BYOS_C.entity.xml is showing up as a file in the directory W_BoomerEdge. This file does not exist in this folder, but yet in a different folder. The output is consistent with the 'print' statements you will see in the function I posted earlier. On 8/17/07, Robert Dailey wrote: > > Hi, > > I've created a function that is used to recurse a directory tree in > Windows XP using os.walk(). For the most part it works, however in some > instances the data is incorrect and I'm getting invalid sub-directory paths. > Here's the function: > > > def __doSearch( root_dir, sub_path, restype, ext ): > print sub_path > # Searches the specified directory and generates a > # list of files to preload. > complete_path = osp.normpath( osp.join( root_dir, sub_path ) ) > for root, dirs, files in os.walk( complete_path ): > > # Record the list of file hash ID's > for file in files: > split = __resType( file ) > if split[1] == restype: > # print sub_path > print "\t", file > __appendResource( ext, sub_path, split[0] ) > > # Remove .svn subdirectories; we don't walk these. > if ".svn" in dirs: > dirs.remove( ".svn" ) > > # Recurse child directories > for dir in dirs: > __doSearch( root_dir, osp.join( sub_path, dir ), restype, ext > ) > > Does anyone see anything immediately suspicious about the code? I'm > assuming that in Python, every time a function is called recursively it gets > its own copy of local variables. For some reason the sub_path variable isn't > consistent depending on where I use it. For example, if you notice the print > call at the very start of the function, it will output something like > "models/ships". However, after passing it into __appendResource(), it > appears to be just "models". > -------------- next part -------------- An HTML attachment was scrubbed... URL: From arkanes at gmail.com Wed Aug 1 12:46:17 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 1 Aug 2007 11:46:17 -0500 Subject: calling a .net application from Python 2.5 In-Reply-To: <8a6b8e350708010925t56d107a0md38a8fc1f750898d@mail.gmail.com> References: <1185959694.045149.214050@19g2000hsx.googlegroups.com> <8a6b8e350708010925t56d107a0md38a8fc1f750898d@mail.gmail.com> Message-ID: <4866bea60708010946sd68e524tf6989fd5382c5df1@mail.gmail.com> Note that for 2.5 you'll want the released snapshot, not the official release. On 8/1/07, James Matthews wrote: > http://pythonnet.sourceforge.net/ > > > On 8/1/07, Acm wrote: > > I am working with Python 2.5. > > > > I would like to know how to call a .NET application (or .dll) from a > > Python script. > > > > Can anyone help please? > > > > Thank you. > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > http://www.goldwatches.com/ > http://www.jewelerslounge.com > -- > http://mail.python.org/mailman/listinfo/python-list > From carsten at uniqsys.com Thu Aug 30 07:50:16 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 30 Aug 2007 07:50:16 -0400 Subject: list index() In-Reply-To: <1188456273.102334.48660@50g2000hsm.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> Message-ID: <1188474616.3257.18.camel@localhost.localdomain> On Wed, 2007-08-29 at 23:44 -0700, zzbbaadd at aol.com wrote: > What's with the index() function of lists throwing an exception on not > found? Let's hope this is rectified in Python 3. You're assuming that this behavior is a mistake. It's not, and consequently, it won't be "rectified". > If nothing else, add > a function that doesn't throw an exception. There are a million > situations where you can have an item not be in a list and it is not > an exception situation. How could it not be an exception, in the plain English sense of the word? Most certainly you're asking for the index because you want to do something with the index. If the item is not found, you have no index, so that's a special case that must be handled separately. There is no logical difference between handling that special case in an except clause versus handling it with an if-branch. Is the Pythonic way try: i = somelist.index(thing) # Do something with i except IndexError: # Do something if thing not found really that much worse than the theoretical alternative i = somelist.index_that_returns_an_indicator(thing) if i!=ThingNotFoundIndicator: # Do something with i else: # Do something if thing not found ? -- Carsten Haese http://informixdb.sourceforge.net From laurent.pointal at limsi.fr Tue Aug 14 09:03:29 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 14 Aug 2007 15:03:29 +0200 Subject: JPype - passing to Java main In-Reply-To: <1187095969.789811.63960@j4g2000prf.googlegroups.com> References: <1187040070.806416.75090@r34g2000hsd.googlegroups.com> <1187095969.789811.63960@j4g2000prf.googlegroups.com> Message-ID: unlikeablePorpoise at gmail.com a ?crit : >> Try this: >> com.JPypeTest.main("arg") >> >> Ian > > Thanks for your suggestion, but it doesn't work (produces an error). This is where you should have copy/pasted the error. ;-) > > Does anybody else have any ideas? Sorry, no. From steve at holdenweb.com Tue Aug 14 21:45:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 14 Aug 2007 21:45:41 -0400 Subject: buggie in else syntax ? In-Reply-To: <46C21D70.8000409@gmail.com> References: <46C21D70.8000409@gmail.com> Message-ID: stef mientki wrote: > hello, > > I've the idea that the "else" syntax is not always handled correctly, > or I'm overlooking something. > [...] When faced with a choice between an error in a basic piece of Python and a misunderstanding on your part, Occam's razor would suggest you are failing to understand something. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From cdleary at gmail.com Wed Aug 8 05:11:18 2007 From: cdleary at gmail.com (cdleary at gmail.com) Date: Wed, 08 Aug 2007 09:11:18 -0000 Subject: Case study: library class inheritance with property declarations In-Reply-To: <46b23c19$0$13518$426a74cc@news.free.fr> References: <1186062582.975223.230270@g12g2000prg.googlegroups.com> <1186063694.311416.133390@i13g2000prf.googlegroups.com> <1186065365.546545.184840@i13g2000prf.googlegroups.com> <46b23c19$0$13518$426a74cc@news.free.fr> Message-ID: <1186564278.798772.316720@w3g2000hsg.googlegroups.com> On Aug 2, 7:05 am, Bruno Desthuilliers wrote: > cdle... at gmail.com a ?crit : > (snip) > > > Last post -- I swear. > > > I failed to realize that it's all part of an extremely well defined > > attribute resolution protocol, and handled via the descriptor > > specification. Discussing descriptors was on the TODO list for the > > type/class unification document, but there's a very fulfilling > > explanation by Raymond Hettinger:http://users.rcn.com/python/download/Descriptor.htm > > Also, the official doc is here:http://docs.python.org/ref/descriptors.html > > > Maybe the documentation for the property builtin should make reference > > to the descriptor specification? If nobody thinks this is silly, I'll > > submit a documentation patch in a few days. > > What to say ? As an old-time pyton user (well... 7+ years now) and > meta-programming addict, it's nothing new to me, but the fact that you > didn't realize it is certainly a clear indication that documentation is > not really up to date, so yes, submitting a patch is certainly a pretty > good idea. > > > Sorry for the spam -- hope someone besides me learns from it! > > What's to be learned is mostly that we (the whole community) should take > more care of the doc (which I never contributed FWIW, so I'm the first > one that should feel in guilt here). Actually I was wrong about this! Of course, the problem was insufficient test coverage :) The key addition: assert spam.useful_attr == 12 # FAILS!!! I failed to realize it in the last posts... When you don't declare a descriptor as a class attribute the descriptor protocol isn't invoked! The descriptor protocol looks in the /class/ attributes -- it transforms spam.useful_attr to type(spam).__dict__['useful_attr'].__get__(spam, type(spam)), the caveat being /type(spam)/. >From the doc: (http://users.rcn.com/python/download/Descriptor.htm) The implementation works through a precedence chain that gives data descriptors priority over instance variables, instance variables priority over non-data descriptors, and assigns lowest priority to __getattr__ if provided. The data descriptors are only looked up in the class attributes -- the instance attributes are returned as-is, so the above assertion fails! The addition of 'print spam.useful_attr' produces , because the portion of the descriptor protocol that invokes __get__ is does not cover instance attributes (as declared in __init__). So, we're back to the original problem, with a bit more insight. What if we declare the useful_attr property as a class attribute in the constructor after the LibraryClass initialization function? It only works once! Once you set a class attribute on the first instantiation it's obviously there the next time you try to instantiate. Now our test looks like this: def test(): class _Fake(object): pass external_obj = _Fake() external_obj.proxy_useful_attr = 12 spam = MyInheritedClass(external_obj) assert spam.useful_attr == 12 eggs = MyInheritedClass(external_obj) assert eggs.useful_attr == 12 Which provides coverage for the INCORRECT class-attribute-on- instantiation solution, since eggs won't be able to instantiate. The solution which fails this test looks like this: class MyInheritedClass(LibraryClass): # WRONG! Don't use this. def __init__(self, external_obj): LibraryClass.__init__(self) def get_useful_attr(would_be_self): # has to be unbound return would_be_self._external_obj.proxy_useful_attr MyInheritedClass.useful_attr = property(get_useful_attr) self._external_obj = external_obj At this point it seems like the only viable option is to hack getattribute to add special cases. To do this, we continue to use the unbound method getter as our argument to property, but add the getattribute hack which allows for specified instance attributes that have the descriptor protocol invoked on them: class MyInheritedClass(LibraryClass): # ... def __init__(self, external_obj): LibraryClass.__init__(self) def get_useful_attr(would_be_self): return would_be_self._external_obj.proxy_useful_attr self.useful_attr = property(fget=get_useful_attr) self._external_obj = external_obj def __getattribute__(self, attr_name): """ Hacks getattribute to allow us to return desired instance attributes with the descriptor protocol. """ instance_descrs = ['useful_attr'] if attr_name in instance_descrs and attr_name in self.__dict__: attr = self.__dict__[attr_name] return attr.__get__(self, type(self)) return object.__getattribute__(self, attr_name) This passes the above test, but obviously requires a hack -- is there a more elegant way to do it? - Chris From bj_666 at gmx.net Thu Aug 30 09:35:39 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Aug 2007 13:35:39 GMT Subject: SAXParseException: not well-formed (invalid token) References: <5jnrrqFdmbcU5@mid.uni-berlin.de> <46D6C6CE.5070009@cesga.es> Message-ID: <5jnvdbFdmbcU7@mid.uni-berlin.de> On Thu, 30 Aug 2007 15:31:58 +0200, Pablo Rey wrote: > On 30/08/2007 14:35, Marc 'BlackJack' Rintsch wrote: > >> Maybe you can download that XML file and use `xmllint` to check if it >> is well formed XML!? > > This is the output of the xmllint command: > > [prey at www3 voms2users]$ xmllint cms.xml cms.xml:553: error: Input is not > proper UTF-8, indicate encoding ! > /C=BE/O=BEGRID/OU=Physique/OU=Univesit? Catholique de > Louvain/CN=Roberfroi > ^ > cms.xml:553: error: Bytes: 0xE9 0x20 0x43 0x61 > /C=BE/O=BEGRID/OU=Physique/OU=Univesit? Catholique de > Louvain/CN=Roberfroi > > [?] > > So the XML says it is encoded in UTF-8 but it contains at least one character that seems to be encoded in ISO-8859-1. Tell the authors/creators of that document there XML is broken. Ciao, Marc 'BlackJack' Rintsch From athropos at gmail.com Wed Aug 15 08:39:16 2007 From: athropos at gmail.com (=?ISO-8859-1?Q?Fran=E7ois_Ingelrest?=) Date: Wed, 15 Aug 2007 14:39:16 +0200 Subject: Combinatorial of elements in Python? In-Reply-To: <46C2ED11.70904@freakmail.de> References: <9e2f512b0708142203m782b0e10s817fb4d061ba0e46@mail.gmail.com> <46C2ED11.70904@freakmail.de> Message-ID: > > I have 2 (or more) groups of elements, and I want to get all possible > > unique combinations from all of them. Is there a build-in method to do > > it? > >>> ADictionary={"one":["A","B","C","D"],"two":["H","I"]} > >>> result = set() > >>> for one in ADictionary["one"]: > ... for two in ADictionary["two"]: > ... result.add(one + two) > ... > >>> result > set(['CI', 'CH', 'DH', 'DI', 'AI', 'AH', 'BH', 'BI']) With a list comprehension: >>> d={"one":["A","B","C","D"],"two":["H","I"]} >>> [a+b for a in d['one'] for b in d['two']] ['AH', 'AI', 'BH', 'BI', 'CH', 'CI', 'DH', 'DI'] From raims at dot.com Mon Aug 13 06:20:16 2007 From: raims at dot.com (Lawrence Oluyede) Date: Mon, 13 Aug 2007 12:20:16 +0200 Subject: check if var is dict References: Message-ID: <1i2sa4l.1s8guf1d5npcN%raims@dot.com> Astan Chee wrote: > I have a variable, I want to check if it is a dictionary or a string. > Is there any better way to do this than I've done. How I did it is by > doing a .items() and catching a AttributeError that it raises if its not > a dictionary. > How do i properly do it? One way is: In [6]: isinstance(d, dict) Out[6]: True In [7]: isinstance("ciao", basestring) Out[7]: True This way you won't catch custom classes implementing dict or basestring "protocols". In order to do that you can check if it implements the right methods or treat the object as a dict or a string. It depends on what you're trying to achieve. -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From johnmasters at oxtedonline.net Sun Aug 19 14:13:09 2007 From: johnmasters at oxtedonline.net (John K Masters) Date: Sun, 19 Aug 2007 19:13:09 +0100 Subject: Python equivalent of Perl's $/ Message-ID: <20070819181309.GC4841@spookie1.spookiegate> I am currently working my way through Jeffrey Friedl's book Mastering Regular Expressions. Great book apart from the fact it uses Perl for the examples. One particular expression that interests me is '$/ = ".\n"' which, rather than splitting a file into lines, splits on a period-newline boundary. Combined with Perl's 'while (<>)' construct this seems a great way to process the files I am interested in. Without wishing to start a flame war, is there a way to do this in Python? Regards, John -- War is God's way of teaching Americans geography Ambrose Bierce (1842 - 1914) From joshua at eeinternet.com Wed Aug 1 20:35:35 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 01 Aug 2007 16:35:35 -0800 Subject: Is shelve/dbm supposed to be this inefficient? References: <200708020208.53982.thomas@jollans.com> Message-ID: On Wednesday 01 August 2007 16:08, Thomas Jollans wrote: > Have you considered a directory full of pickle files ? (In effect, > replacing the dbm with the file system) i.e. something like (untested) > > class DirShelf(dict): A very interesting idea. I'll have to see how that plays out performance-wise. Thanks for the idea, and the roughed-out code! j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE From gagsl-py2 at yahoo.com.ar Tue Aug 28 00:23:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 28 Aug 2007 01:23:35 -0300 Subject: Image.open( "C:\test.jpg") is this wrong ? References: Message-ID: En Mon, 27 Aug 2007 11:48:46 -0300, Carnell, James E escribi?: >> Image.open("C:\test.jpg") # this is what I have right now. And it >> can't find the file or directory. The file is there (it is everywhere >> on my computer now!!!) Use "C:\\test.jpg" or r"C:\test.jpg" or "C:/test.jpg" instead. \t is interpreted as a tab character > I found some code where they apply the file path to a variable in single > quotes. Is that how it is done. Also I thought single quotes were for > characters not strings. a = 'This is a string' b = "This is a string too" c = """This is a very long string, spanning several lines""" d = '''This is a multiline string too''' e = "e" f = 'f' You can read the relevant Tutorial section here -- Gabriel Genellina From bj_666 at gmx.net Thu Aug 30 08:39:27 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Aug 2007 12:39:27 GMT Subject: Python doesn't see the directories I create References: <46d6856b$0$17674$426a74cc@news.free.fr> <46d6a72c$0$20532$426a74cc@news.free.fr> Message-ID: <5jns3vFdmbcU6@mid.uni-berlin.de> On Thu, 30 Aug 2007 07:28:52 -0400, Steve Holden wrote: > Bruno Desthuilliers wrote: >> Steve Holden a ?crit : >> Indeed. But I doubt a path starting with 'C:' will work fine on a >> unix-like environment anyway !-) > > Just to be contrarian: > > sholden at bigboy ~/Projects/python.org/build > $ ls C:/Steve/ > Apache SANSsecurityOverview.pdf > Apache2 SQLServer.txt > ... > Resume.odt todo.txt > Resume.pdf untitled-1.py > > sholden at bigboy ~/Projects/python.org/build > > That's Cygwin, of course. Is that sufficiently "unix-like"? Though I > have to admit that the different utilities all take different approaches > to the use of Windows paths, and some just won't take them at all. Even on Unix it shouldn't be a problem on most file systems to create a directory named 'C:' bj at s8n:~$ mkdir C: bj at s8n:~$ touch C:/test.txt bj at s8n:~$ ls -l C: total 0 -rw-r--r-- 1 bj bj 0 2007-08-30 14:38 test.txt :-) Ciao, Marc 'BlackJack' Rintsch From godzillaismad at gmail.com Thu Aug 16 23:51:28 2007 From: godzillaismad at gmail.com (Godzilla) Date: Thu, 16 Aug 2007 20:51:28 -0700 Subject: Memory leak when creating lots of object In-Reply-To: <1187190827.395382.85740@57g2000hsv.googlegroups.com> References: <1187067442.084074.55010@z24g2000prh.googlegroups.com> <1187190827.395382.85740@57g2000hsv.googlegroups.com> Message-ID: <1187322688.545415.122010@i38g2000prf.googlegroups.com> On Aug 16, 1:13 am, Paul Moore wrote: > On 14 Aug, 05:57, Godzilla wrote: > > > Hello, > > > I have a program that create and pop an object off a queue, but it is > > experiencing some memory leakage. I have been unable to detect where > > the memory leakage occur. The strange thing is when i replace the > > object creation with a plain integer/string, the leak goes away... > > Here's the code I used as my test: > [...] > > I can see the memory usage increases slowly in Task Manager under XP, > > but do not know why. Anyone help? > > I tried your code on my (Windows XP SP2, Python 2.5) system. No memory > leak here - I left it running for over 5 minutes and memory usage was > static at just under 4MB. > > Do you see memory growth with precisely this code? Over what period? > How much? > > Paul. Hi Paul, I have it running for more than 1 hour... the main application software runs for about 50 days non stops and the memory just keep growing... I have a pdu.py class which has about 130 methods that's been created on the fly. If you substitute the above code of PDU() init with the pdu class from pdu.py, I see a dramatic increase in RAM in python 2.4.4! But not in version 2.5.1. So I upgraded to the latest version... I still see the main application uses more and more memory as the time goes by... What should I do next? Can I force garbage collection manually? If so, how do I do that? From martin at v.loewis.de Tue Aug 7 17:14:10 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 07 Aug 2007 23:14:10 +0200 Subject: Misleading wikipedia article on Python 3? In-Reply-To: <87lkcnoydy.fsf@pobox.com> References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <87lkcnoydy.fsf@pobox.com> Message-ID: <46b8e0a2$0$12255$9b622d9e@news.freenet.de> > Do you *really* think that projects will fall 50-50 into the "yes" and > "no" camps, as you seem to imply -- after all, if you thought that one > case was more common, why wouldn't you mention which it was? I know you didn't ask me this time, but I answer anyway: I don't know. I *really* think that only experience can tell, and that any kind of prediction on that matter is futile FUD (as FUD, it might be successful, of course). I do so using all my skill and judgment. Only when people actually start to try porting, list specific issues that they actually ran into (rather than listing issues they anticipate to run into), only then I can make guesses as to what the common case will be. Ask this question a year from now again. Regards, Martin From gnewsg at gmail.com Thu Aug 23 15:01:03 2007 From: gnewsg at gmail.com (billiejoex) Date: Thu, 23 Aug 2007 12:01:03 -0700 Subject: Impersonate another user temporarily (Unix and Windows) In-Reply-To: References: <1187809798.274511.230240@z24g2000prh.googlegroups.com> <1187866104.967297.324650@j4g2000prf.googlegroups.com> Message-ID: <1187895663.991360.224830@x40g2000prg.googlegroups.com> On 23 Ago, 13:13, "Chris Mellon" wrote: > On 8/23/07, billiejoex wrote: > > > > > > > On 23 Ago, 10:38, Tim Golden wrote: > > > billiejoex wrote: > > > > Hi there. I'm writing a modification for a FTP server library I'm > > > > maintaining. > > > > Depending on the system I'd want to temporarily impersonate the logged > > > > user to perform actions on filesystem. > > > > Something like: > > > > > try: > > > > change_user('user', 'password') > > > > os.rmdir('dir') > > > > except: > > > > print "some error" > > > > finally: > > > > change_user('old_user', 'password') > > > > > On Unix I took at look at os.seteuid() and os.setegid() functions and > > > > I noticed they could be useful for my purpose. > > > > On Windows I have no idea about how could I emulate a similar > > > > behaviour. > > > > Could someone please point me in the right direction? > > > > (Warning: not tried, but at least gives you the things to Google for!) > > > > You need the win32security module from the pywin32 extensions. [1] > > > In particular, you want to look at the LogonUser and > > > ImpersonateLoggedOnUser functions. > > > > TJG > > > > [1]http://pywin32.sf.net-Nascondi testo tra virgolette - > > > > - Mostra testo tra virgolette - > > > Thanks for suggestion. > > I made it. > > Note that running your process as a user with enough priviledges to > impersonate another user pretty much eliminates all the benefits of > running as a low-priviledged user in the first place. Consider > re-thinking your application model and having an "ftp" user instead.- Nascondi testo tra virgolette - > > - Mostra testo tra virgolette - Could you be more precise? Why it's not a good idea? I was thinking of starting ftpd as limited user ('nobody'/'ftp' on unix, 'Guest' on Windows), then temporary switching to another user when I got to perform actions on file system. Maybe you're saying that as limited user I can't do such switching? From mail at microcorp.co.za Wed Aug 1 02:55:43 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 1 Aug 2007 08:55:43 +0200 Subject: simple string backspace question References: <1185875052.153091.23300@19g2000hsx.googlegroups.com><1185876068.755101.316320@b79g2000hse.googlegroups.com> <1185884227.491711.105160@x35g2000prf.googlegroups.com> Message-ID: <014401c7d418$3273c520$03000080@hendrik> "John Machin" wrote: > Point (2): Backspace??? YAGNI --- backspace hasn't been much use for > anything (except when typing text) since the days when in order to get > a bold letter (say X) on a character impact printer, one would > transmit X\bX\bX ... ooooooh! Ugly! Almost as bad as, on a golf ball printer: "I am a little nodding man, I always nod my head..." followed by an infinite loop of shift-in, shift-out characters. - Hendrik From andre.roberge at gmail.com Thu Aug 2 10:49:32 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Thu, 02 Aug 2007 14:49:32 -0000 Subject: Determining if file is valid image file In-Reply-To: <1186065486.645871.175590@m37g2000prh.googlegroups.com> References: <1186064098.587590.91210@g4g2000hsf.googlegroups.com> <1186064275.652416.250540@d55g2000hsg.googlegroups.com> <1186065486.645871.175590@m37g2000prh.googlegroups.com> Message-ID: <1186066172.591814.215970@o61g2000hsh.googlegroups.com> On Aug 2, 11:38 am, kyoso... at gmail.com wrote: > On Aug 2, 9:35 am, Thomas Jollans wrote: > > > > > On Thursday 02 August 2007, Andr? wrote: > > > > On Aug 2, 11:14 am, Andr? wrote: > > > > Other than installing PIL, is there a "simple" way using Python only > > > > to determine if a file is a valid image file? > > > > > I'd be happy if I could at least identify valid images files for gif, > > > > jpeg and png. Pointers to existing modules or examples would be > > > > appreciated. > > > > > The reason why I'd prefer not using PIL is that I'd like to bundle > > > > such a function/module in my app. > > > > I should have added: I'm interesting in validating the file *content* > > > - not the filename :-) > > > The file name has nothing to do with the type :-P > > > A straightforward way you won't like: read the specs for all formats you're > > interested in and write the function yourself ;-) > > Use the md5 module to create checksums. Links below: > Sorry, I fail to see how this helps me to identify if a file I retrieve from somewhere is a valid image file... > http://www.peterbe.com/plog/using-md5-to-check-equality-between-fileshttp://effbot.org/librarybook/md5.htmhttp://docs.python.org/lib/module-md5.html > > Larry is right too...what's wrong with bundling PIL or any third party > module? > Why not bundling PIL?: Because I'm trying to keep the size of my app as small as possible. I don't mind bundling some other modules from third parties (in fact, I already do include three modules from ElementTree...). Andr? > Mike From raims at dot.com Sat Aug 18 21:27:42 2007 From: raims at dot.com (Lawrence Oluyede) Date: Sun, 19 Aug 2007 03:27:42 +0200 Subject: How to make a module function visible only inside the module? References: <1187484334.091530.90420@m37g2000prh.googlegroups.com> Message-ID: <1i32pg7.b0y3h92vjygwN%raims@dot.com> beginner wrote: > Is there any equivalent version of C's static function in Python. I > know I can make a class function private by starting a function name > with two underscores, but it does not work with module functions. The trick for the name mangling does not work at module level. Anyway, if you read the PEP 8 [1] you can correctly write your code following a well known coding standard. A function like this: def _f(): pass is meant to be private, you can also state it in the function's docstring to be more clear, if you want, but it's not necessary > For exmaple, __func1 is still visible outside the module. Yes, and _f() will also be. There's no such thing as enforcing encapsulation in Python, even the "__method()" trick can be easily bypassed if you have to. 1 - HTH -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From zzbbaadd at aol.com Thu Aug 30 13:56:28 2007 From: zzbbaadd at aol.com (zzbbaadd at aol.com) Date: Thu, 30 Aug 2007 10:56:28 -0700 Subject: list index() In-Reply-To: <46d674c2$0$417$426a34cc@news.free.fr> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <46d674c2$0$417$426a34cc@news.free.fr> Message-ID: <1188496588.750629.208100@g4g2000hsf.googlegroups.com> On Aug 30, 12:42 am, Bruno Desthuilliers wrote: > zzbba... at aol.com a ?crit : > > What's with using your brain instead of whining ? I knew there would be at least one religious zealot. From steve at holdenweb.com Wed Aug 8 08:52:59 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 08 Aug 2007 08:52:59 -0400 Subject: Something in the function tutorial confused me. In-Reply-To: <5hsoi3F3mlni2U1@mid.individual.net> References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <1186424693.529497.217040@w3g2000hsg.googlegroups.com> <46B8626A.2070303@bigfoot.com> <5hsoi3F3mlni2U1@mid.individual.net> Message-ID: greg wrote: > Steve Holden wrote: >> OK. The difference is that [] is a mutable value, while None is >> immutable. > > No, it's not. It has nothing to do with mutability > vs immutability. > I beg to differ. That has everything to do with it. > The difference is that in the first version the > expression [] is evaluated only *once*, when the > function is defined. Therefore there is just one > list object getting re-used. > In exactly the same way that with a default value of None just one None value is being re-used. The difference is that you have no way to nutate that value in place, whereas with a list object you can indeed do that. > In the second version, the expression [] gets > evaluated *each* time the function is called, > creating a new list object each time. > Correct. >> When the function starts out with None as y's value any assignment to y >> causes it to reference a different value (since None is immutable). > > You're confused. Assigning to y simply causes it > to reference whatever object is being assigned. > This is always true, regardless of what y was > referencing before. > While it's correct that rebinding y will usually cause it to reference a different object, this need not be true of assignment. The augmented assignment operations do no necessarily rebind their left-hand operand - that depends on the implementation of the relevant method in whatever type is the subject of the augmented assignment. An *assignment* to y therefore *usually* rebinds the name y to point to a different value. A *mutation* of the object *referenced* by y leaves y pointing to the same value. This is why appends to a default list argument are visible in later calls: because each call initializes y to reference the single object that was provided as the default value, which has been changed by previous calls. > To see that the immutability of None has nothing > to do with it, try the following version: > > def f(x, y = []): > y = [] > y.append(x) > print y > > f(17) > f(42) > > Try to work out what it will do, then try it, and > see if you understand why it does what it does. > I know exactly what it will do without running it, thank you. Each call will return a single-valued list. It's hardly relevant, though since the value of the default argument isn't used anywhere in the function body. You are correct in stating that the [] construct always creates a new list. However, your explanation of why a list as a default argument retains mutations in further calls seems to me to omit some important details. For some reason your reply got right up my nose, so I have had to restrain the impulse to be unpleasant. I'm left wondering if that's because of something in your reply (such as your assumption that your understanding of this situation is superior to mine) or because I got out of the wrong side of bed this morning. I'm currently giving you the benefit of the doubt, and going for another cup of coffee. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From michael at jedimindworks.com Thu Aug 9 06:26:45 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 9 Aug 2007 03:26:45 -0700 Subject: Launching App In-Reply-To: <00e301c7da6c$51ee3fc0$f5cabf40$@rawlins@thinkbluemedia.co.uk> References: <00e301c7da6c$51ee3fc0$f5cabf40$@rawlins@thinkbluemedia.co.uk> Message-ID: <4FE6546B-782B-41CA-A037-82D634E6C7ED@jedimindworks.com> On Aug 9, 2007, at 3:01 AM, Robert Rawlins - Think Blue wrote: > I?m looking for the best method to launch my python app when my > Linux system boots up. At the moment I just have an entry like this > in my rc.local file: > > CD /myfolder/anotherfolder > > ./myapp.py > > > > Is this the best way to do this? Or is there a better way? I feel > like a bit of a dummy asking this question, I just wanted to ensure > the best method. A better way is to use the SYSV init system: create a start/stop/ status script for your app in /etc/init.d (use existing scripts in that directory for examples of what you can do). On Debian, you can then use update-rc.d to create the appropriate symlinks. hope this helps, Michael --- Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. --Brian W. Kernighan -------------- next part -------------- An HTML attachment was scrubbed... URL: From joevans at gmail.com Wed Aug 22 22:07:16 2007 From: joevans at gmail.com (Jason Evans) Date: Wed, 22 Aug 2007 19:07:16 -0700 Subject: Parser Generator? In-Reply-To: References: Message-ID: <1187834836.115735.111160@e9g2000prf.googlegroups.com> On Aug 18, 3:22 pm, "Jack" wrote: > Hi all, I need to do syntax parsing of simple naturual languages, > for example, "weather of London" or "what is the time", simple > things like these, with Unicode support in the syntax. > > In Java, there are JavaCC, Antlr, etc. I wonder what people use > in Python? Antlr also has Python support but I'm not sure how good > it is. Comments/hints are welcome. I use Parsing.py. I like it a lot, probably because I wrote it. http://www.canonware.com/Parsing/ Jason From aleax at mac.com Sun Aug 26 11:52:56 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 26 Aug 2007 08:52:56 -0700 Subject: Need a better understanding on how MRO works? References: <1i3evke.1rwf8pn10k1h30N%aleax@mac.com> <1i3f78x.1pxexgx6emjfhN%aleax@mac.com> Message-ID: <1i3g2cb.1vtfo65u1a072N%aleax@mac.com> Steven W. Orr wrote: ... > =>accepts whatever dictionary you give it (so you can, though shouldn't, > =>do strange things such as pass globals()...:-). > > In fact, I wanted to make a common routine that could be called from > multiple modules. I have classes that need to be created from those > multiple modules. I did run into trouble when I created a common routine > even though I passed globals() as one of the args. The """though > shouldn't""" is prompting me to ask why, and where I might be able to read > more. The dictionary you pass to new.classobj should be specifically constructed for the purpose -- globals() will contains all sort of odds and ends that have nothing much to do with the case. You appear to be trying to embody lot of black magic in your "common routine", making it communicate with its callers by covert channels; the way you use globals() to give that routine subtle "side effects" (making the routine stick entries there) as well as pass it an opaque, amorphous, unknown blobs of input information, strongly suggests that the magic is running away with you (a good general reference about that is ). "Explicit is better than implicit", "simple is better than complex", etc, can be read by typing ``import this'' at an interactive Python prompt. The best book I know about the do's and don't's of large-scale software architecture is Lakos' "Large-Scale C++ Software Design", -- very C++ specific, but even though some of the issues only apply to C++ itself, many of its crucial lessons will help with large scale SW architecture in just about any language, Python included. What I had to say about the lures and pitfalls of black magic in Python specifically is spread through the Python Cookbook 2nd edition (and, to a lesser extent, Python in a Nutshell). Alex From kyosohma at gmail.com Thu Aug 2 14:01:08 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 02 Aug 2007 18:01:08 -0000 Subject: Email In-Reply-To: <1186076005.729346.327140@z24g2000prh.googlegroups.com> References: <1186076005.729346.327140@z24g2000prh.googlegroups.com> Message-ID: <1186077668.315353.172360@x35g2000prf.googlegroups.com> On Aug 2, 12:33 pm, Rohan wrote: > I was wondering if there could be an arrangement where a file could be > attached and send as an email. > For ex > f = open(add.txt,w) > f.write('python') > f.close() > > Now I would like to send an email with add.txt as an attachment, is it > possible ? > some one give me a pointer towards this. Try looking up the email module. http://docs.python.org/lib/node162.html Mike From horpner at yahoo.com Mon Aug 27 14:20:33 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 27 Aug 2007 18:20:33 GMT Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com> <1187898049.734696.9500@l22g2000prc.googlegroups.com> <13csoronscqp7d2@corp.supernews.com> <1188090322.663217.102750@22g2000hsm.googlegroups.com> <13d4bucfm4m1lc4@corp.supernews.com> <13d4gjm3qq0lt7c@corp.supernews.com> Message-ID: On 2007-08-27, bambam wrote: > Thank you, I have been through the tutorial several times, I > guess I'm just not smart enough. Perhaps I have been led astray > by what I read here? > > My code started like this: > > for i in range(self.parent.GetPageCount()): > > I was asked: > >> Does page count change? i.e. is it necessary to retrieve it in >> every loop > > Is self.parent.GetPageCount() 'retrieved every loop'? No. The question seems to imply that if you wish it to be retrieved every loop you must change the code to something else. i = 0 while i < self.parent.GetPageCount(): # do stuff i += 1 I find that kind of while loop clunky. Since Python is hard-headed about not providing a structured looping construct, you may feel the need to compose your own special-purpose iterator or generator instead. def pageCountGenerator(document): i = 0 while i < document.GetPageCount(): yield i i += 1 It can be used like this: for i in pageCountGenerator(self.parent): # do stuff That way you get the happy syntax of a for loop, with the additional safety of checking the page count each iteration. This sort of suggests a direct solution: for i in xrange(self.parent.GetPageCount()): if i >= self.parent.GetPageCount(): break # do stuff At least that way you're spared the manual manipulation of i. -- Neil Cerutti From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Aug 2 05:30:35 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 02 Aug 2007 11:30:35 +0200 Subject: a dict trick In-Reply-To: <1186043222.732234.152550@d30g2000prg.googlegroups.com> References: <1186036331.304916.304020@e9g2000prf.googlegroups.com> <1186043222.732234.152550@d30g2000prg.googlegroups.com> Message-ID: <46b1a43b$0$20425$426a74cc@news.free.fr> james_027 a ?crit : > Hi, > > what if we're not dealing with dict? is there a pythonic way of doing > ternary? the bool ? x:y Python 2.5 introduced the following syntax: expr1 if condition else expr2 In older Python versions, one has to use and/or (like you wrongly did) or tuple/dict dispatch or other ad-hoc tricks. Or use a plain old if/else branch. From martin at v.loewis.de Tue Aug 28 13:13:31 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 28 Aug 2007 19:13:31 +0200 Subject: sys.setdefaultencoding In-Reply-To: References: Message-ID: <46D457BB.6020809@v.loewis.de> > Is there a way to allow the process to specify that unicode-->str should > use 'utf8' rather than 'ascii' in all non-specific cases? No. Things might break if you change the default encoding to anything but ASCII, and more so if you do that "at runtime". For example, dictionaries with Unicode keys may stop working, and the cached byte-oriented version of a Unicode string may become incorrect. In general, programs and libraries should not rely on the default encoding for anything. Instead, they should convert explicitly, either from an explicitly specified encoding, or one derived from the context. Experience has shown that this is possible in nearly every case (and in all cases if an appropriate refactoring is made). Regards, Martin From cjw at sympatico.ca Wed Aug 15 16:00:04 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 15 Aug 2007 16:00:04 -0400 Subject: sub-classing the types in the builtin module datetime In-Reply-To: <46C33DFF.90704@jayloden.com> References: <46C33DFF.90704@jayloden.com> Message-ID: <46C35B44.5020406@sympatico.ca> An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Mon Aug 20 03:33:00 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 20 Aug 2007 04:33:00 -0300 Subject: Importing DLLs References: <7603657D433B034AB667802696450A3EAA6161@MAIL2.api.com> Message-ID: En Wed, 15 Aug 2007 14:20:26 -0300, Corbitt, Kyle escribi?: > I'm running Linux with Python 2.3. I have a C shared object file (*.so) > and I need to be able to call its functions from within Python. I have > found a couple of Python modules that allow me to do this (dl, ctypes) > but unfortunately I am only able to get them to return integers, even > for function calls that I KNOW the library is supposed to return other > types for. I need the library to be able to return doubles, 2D arrays Use the ctypes module. Read the tutorial - you have to set the restype attribute on functions. -- Gabriel Genellina From nick at craig-wood.com Sat Aug 11 10:30:05 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 11 Aug 2007 09:30:05 -0500 Subject: The Future of Python Threading References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <5i329uF3muir4U1@mid.individual.net> <5i45luF3mvdesU1@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > Nick Craig-Wood wrote: > [GIL] > > That is certainly true. However the point being is that running > > on 2 CPUs at once at 95% efficiency is much better than running on > > only 1 at 99%... > > How do you define this percent efficiency? Those are hypothetical numbers. I guess that a finely locked python will spend a lot more time locking and unlocking individual objects than it currently does locking and unlocking the GIL. This is for two reasons 1) the GIL will be in cache at all times and therefore "hot" and quick to access 2) much more locking and unlocking of each object will need to be done. > >>> The truth is that the future (and present reality) of almost > >>> every form of computing is multi-core, > >> > >> Is it? 8) > > > > Intel, AMD and Sun would have you believe that yes! > > Strange, in my programs, I don't need any "real" concurrency (they > are network servers and scripts). Or do you mean "the future of > computing hardware is multi-core"? That indeed may be true. I meant the latter. I agree with you though that not all programs need to be multi-threaded. Hence my proposal for two python binaries. > >> The question is: If it really was, how much of useful > >> performance gain would you get? > > > > The linux kernel has been through these growing pains already... > > SMP support was initially done with the Big Kernel Lock (BKL) > > which is exactly equivalent to the GIL. > > So, how much performance gain would you get? Again, managing > fine-grained locking can be much more work than one simple lock. Assuming that you are not IO bound, but compute bound and that compute is being done in python then you'll get a speed up proportional to how many processors you have, minus a small amount for locking overhead. > > The linux kernel has moved onwards to finer and finer grained > > locking. > > How do you compare a byte code interpreter to a monolithic OS > kernel? In this (locking) respect they are quite similar actually. You can think of kernel code as being the python interpreter (BKL vs GIL), user space being as C extensions running with the GIL unlocked and calling back into the python interpreter / kernel. > > I'd like to see a python build as it is at the moment and a > > python-mt build which has the GIL broken down into a lock on each > > object. python-mt would certainly be slower for non threaded > > tasks, but it would certainly be quicker for threaded tasks on > > multiple CPU computers. > > From where do you take this certainty? For example, if the program > in question involves mostly IO access, there will be virtually no > gain. Multithreading is not Performance. Yes you are right of course. IO bound tasks don't benefit from multi-threading. In fact usually the reverse. Twisted covers this ground extremely well in my experience. However IO bound tasks probably aren't taxing your quad core chip either... > > The user could then choose which python to run. > > > > This would of course make C extensions more complicated... > > Also, C extensions can release the GIL for long-running > computations. Provided they stay in C. If they call any python stuff then they need to take it again. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From nyamatongwe+thunder at gmail.com Thu Aug 30 18:25:37 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Thu, 30 Aug 2007 22:25:37 GMT Subject: pure python for sms In-Reply-To: References: Message-ID: Gerardo Herzig: > Hi dudes. Im looking for a python implementation for sending sms to a > cell phone. I was try using some free pages, but i want to use a python. > Do i need a cellphone conected to my machine? Or can i send sms to some > cell via some python library? This is likely to cost some money similar to sending an SMS from a 'phone. There are several companies that provide SMS sending services that can be accessed through HTTP. Have a look at www.clickatell.com and www.aql.com . Here is a library based on Clickatell: http://www.powertrip.co.za/code/python/clickatell.py Neil From dwahler at gmail.com Wed Aug 15 16:17:41 2007 From: dwahler at gmail.com (David Wahler) Date: Wed, 15 Aug 2007 15:17:41 -0500 Subject: encrypting files + filestreams? In-Reply-To: <1187186797.579680.206820@19g2000hsx.googlegroups.com> References: <1187186797.579680.206820@19g2000hsx.googlegroups.com> Message-ID: On 8/15/07, per9000 wrote: > Hi python people, > > I am trying to figure out the best way to encrypt files in python. > > I've build a small script (see below) that encrypts the ubuntu 7.04 > iso file in 2 minutes (I like python :) ). > > But I have some thoughts about it. By pure luck (?) this file happened > to be N*512 bytes long so I do not have to add crap at the end - but > on files of the size N*512 + M (M != 521) I will add some crap to make > it fit in the algorithm. When I later decrypt I will have the stuff I > do not want. How do people solve this? (By writing the number of > relevant bytes in readable text in the beginning of the file?) The term you're looking for is "padding". See http://en.wikipedia.org/wiki/Padding_%28cryptography%29 for a brief introduction, and especially the two RFCs mentioned about halfway down. > Also I wonder if this can be solved with filestreams (Are there > streams in python? The only python file streams I found in the evil > search engine was stuff in other forums.) I don't know how to answer this, because it's not clear what you mean by "file streams". Python's file objects act similarly to things called streams in other languages, such as Java's InputStreams and Readers, if that's what you're asking. > Other comments are of course also welcome, > Per > > > # crypto_hardcoded.py starts here [snip] I notice there's some repeated code in your main loop. This generally means there's room for improvement in your program flow. Here's one possible way you could structure it: separate out the file reading and padding logic into a generator function that takes a filename or file object, and yields blocks one at a time, padded to the correct block size. Then your main loop can be simplified to something like this: for plaintext_block in read_as_blocks(in_file, block_size): ciphertext_block = cryptor.encrypt(plaintext_block) out_file.write(ciphertext_block) Techniques like these can make it easier to follow what's going on, especially as your programs get more complicated. Don't be afraid to experiment! -- David From cetiri at gmail.com Thu Aug 16 14:24:04 2007 From: cetiri at gmail.com (cetiri at gmail.com) Date: Thu, 16 Aug 2007 11:24:04 -0700 Subject: Tuning - Styling Message-ID: <1187288644.599015.290100@57g2000hsv.googlegroups.com> Cool cars, tuning & styling, modified cars, many upgrades here... http://tuning-styling.blogspot.com/ From franz.steinhaeusler at gmx.at Sun Aug 5 06:14:38 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhäusler) Date: Sun, 05 Aug 2007 12:14:38 +0200 Subject: Best programs written completly in Python Message-ID: Hello NG, wWhat are the best programs in your opinion, written entirly in pyhton, divided into categories like: a) Games b) Utilities/System c) Office d) Web/Newsreader/Mail/Browser ... I don't want to start a long thread, if a site of such an discussion already exists, a link will be enough. Many thanks in advance! -- Franz Steinhaeusler From tzuchien.chiu at gmail.com Wed Aug 22 05:50:16 2007 From: tzuchien.chiu at gmail.com (tzuchien chiu gmail com) Date: Wed, 22 Aug 2007 02:50:16 -0700 Subject: Design philosophy of HTTPServer and BaseHTTPRequestHandler Message-ID: <1187776216.269456.310230@q4g2000prc.googlegroups.com> Hello, everyone. Several instances of a same script, which accepts parameters and does a lengthy job, are executed on a remote machine. I want to couple the script with a tiny HTTP server so that I can connect to the machine with a browser and monitor the progress of jobs. The HTTP server of each instance will bind to different ports. A BaseHTTPRequestHandler-derived class must somehow know the parameters of each instance/job in order to return instance/job- specific result back to the client in do_GET. However, there is no way to pass parameters (of the lengthy job) because the constructor of HTTPServer expects a BaseHTTPRequestHandler-derived "class", instead of an "object". I cannot (or should not) dynamically create a "BaseHTTPRequestHandler- derived "class" for each instance of the script, right? Do I misunderstand the design philosophy of HTTPServer and BaseHTTPRequestHandler, and they should not be used in this way? From tkpmep at hotmail.com Tue Aug 28 10:03:29 2007 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: Tue, 28 Aug 2007 07:03:29 -0700 Subject: int/long bug in locale? Message-ID: <1188309809.592078.58960@22g2000hsm.googlegroups.com> To pretty up some numbers stored as strings, I used locale to format them with commas. I then found the following error: >>> import locale >>>locale.setlocale(locale.LC_ALL, 'English_United States.1252') 'English_United States.1252' >>> locale.format('%d', float('2244012500.0000'), grouping = True) Traceback (most recent call last): File "", line 1, in locale.format('%d', float('2244012500.0000'), grouping = True) File "C:\Python25\lib\locale.py", line 145, in format formatted = percent % value TypeError: int argument required However, if the number is <= 2**31-1, it works just fine: >>>locale.format('%d', float('224401250.0000'), grouping = True) '224,401,250' Interestingly, if I first convert the floats to ints, , the function works just fine, even if the numbers exceed 2**31-1: >>> locale.format('%d', int(float('2244012500.0000')), grouping = True) '2,244,012,500' Is there an int/long related bug lurking in locale? Sincerely Thomas Philips From zyzhu2000 at gmail.com Wed Aug 1 14:01:51 2007 From: zyzhu2000 at gmail.com (beginner) Date: Wed, 01 Aug 2007 18:01:51 -0000 Subject: Assertion in list comprehension In-Reply-To: References: <1185982643.001546.138180@e16g2000pri.googlegroups.com> <46b0bb19$0$14060$9b622d9e@news.freenet.de> Message-ID: <1185991311.411744.182890@x35g2000prf.googlegroups.com> On Aug 1, 12:38 pm, "Chris Mellon" wrote: > On 01 Aug 2007 16:55:53 GMT, Stargaming wrote: > > > > > > > On Wed, 01 Aug 2007 11:28:48 -0500, Chris Mellon wrote: > > > > On 8/1/07, beginner wrote: > > >> Hi, > > > >> Does anyone know how to put an assertion in list comprehension? I have > > >> the following list comprehension, but I want to use an assertion to > > >> check the contents of rec_stdl. I ended up using another loop which > > >> essentially duplicates the functions of list comprehension. It just > > >> look like a waste of coding and computer time to me. > > > >> I just wish I could put the assertions into list comprehensions. > > > >> x=[(rec_stdl[0].st/10000.0, > > >> rec_stdl[0].cl, > > >> rec_stdl[0].bb, > > >> rec_stdl[0].bo, > > >> rec_stdl[1].bb, > > >> rec_stdl[1].bo, > > >> rec_stdl[0].ex > > >> ) > > >> for rec_stdl in rec_by_ex if len(rec_stdl)==2 > > >> ] > > > >> #duplicated loop > > >> if __debug__: > > >> for rec_stdl in rec_by_ex: > > >> l=len(rec_stdl) > > >> assert(l<=2 and l>0) > > >> if l==2: > > >> assert(rec_stdl[0].c=="C" and rec_stdl[1].c=="P") > > >> assert(rec_stdl[0].ex==rec_stdl[1].ex) > > >> assert(rec_stdl[0].st==rec_stdl[1].st) > > >> assert(rec_stdl[0].cp==rec_stdl[1].cp) > > > > First: All your asserts are wrong. Assert is a statement, not a > > > function. These specific ones will behave as expected, but it's easy to > > > accidentally write ones that always pass this way. > > > Could you come up with an example? I can only think of accidentally > > injecting a comma, what would create a (true, in a boolean context) tuple. > > > And, well, if you're only using () for readabilty, this might sometimes > > look messy when calling assert with the extended syntax:: > > > assert(False), "error text" > > It's very easy to write this as assert(False, "error text") if you're > in the habit of thinking that assert is a function. > > > Where one could expect the construction of a tuple. > > > > Secondly: This is a waste of code, because if __debug__ is not defined > > > asserts will be skipped by the compiler. You could use the same loop > > > block for both branches. > > > Well, the `assert` isn't there for no reason, but if you're serious about > > it, `raise` could be better. > > > > Thirdly: This sort of testing is precisely what unit tests and/or > > > doctests are for. > > > Huh? What beginner is doing there seems more like input validation than > > testing. Unit or doctests are meant for testing (and in case of doctests, > > showing) whether a function works as expected. > > Not in a big __debug__ block it isn't. No I was trying to test the logic of my code not validating the contents of the data. Thanks. > > > > -- > >http://mail.python.org/mailman/listinfo/python-list- Hide quoted text - > > - Show quoted text -- Hide quoted text - > > - Show quoted text - From rvtol+news at isolution.nl Sat Aug 11 11:53:11 2007 From: rvtol+news at isolution.nl (Dr.Ruud) Date: Sat, 11 Aug 2007 17:53:11 +0200 Subject: I am giving up perl because of assholes on clpm -- switching to Python References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> <7x4pjq7v69.fsf@ruckus.brouhaha.com> <46aa1986$0$31715$db0fefd9@news.zen.co.uk> Message-ID: RedGrittyBrick schreef: > treasure the saints, tolerate the irritable and > ignore the whiners. *You are what you read.* What is "irritating" to some, is "to the point" to others. That should say enough, but some people just can not stand short replies, they can not hold themselves back from reading all negative kinds of things into them. Too little attention maybe? (I am just making the same mistake to show how it works.) Only rarely someone mistakes the "to the point" for the "irritating", without acknowledging their mistake in the first or second next reply. Newbies with the wrong focus, under pressure, probably suffering lack of sleep? (I am just making things worse.) -- Affijn, Ruud "Gewoon is een tijger." From sbellon at sbellon.de Thu Aug 2 16:30:26 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Thu, 2 Aug 2007 22:30:26 +0200 Subject: Catching SystemExit in C API code when embedding Python? References: <20070802141906.2581c099@cube.tz.axivion.com> <20070802212949.222081eb@cube.tz.axivion.com> Message-ID: <20070802223026.6e931e0e@cube.tz.axivion.com> On Thu, 02 Aug, Farshid Lashkari wrote: > You cannot use PyRun_SimpleString, since it will automatically print > and clear the error. You will need to use PyRun_String instead. Thanks, that helps a lot! -- Stefan Bellon From dobedani at gmx.net Wed Aug 1 09:04:05 2007 From: dobedani at gmx.net (Dobedani) Date: Wed, 01 Aug 2007 06:04:05 -0700 Subject: Plain old SAX and minidom useable? But how then? In-Reply-To: <46B07C0B.70507@web.de> References: <1185969539.653078.287360@w3g2000hsg.googlegroups.com> <46B07C0B.70507@web.de> Message-ID: <1185973445.185359.173130@q75g2000hsh.googlegroups.com> Darsten and Stefan, Yeah, thank you very much! I actually found a good example at http://www.python.org/doc/2.4/lib/dom-example.html Your input was also helpful, so now I have been able to "walk" through the XML and to retrieve the text strings I need: doc = parse(configfile); elems = doc.getElementsByTagName("Environment") for elem in elems: name = elem.getElementsByTagName("Name")[0]; if getText(name.childNodes) == "workspace": ... with getText as defined on the webpage referenced above. Kind regards, Dobedani http://www.python.org/doc/2.4/lib/dom-example.html On Aug 1, 2:26 pm, Stefan Behnel wrote: > Hi, > > calm down, minidom is not easy to use, but it can solve your problem. > > Dobedani wrote: > > I guess I don't know where to look for the right information. I hope > > you guys can help me on the way. I want to retrieve a string from an > > XML-file. If Python were to have XPath available, my problem would be > > solved. The xquery string would be enough and I have already obtained > > that the string. The problem is that I cannot use any add-on - like > > xmllib, sax2 or elementtree - as my customers only have the so-called > > stock Python install - i.e. version 2.4.1. > > Too bad, that rules out lxml.etree (which has XPath and loads of other goodies). > > > Please: where then can I find examples of such use? If I cannot use > > xpath, I would not mind to browse a bit - e.g. using functions like > > getElementByTag() but I don't even know how to use those. TIA > > Try one of these (I looked for "minidom example"): > > http://www.faqs.org/docs/diveintopython/kgp_parse.html > http://docs.python.org/lib/dom-example.html > http://www.cutthecrap.biz/software/whitepapers/minidom.html > > Maybe that helps? > > Stefan From gnewsg at gmail.com Wed Aug 29 07:25:07 2007 From: gnewsg at gmail.com (billiejoex) Date: Wed, 29 Aug 2007 04:25:07 -0700 Subject: tempfile.mkstemp and os.fdopen In-Reply-To: References: <1188323759.955043.317630@19g2000hsx.googlegroups.com> Message-ID: <1188386707.823517.212990@19g2000hsx.googlegroups.com> Gabriel Genellina wrote: > As someone already suggested, why don't you use TemporaryFile or > NamedTemporaryFile and avoid such problems? Because I don't want file to be removed after closing. From koen.vanleemput at gmail.com Thu Aug 30 09:53:01 2007 From: koen.vanleemput at gmail.com (koen.vanleemput at gmail.com) Date: Thu, 30 Aug 2007 13:53:01 -0000 Subject: Sorting a list of Unicode strings? In-Reply-To: <1187608388.772541.251860@22g2000hsm.googlegroups.com> References: <1187542237.139346.6910@o80g2000hse.googlegroups.com> <1187608388.772541.251860@22g2000hsm.googlegroups.com> Message-ID: <1188481981.972728.18020@o80g2000hse.googlegroups.com> Wikipedia in Suomi lists it at the bottom ;-) http://sv.wikipedia.org/wiki/Lista_%C3%B6ver_l%C3%A4nder#.C3.85 Cheers ~K From greg at cosc.canterbury.ac.nz Sat Aug 11 02:05:57 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 11 Aug 2007 18:05:57 +1200 Subject: Threaded Design Question In-Reply-To: <1186788302.998913.76720@d30g2000prg.googlegroups.com> References: <1186683909.797328.68770@i13g2000prf.googlegroups.com> <1186788302.998913.76720@d30g2000prg.googlegroups.com> Message-ID: <5i525dF3kqj4nU1@mid.individual.net> half.italian at gmail.com wrote: > I ended up taking this route for the most part. The worker thread > first moves the file to be processed into a temp directory, No, the watcher thread should do this itself *before* putting it into the work queue. Then there's no chance of it picking up the same file twice before a worker has gotten around to working on it, and there is no need for a custom queue class. -- Greg From horpner at yahoo.com Thu Aug 16 11:59:33 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 16 Aug 2007 15:59:33 GMT Subject: Who told str() to round my int()'s!!! References: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> <9qmvi.47364$s5.1537219@phobos.telenet-ops.be> <3ZudnUuJ68lcxl7bnZ2dnUVZ_t_inZ2d@comcast.com> Message-ID: On 2007-08-16, John Nagle wrote: >>>or the mildy amusing "how do I write bytes not characters to a >>>file" questions at least once a week on this forum. > > Actually, that's a reasonable question, and one that Python didn't do > quite right. > > Remember, in the beginning, Python had only ASCII strings, which > were equivalent to arrays of bytes. Then came Unicode strings. Then > came the restriction of ASCII chars to 0..127. Except that you can > still store binary bytes in ASCII strings, subject to some limitations. > > The next logical step is a complete separation of binary data handling > from text string handling, probably using some type in "numarray" for > arrays of bytes. Python 3000 makes unicode the standard string type, and ushers in a new type name for the old str type called, I think, 'bytes'. So the 3000 devs seem to agree with you to some extent. -- Neil Cerutti Ushers will eat latecomers. --Church Bulletin Blooper From gtcopeland at gmail.com Tue Aug 21 15:47:38 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: Tue, 21 Aug 2007 12:47:38 -0700 Subject: Shed Skin Python-to-C++ compiler 0.0.23 In-Reply-To: References: Message-ID: <1187725658.819624.309370@r34g2000hsd.googlegroups.com> On Aug 20, 7:31 am, "Mark Dufour" wrote: > Hi all, > > I have just released Shed Skin 0.0.23. It doesn't contain the type > inference scalability improvements I was working on, but it does have > quite a few bug fixes and minor feature additions. Here's a list of > changes: > > -support for __iadd__, __imul__ and such (except __ipow__ and __imod__) > -some overdue set optimizations > -fix for string formatting problem (%% did not always work) > -extension module stability fixes > -fix for particular inheritance problem > -other minor bugfixes, cleanups, and error messages > > I could really use some systematic help in pushing Shedskin further. Some ideas: > > -send in bug reports - these are extremely valuable and motivating to > me, yet I don't receive many.. > -find out why test 148 is currently broken under windows > -add datetime, re or socket support > -look into supporting custom classes in generated extension modules > -write a Shedskin tutorial for 'novice' programmers > -systemically test performance and suggest and work on improvements > -investigate replacements for std::string and __gnu_cxx::hash_set > -perform janitorial-type work in ss.py and lib/builtin.?pp > -support extension modules under OSX (OSX gives me accute mental RSI) > -add more tests to unit.py > > Thanks, > Mark Dufour. > -- > "One of my most productive days was throwing away 1000 lines of code" > - Ken Thompson Adding socket support would certainly open the door for many common classes applications. If I had my pick, I say, sockets and then re. BTW, I gatta say projects like shedskin and pypy are the most exciting python projects I'm aware of. Please keep of the good work. I'm so excited about the day I can begin using shedskin for the types of projects I use python on. Greg Greg From oliver at obeattie.com Sat Aug 4 15:07:07 2007 From: oliver at obeattie.com (oliver at obeattie.com) Date: Sat, 04 Aug 2007 12:07:07 -0700 Subject: Encoding DeprecationWarning Message-ID: <1186254427.792114.173170@q75g2000hsh.googlegroups.com> Hey There, Sorry if I am missing something here, but I get a DeprecationWarning when importing a list which has some unicode characters in it (it's a list of countries -- it's being raised on ?land), and I am left wondering why. I am using the syntax u' to denote a unicode string. If anyone would be so kind; what am I doing wrong? Many Thanks, Oliver From ricaraoz at gmail.com Tue Aug 7 08:15:38 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 07 Aug 2007 09:15:38 -0300 Subject: Something in the function tutorial confused me. In-Reply-To: <1186424693.529497.217040@w3g2000hsg.googlegroups.com> References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <1186424693.529497.217040@w3g2000hsg.googlegroups.com> Message-ID: <46B8626A.2070303@bigfoot.com> Lee Fleming wrote: > Thanks for all the help, everyone. I guess I was confused with default > arguments that were mutable and immutable. I will continue to look > over these posts until I understand what is happening. > > I cannot believe the number of helpful responses I got! > Apparently he didn't understand. Neither did I. Either (i)y's initial value (None or []) is saved somewhere to be retrieved every time the function is called without 2nd argument, or (ii) y keeps the value it has when last exiting the function (if there is a third option, please mention it). (i) (a) whenever the function is called without 2nd argument the value None is retrieved and assigned to y, thus causing [] to be assigned to y by the 'if' statement. (i) (b) But then if it is "def f(x, y = [])" the list [] should be ALSO saved somewhere and when the function is called without 2nd argument it should be retrieved and assigned to y, thus y would always be [] when you enter the function without 2nd arg. (ii) (b) if y keeps the value it has when last exiting the function that would explain that the second time you call it the list returned will have two members. (ii) (a) But then if it is "def f(x, Y = None)" when the "if" is evaluated the empty list is assigned to y. So y will NO LONGER be None. The second time the function is called y is NOT None (remember it keeps it's last value) and the function returns a list with two members. So, as I see it, the behavior is not coherent, the function treats y differently according to the value it has assigned. Please correct me! From steve at holdenweb.com Tue Aug 7 12:00:42 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 07 Aug 2007 12:00:42 -0400 Subject: distutils In-Reply-To: <1186497517.224280.126070@22g2000hsm.googlegroups.com> References: <1186489676.042901.236140@w3g2000hsg.googlegroups.com> <1186497517.224280.126070@22g2000hsm.googlegroups.com> Message-ID: vedrandekovic at v-programs.com wrote: > On 7 kol, 14:53, Steve Holden wrote: >> vedrandeko... at v-programs.com wrote: >>> Hello again, >>> Is there any patch for python "distutils", for this >>>>>> from distutils import log,dir_util >>> ImportError: cannot import name log >> What version of Python are you running with? It looks as though there >> may be something wrong with your installation if it's recent: >> >> sholden at bigboy ~/Projects/Python >> $ python >> Python 2.5.1 (r251:54863, May 18 2007, 16:56:43) >> [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin >> Type "help", "copyright", "credits" or "license" for more information. >> >>> from distutils import log >> >>> import distutils.log >> >>> >> > Hello, > > My version of python is 2.4 and I'am running it with Windows XP > Your installation must be corrupted, then: Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Steve>\python24\python Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from distutils import log >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bbxx789_05ss at yahoo.com Tue Aug 7 02:06:57 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 06 Aug 2007 23:06:57 -0700 Subject: read(size=-1) Message-ID: <1186466817.747723.87910@19g2000hsx.googlegroups.com> Suppose I write: f = open("myimg.jpg") f.read(10) According to the docs, ----------- read([size]) Read at most size bytes from the file....The bytes are returned as a string object. ---------- How does python convert a byte to a string? From brett at python.org Thu Aug 23 14:25:24 2007 From: brett at python.org (Brett Cannon) Date: Thu, 23 Aug 2007 11:25:24 -0700 Subject: Issue tracker migration is complete Message-ID: Thanks to the work of Erik Forsberg and Martin von L?wis, Python's issue tracker now lives at http://bugs.python.org . Because this is a new tracker on a new system you cannot use your SourceForge password on the new tracker. But account names have been migrated, so if you go to "Lost your login?" and follow the instructions for SF accounts you can continue to use the same account name on the new tracker (you can also change it once you get a new password). And if you come across any bugs in the tracker, please report them using the "Report Tracker Problem" link. There are a bunch of people to thank for making this all happen. Beyond the huge thanks to Erik (http://efod.se/) and Martin, other people heavily involved include Paul DuBois for coming forward as another tracker admin, the guys at Upfront Systems (http://www.upfrontsystems.co.za/) providing the hosting, Skip Montanaro for working on an anti-spam system, Stefan Seefeld for helping with the test tracker back when this whole process started, the Python Software Foundation's Infrastructure committee for helping choose a tracker, and all the people who participated on the tracker-discuss mailing list. And if I forgot someone, thanks to them as well. =) -Brett Cannon Chairman, PSF Infrastructure committee From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Aug 29 09:02:00 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 29 Aug 2007 15:02:00 +0200 Subject: handling tabular data in python--newbie question In-Reply-To: <6cf42$46d56771$839b8704$5034@news1.tudelft.nl> References: <6cf42$46d56771$839b8704$5034@news1.tudelft.nl> Message-ID: <46d56e43$0$405$426a74cc@news.free.fr> hyena a ?crit : > Hi, > Just jump in python few days. I am wondering how to store and index a > table in python effectively and easily.I think the basic data types are not > very straight foward to handle a table (eg, from csv or data base.) What make you think such a thing ? > I have a csv file, the first row of it is column names and the rest rows > are data. There are some tens of columns and hundreds rows in the file. I am > planning to use the column names as variables to access data, currently I am > thinking of using a dictionary to store this file but did not figure out a > elegant way to start. Use the csv module - it's in the standard lib. It has an option to use dicts to allow keyed access to 'columns' (look for csv.DictReader). Anyway, if you have anything complex to do with your data, you'd probably better use SQLite (possibly using csv module to help importing your data). My 2 cents... From bignose+hates-spam at benfinney.id.au Thu Aug 30 19:28:14 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 31 Aug 2007 09:28:14 +1000 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <87hcmhebwv.fsf@benfinney.id.au> <1188492060.983148.90000@r34g2000hsd.googlegroups.com> Message-ID: <87fy20d2lt.fsf@benfinney.id.au> zzbbaadd at aol.com writes: > On Aug 30, 12:09 am, Ben Finney > wrote: > > It's letting you know that the item isn't in the list. There's no > > sensible return value from an "index" function in that condition. > > for str: > find( sub[, start[, end]]) > [...] > Return -1 if sub is not found. > > -1 is used in other languages as well. It is no more sensible there than in the 'str.find' method, which is a historical wart. -- \ "Hey Homer! You're late for English!" "Pff! English, who needs | `\ that? I'm never going to England!" -- Barney & Homer, _The | _o__) Simpsons_ | Ben Finney From grante at visi.com Wed Aug 22 10:08:35 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 22 Aug 2007 14:08:35 -0000 Subject: Chaining programs with pipe References: <1187734166.384152.178040@o80g2000hse.googlegroups.com> <13cnbi87neru8c3@corp.supernews.com> Message-ID: <13cogr3n6no937b@corp.supernews.com> On 2007-08-22, Steve Holden wrote: > Grant Edwards wrote: >> On 2007-08-21, avishay wrote: >> >>> I'm trying to chain two programs with a pipe (the output of >>> one feeding the input of the other). I managed to capture the >>> output and feeding the input of each program independently >>> with popen, but how do I tie them together? >> >> On Unix, you do the same thing you would in C. Create a pipe >> using os.pipe(), then run one program with stdout connected to >> the "write" end of the pipe and the other program with stdin >> connected to the "read" end of the pipe. >> >> Or you can take a bit of a shortcut by letting the subprocess >> module create the pipe for you: >> >> http://docs.python.org/lib/node536.html >> >>> Is there a solution that works equally on all platforms? >> >> The doc page for subprocess doesn't say what platforms support >> it. I've had a lot of problems trying to use the subprocess >> module on windows. As is typical for Windows, there are all >> sorts of special cases that either don't work at all or don't >> work the way they should. You pays your money and you takes >> your chances. >> > Grant: > > I will shortly have to write some training material on using > subprocess under Windows, so if you have any pointers to where > your accumulated knowledge can be gleaned I would be grateful > for the time saving. There were two main problems I ran into: 1) When you try to execute a program with with a pathname like \\host\path\to\prog.exe instead of R:\path\to\prog.exe, cmd.exe chokes and says it can't execute the file. If you use a UNC path (the "\\" version) you have to use subprocess's shell=False option. [I did find references to a patched version of cmd.exe on a few web pages, but didn't persue that option.] os.system() has the same issue with UNC path names. 2) In a wxPython app (possibly in non-console apps in general?), the child process's stdout and/or stderr didn't default to usable values. When the child tried to write to them you'd get crashes with rather cryptic error messages. Explicitly setting the child's stderr and stdout fixes that. I don't remember os.system() having this problem, since it only cropped up after I switched to subprocess to try to solve 1). In hindsight, these don't seem like big problems, but I tripped over them at the same time and it took me _days_ to figure out what was wrong. I'm sure most Win32 programmers already knew about those problems, but I'm a Unix guy who occasionally tries to ship a Windows version of a Python app: the concept of a process defaulting to having a stderr or stdout that wasn't writable was utterly foreign to me. -- Grant Edwards grante Yow! Mr and Mrs PED, can I at borrow 26.7% of the RAYON visi.com TEXTILE production of the INDONESIAN archipelago? From bricksales at yahpp.com Tue Aug 28 19:32:55 2007 From: bricksales at yahpp.com (Thick as a Brick) Date: Tue, 28 Aug 2007 18:32:55 -0500 Subject: Let's Unite Against Pinheaded midgets ! In-Reply-To: <1188198797.772672.60840@r29g2000hsg.googlegroups.com> References: <1188198797.772672.60840@r29g2000hsg.googlegroups.com> Message-ID: <1188343811_10573@sp12lax.superfeed.net> Nenad Milicevic - The Aryan Serb wrote: > > Serbian Committee for Aryan Defence > Aren't the Serbian population the white trailer trash of every nationality in Europe ? You are going have to do some pretty deep house cleaning to even find a white spot. ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From jmcmonagle at velseis.com.au Thu Aug 2 22:38:09 2007 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Fri, 03 Aug 2007 12:38:09 +1000 Subject: Error with Tkinter and tkMessageBox In-Reply-To: <46b19fe4$0$17952$4fafbaef@reader1.news.tin.it> References: <46af71b7$0$10619$4fafbaef@reader2.news.tin.it> <46b19caa$0$17951$4fafbaef@reader1.news.tin.it> <46b19fe4$0$17952$4fafbaef@reader1.news.tin.it> Message-ID: <46B29511.3010801@velseis.com.au> Fabio Z Tessitore wrote: > I've tried to use Twm and SURPRISE! it works!!! > > Can you say why? How can I fix the prob with Gnome? > > Thanks I don't know why it doesn't work correctly on the version of gnome which you are running (I run KDE). Perhaps the question needs to be posed to a gnome group ? From ldo at geek-central.gen.new_zealand Fri Aug 31 01:20:03 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 31 Aug 2007 17:20:03 +1200 Subject: SAXParseException: not well-formed (invalid token) References: <46D6B9F6.2010402@web.de> <46D6C40F.4060105@cesga.es> Message-ID: In message , Carsten Haese wrote: > If your input string contains the byte 0xe9 where your accented e is, > the file is actually latin-1 encoded. If it contains the byte sequence > 0xc3,0xa9 it is UTF-8 encoded. It is dismaying how often I come across Web pages that claim to be UTF-8-encoded, but are actually Latin-1 or Dimdows-1252. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Aug 14 04:58:53 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 14 Aug 2007 10:58:53 +0200 Subject: Module imports during object instantiation In-Reply-To: References: <4c3vo4-u7k.ln1@learner.hq.netapp.com> Message-ID: <46c16ec9$0$405$426a34cc@news.free.fr> Ritesh Raj Sarraf a ?crit : > Steve Holden wrote: (snip) >> What's leading you to conclude the import isn't being executed? You >> realise, I trust, that the module's code will only be executed on the >> first call to __init__()? >> > > Well. Putting it in a "try" inside __init__() doesn't do anything. This would be highly suprising. > The > import never happens. As soon as your running this code on a platform where os.name yields either 'nt' or 'dos', the import statement is executed. You can bet your ass on this. Now this import can fail for a lot of reasons (imported module not in sys.path, error in the imported module, etc), and since your catching *and dismissing* the ImportError, you don't know what *effectively* happens. It's like someone send you mails, you set your filter to trash mails from this person, and then complain this person never send you mails !-) > And thus if I make a call in any of the methods, it > fails with an error message. A NameError IIRC. "IIRC" ? Inspecting the traceback may help, you know. Anyway, there's a simple way to know what happens: class Log: def __init__(self, verbose, lock = None): self.VERBOSE = bool(verbose) self.lock = bool(lock) if self.lock: self.dispLock = threading.Lock() else: self.dispLock = None if os.name == 'posix': self.platform = 'posix' self.color = get_colors() elif os.name in ['nt', 'dos']: self.platform = 'microsoft' try: import SomeModule except ImportError, e: # comment out next line before going to prod... print >> sys.stderr, e self.color = None else: self.color = SomeModule.get_colors_windows() else: self.platform = None self.color = None This should print the exact ImportError message. Which may help. IMHO. >> You are right in assuming that __init__() is called once per instance >> created, and it's legitimate to make an import conditional in the way >> you have because of the "execute code only once" behavior - if the >> module is already in sys.modules then it won't be re-imported, the >> existing one will be used. >> > > This is what even my understanding is. But am afraid to say that this > understanding is not implemented in Python. Do you *really* believe that no one would have noticed if something as important as the import mechanism was broken ? (snip) > Now I have some questions. > > Going with your point of try/except imports at the top level, I am having > multiple imports at the top level for the multiple classes that I have in > the module. Not everything from the top level imports is required for the > class Log (Say, just one module is what is required). > So when I do a `from module import Log`, do all the modules at the top > level get imported? Yes. > My understanding says Yes, and if that's true, that's > bad IMO. No, that's the right thing to do. When a module is loaded, all the top-level code is executed. period. How else would the class and def statements be executed ? FWIW, modules are supposed to have high cohesion. If you put unrelated things in a same module, then it's *your* design that's bad. > My ultimate goal is to make all my classes as independent as possible while > keeping them as lightweight as possible. If all top level module import > statements are getting executed during a `from module import class`, this > is _not_ lightweight IMO. Since a module is only imported once, this should not be such a concern. It's obviously much more "lightweight" than going thru the import each time you instanciate the class, just to find out that the module is already imported. But anyway, if two classes should be "totally" independant from each other, then what on earth are they doing in the same module ? > That's what led me to try imports in __init__() but unfortunately I haven't > seen that working for me even once. "not working" is not a very useful description of a problem. The import mechanism works and it works fine. Your problem is elsewhere, but you didn't provide enough information for us to help you. From ptmcg at austin.rr.com Wed Aug 1 09:08:07 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 01 Aug 2007 06:08:07 -0700 Subject: Extending Python by Adding Keywords & Data types In-Reply-To: <1185913739.879602.212950@w3g2000hsg.googlegroups.com> References: <1185913739.879602.212950@w3g2000hsg.googlegroups.com> Message-ID: <1185973687.883520.227540@k79g2000hse.googlegroups.com> On Jul 31, 3:28 pm, Maximus Decimus wrote: > > I am using python v2.5 and I am an amateur working on python. I am > extending python for my research work and would like some help and > guidance w.r.t this matter from you experienced python developers. > > II want to add some more KEYWORDS and DATATYPES into the python script > apart from the existing ones. > Vishak - Let me echo the sentiments of the other posters who replied to your message. It is *very* unusual for a new Python user to begin their Pythonic journey by modifying the Python interpreter to add new keywords and datatypes. Python is designed to be a very flexible and extensible language just as it is. Since you are familiar with C, your question strikes those of us on this group as one who would write "I'm just learning C and I would like to modify the core library to add some new functions for my research." And all the readers on comp.lang.c scratch their heads, thinking "Huh? Why doesn't this guy just write the functions in his own program, the way the language was designed for him to do in the first place?" Now maybe your research is in the field of language design, and has something to do with the relative ease/difficulty of modifying computer languages. Then it would make sense for you to dive right in to learning how to modify Python's compiler. But if your research was in just about any other field (from finite elements analysis to genetic programming to genetics to simulations to process control to whatever), DON'T start by modifying Python - start by LEARNING Python. When a new datatype is required in a Python program, then the programmer writes a class to implement this datatype. The class itself is written in Python, but it can be used just like any built-in datatype. For instance, here is a new datatype I just thought up - a Box that can hold up to 'n' objects. class Box(object): def __init__(self,n): self.capacity = n self.contents = [] def add(self,other): if len(self.contents) < self.capacity: self.contents.append( other ) else: raise ValueError("can't add any more to this Box") def __iadd__(self,other): self.add(other) return self box = Box(3) # add stuff to the box until it overflows while(True): box += object() Voila! I created a new datatype, Box, and even added support for it to understand how to use the '+=' operator so that adding objects to the Box looks like an addition statement. All without modifying Python itself. (Here's an exercise - extend this example so that the Box has a limited capacity in the *weight* of the added objects, as well as in the number of objects.) This is the basic way that one extends Python with their own new datatypes and methods. New keywords are a little rarer, but really, start by just adding methods, like the add method above. Python users around the world develop a wide range of applications and programs using just these techniques, and never touch the Python compiler itself. And here is a case you'd like to avoid. Let's say you start by learning how to modify Python because you need a general-purpose container for things. You spend two weeks learning how to do this, getting your code mostly debugged, and then you post to comp.lang.python your proud achievement. Immediately the replies come back, "Congratulations, newbie, you just reinvented the built-in list type." Without LEARNING Python, you wont know what is already provided in the language. So, in general this is a helpful group, and it is possible that you DO need to learn how to add datatypes and keywords to Python as your first objective. We're not trying to pry, but give us a bit more detail. Someone might even rough out for you what one of your new datatypes might look like. So pray, tell us what sort of specialized datatypes and keywords do you think you need to add, and we'll try to point you in one or more directions. -- Paul From hat at se-162.se.wtb.tue.nl Wed Aug 15 10:11:09 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 15 Aug 2007 16:11:09 +0200 Subject: Using python for dynamic behavior from C++ References: Message-ID: On 2007-08-15, Jorgen Bodde wrote: > Hi all, > > I am looking into using Python to introduce dynamic behavior in my > C++, e.g. something like a simulation where objects can interact with > eachother. I know Python can be called from C++, but is it possible to > call a binary compiled Python file / array from C++ ? The reason I ask > is that if my objects call a script every tick to do something, I > would not like to let the python interpreter recompile the same code > over and over again. > > Any pointers to how I can do that? It is called 'embedding the Python Interpreter' and is in the second part of the 'Extending and Embedding the Python Interpreter' document at python dot org. Albert From mfglinux at gmail.com Thu Aug 16 08:55:24 2007 From: mfglinux at gmail.com (mfglinux) Date: Thu, 16 Aug 2007 05:55:24 -0700 Subject: "Variable variable name" or "variable lvalue" In-Reply-To: References: <1187199722.618893.281170@r29g2000hsg.googlegroups.com> Message-ID: <1187268924.412543.127690@r34g2000hsd.googlegroups.com> The solution with the dictionary worked perfectlly well, my script is running and even produces data with sense!!! Thank you very much indeed to all of you answering. Cheers! From davidjl at gol.com Sun Aug 19 23:12:38 2007 From: davidjl at gol.com (David J. Littleboy) Date: Mon, 20 Aug 2007 12:12:38 +0900 Subject: Latest models of Gibson guitars References: <1187544898.289948.322160@22g2000hsm.googlegroups.com> <190820071924351381%rag@nospam.techline.com> Message-ID: <6sGdnRD3kJUvm1TbnZ2dnUVZ_i2dnZ2d@giganews.com> "Randall Ainsworth" wrote: > In article , Hermit > wrote: > >> How does the image quality compare with a DSLR? > > Depends on whether it's a Paul or a Strat. My L5 beats out any dSLR any day. David J. Littleboy Tokyo, Japan From claird at lairds.us Thu Aug 9 09:37:41 2007 From: claird at lairds.us (Cameron Laird) Date: Thu, 9 Aug 2007 13:37:41 +0000 Subject: Issues of state (was: Tkinter or wxpython?) References: <7x8x8mpn37.fsf@ruckus.brouhaha.com> <7xfy2t8l5n.fsf@ruckus.brouhaha.com> Message-ID: <5uhro4-st8.ln1@lairds.us> In article <7xfy2t8l5n.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >claird at lairds.us (Cameron Laird) writes: >> Others have answered this at other levels. In elementary terms, >> there truly is a difference, Paul, and one that's widely reified: >> a "desktop client-server" application typically listens through >> one socket, which therefore constitutes an index of the connection >> or client, while a Web application communicates through a sequence >> of independent HTTP transactions. The latter can manage state only >> to the extent it passes session information around. > >Is this significant? In the case of a single user http app running on >the same computer as the browser, the server should only listen on >127.0.0.1. Every http hit then almost certainly comes from the same >session. If there's doubt, the app can always set a random cookie at >the initial screen and check that the cookie never changes. > >If there's only a small amount of session state (say up to a few >hundred bytes) you can put it entirely into browser cookies and send >it on every single http hit. I'm not sure what we're discussing. Yes, I agree those are mechanisms by which Web applications manage state. Apparently we agree that, in a general Web application, state management, or related persistence, requires *some* mechanism or assumption. From max at alcyone.com Sun Aug 12 05:26:59 2007 From: max at alcyone.com (Erik Max Francis) Date: Sun, 12 Aug 2007 02:26:59 -0700 Subject: Fatest standard way to sum bytes (and their squares)? Message-ID: For a file hashing system (finding similar files, rather than identical ones), I need to be able to efficiently and quickly sum the ordinals of the bytes of a file and their squares. Because of the nature of the application, it's a requirement that I do it in Python, or only with standard library modules (if such facilities exist) that might assist. So far the fastest way I've found is using the `sum` builtin and generators:: ordinalSum = sum(ord(x) for x in data) ordinalSumSquared = sum(ord(x)**2 for x in data) This is about twice as fast as an explicit loop, but since it's going to be processing massive amounts of data, the faster the better. Are there any tricks I'm not thinking of, or perhaps helper functions in other modules that I'm not thinking of? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis Whoever named it necking was a poor judge of anatomy. -- Groucho Marx From aleax at mac.com Sat Aug 25 11:48:34 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 25 Aug 2007 08:48:34 -0700 Subject: Does shuffle() produce uniform result ? References: Message-ID: <1i3e7ul.1ougauneewje9N%aleax@mac.com> tooru honda wrote: > At the end, I think it is worthwhile to implement my own shuffle and > random methods based on os.urandom. Not only does the resulting code > gets rid of the minuscule bias, but the program also runs much faster. > > When using random.SystemRandom.shuffle, posix.open and posix.close from > calling os.urandom account for almost half of the total execution time > for my program. By implementing my own random and getting a much larger > chunk of random bytes from os.urandom each time, I am able to reduce the > total execution time by half. If I were in your shoes, I would optimize by subclassing random.SystemRandom and overriding the random method to use os.urandom with some large block size and then parcel it out, instead of the _urandom(7) that it now uses. E.g., something like: class SystemBlockRandom(random.SystemRandom): def __init__(self): random.SystemRandom.__init__(self) def rand7(): while True: randata = os.urandom(7*1024) for i in xrange(0, 7*1024, 7): yield long(binascii.hexlify(randata[i:i+7]),16) self.rand7 = rand7().next def random(self): """Get the next random number in the range [0.0, 1.0).""" return (self.rand7() >> 3) * random.RECIP_BPF (untested code). No need to reimplement anything else, it seems to me. Alex From david at asdf.asdf Thu Aug 23 05:45:47 2007 From: david at asdf.asdf (bambam) Date: Thu, 23 Aug 2007 19:45:47 +1000 Subject: beginner, idiomatic python Message-ID: <13cqlqbbpn0dmea@corp.supernews.com> Would someone like to suggest a replacement for this? It works ok, but it doesn't look like any of the other code: tempList = ['1','2','3','4','5','6','7','8'] sampleList=[] for port in tempList: pagefound = False for i in range(self.parent.GetPageCount()): page=self.parent.GetPage(i) if hasattr(page, "port"): if page.port == int(port): pagefound=True if not pagefound: sampleList.append(port) Thanks! From bj_666 at gmx.net Fri Aug 10 09:19:00 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Aug 2007 13:19:00 GMT Subject: Does PyModule_GetDict return information about class method variables? References: <1186713277.019869.265820@d30g2000prg.googlegroups.com> <5i2c8rF3kqc46U1@mid.uni-berlin.de> <1186750443.773641.88450@i13g2000prf.googlegroups.com> Message-ID: <5i36u4F3kqc46U4@mid.uni-berlin.de> On Fri, 10 Aug 2007 05:54:03 -0700, MD wrote: > On Aug 10, 12:43 am, Marc 'BlackJack' Rintsch wrote: >> class A(object): >> def foo(self): >> bar = 42 >> >> The local name `bar` only exists if `foo()` is called on an instance of `A`. > > Thanks for your reply. I am calling my extension function from the > class method itself. So at that point the variable does exist. I am > puzzled why PyModule_GetDict is not able to access the variable even > though it does exist at that point. It does not exist in the module or the function object but on the stack. Let's go to C again: void baz(void); void foo(void) { int bar = 42; baz(); } How do you get from `baz()` the value of `foo()`\s local `bar`? Other than ugly non portable stack trickery!? Why don't you just give the object as argument to your C function? Wanting to poke around in the callers name space is code smell. Don't do that. Ciao, Marc 'BlackJack' Rintsch From paddy3118 at googlemail.com Fri Aug 31 05:19:18 2007 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 31 Aug 2007 02:19:18 -0700 Subject: list index() In-Reply-To: <0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188497498.3468.60.camel@dot.uniqsys.com> <0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net> Message-ID: <1188551958.728836.137370@x35g2000prf.googlegroups.com> On Aug 31, 8:47 am, Erik Max Francis wrote: > Hendrik van Rooyen wrote: > > weird this - maybe a native English speaker can comment - > > when I pronounce what fishermen do - it rhymes with roll, > > but when I am talking about the thing that lives under bridges > > and munches goats, the "O" sound is shorter, and more > > towards the back of my mouth. > > Native English accents vary as well, but _roll_ rhymes with _troll_, not > _trawl_. _Trawl_ would rhyme with _fall_, and _fall_ definitely doesn't > rhyme with _roll_. > > -- > Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/ > San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis > I do not like work even when someone else does it. > -- Mark Twain I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll and role similarly. My accent is probably from the East Midlands of the UK, but is not pronounced. - Paddy. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Aug 19 08:30:22 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 19 Aug 2007 14:30:22 +0200 Subject: Hot subject: a good python editor and/or IDE? References: Message-ID: <5iqreuF3qanv6U1@mid.individual.net> S?bastien wrote: > I am currently using Eclipse+PyDev when developping Python > projects but I lack a fast, simple editor for tiny bit of scripts. > So here is my question: what is, for you, the current best ( but > still kind of light! ) Python editor/IDE ? vim BTW, this is an FAQ. Please look through the archives for many threads with many, many IDEs. Regards, Bj?rn -- BOFH excuse #140: LBNC (luser brain not connected) From dejanews at email.com Fri Aug 17 22:32:02 2007 From: dejanews at email.com (samwyse) Date: Sat, 18 Aug 2007 02:32:02 GMT Subject: clarification In-Reply-To: <13cb7frnqs8f6d9@corp.supernews.com> References: <13cb7frnqs8f6d9@corp.supernews.com> Message-ID: Scott David Daniels wrote: > lefts = set() > rights = set() > with open('sheet1', 'r') as fh: > for line in fh: > trimmed = line.strip() > if trimmed: # Skip blanks (file end often looks like that) > left, right = line.strip().split('\t') > lefts.add(left) > rights.add(right) > result = lefts & rights > > -Scott # change to however many columns may later exist cols = [ set() for i in range(0, 2) ] with open('sheet1', 'r') as fh: for line in fh: for col, data in zip(cols, line.strip().split('\t')): col.add(data) result = cols[0] & cols[1] From __peter__ at web.de Thu Aug 23 07:34:38 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 23 Aug 2007 13:34:38 +0200 Subject: sentance containg the string or symbol ? References: <1187868007.012689.224290@z24g2000prh.googlegroups.com> Message-ID: yadin wrote: > how can i print a sentance containg the string or symbol ? in python > and also lambda? The most robust way is to use unicode strings: >>> print u"? and also \N{GREEK CAPITAL LETTER LAMDA}" ? and also ? If you use literals like the omega above you also have to specify the encoding of your script in the first or second line, typically # -*- coding: utf-8 -*- Only 8-bit encodings are allowed. Peter From paul at boddie.org.uk Mon Aug 13 14:03:01 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 13 Aug 2007 11:03:01 -0700 Subject: Adventure-Engines in Python In-Reply-To: References: <46C0255A.4080707@freakmail.de> Message-ID: <1187028181.091616.177070@d55g2000hsg.googlegroups.com> Wildemar Wildenburger wrote: > > OK, thanks. I should, of course, have been more specific. By saying > "adventure" I mean the graphical variant (say, Monkey Island or Broken > Sword), preferably but not necessarily in 2D. Perhaps you could get a start from this game: http://www.pygame.org/projects/23/300/ > I've also found vidaG, but it seems dead as well. I'll keep looking but > if you know something, please let me know. I imagine you can pester the developer here: http://dodgyville.livejournal.com/ Paul From ca.allen at gmail.com Fri Aug 3 14:47:53 2007 From: ca.allen at gmail.com (Chris Allen) Date: Fri, 03 Aug 2007 11:47:53 -0700 Subject: Global package variable, is it possible? In-Reply-To: <46b36b31$0$10622$4fafbaef@reader2.news.tin.it> References: <1186160415.065108.139160@e9g2000prf.googlegroups.com> <46b36b31$0$10622$4fafbaef@reader2.news.tin.it> Message-ID: <1186166873.485756.290100@i13g2000prf.googlegroups.com> On Aug 3, 10:51 am, Fabio Z Tessitore wrote: > Heve you tried to do something like: > > # module configure.py > value1 = 10 > value2 = 20 > ... > > # other module > from configure import * > > # now I'm able to use value1 value2 etc. > var = value1 * value2 > > bye Thanks for the response Fabio. I thought about this, but I don't think this will work well in my situation either. Take a look at the following: __init__py: ####################### _default_cfgfile = 'config.conf' from configure import * cfg = loadcfg(_default_cfgfile) import pkg_module1 import pkg_module2 # EOF configure.py: ######################## from ConfigParser import SafeConfigParser def loadcfg(filename): file = open(filename) cfg = SafeConfigParser() cfg.readfp(file) return cfg # EOF pkg_module1: ######################## _default_cfgfile = 'config.conf' from configure import * cfg = loadcfg(_default_cfgfile) # EOF One problem I see with this approach is that we must define the configuration file in every module. Alternatively a better approach would be to only define the configuration file within configure.py, however this also seems less than ideal. I don't like it because I believe something as important as the location of the package configuration file, used by all modules, should defined in __init__ not tucked away in one of it's modules. Another problem is that after the package is loaded and we want to load in a new config file, what will happen? With this approach we'll have to reload every module the package uses for them to read the new config. And even then, how do we tell each module what the new config file is? If I did define the configuration file in configure.py then I suppose what I could do is set a cfgfile variable in configure.py to the new file location and reload all the modules. If there is no global package variables, then maybe this isn't so bad... Hmm. So maybe something like this makes sense: __init__py: ####################### _default_cfg_file = 'config.conf' import configure def loadcfg(filename): configure.cfgfile = filename try: reload(pkg_module1) reload(pkg_module2) except NameError: pass cfg = loadcfg(_default_cfg_file) import pkg_module1 import pkg_module2 # EOF confgure.py: ####################### cfgfile = None def loadcfg() global cfgfile if not cfgfile: return None file = open(cfgfile) cfg = SafeConfigParser() cfg.readfp(file) return cfg # EOF pkg_module1: ####################### import configure cfg = configure.loadcfg() # EOF It's a little bit convoluted, but I think it solves most of my gripes. Anybody have a better idea of how to do this? Thanks again Fabio. From mail at microcorp.co.za Sat Aug 18 02:55:54 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 18 Aug 2007 08:55:54 +0200 Subject: best GUI library for vector drawing program References: <1187357244.883516.79840@j4g2000prf.googlegroups.com> <46c5c3b9$0$36443$4fafbaef@reader5.news.tin.it> Message-ID: <014b01c7e169$bd20af40$03000080@hendrik> "pierbr....e.it" wrote: > I used wxWidgets for a work like that. I found it quite easy to use and > I found simple to create a Gui with wxdev which is quite rad. > bye > Pier Paolo There is also pycad, but apart from knowing that it exists, I know nothing about it. - Hendrik From oliver at ootbc.com Sat Aug 18 13:02:53 2007 From: oliver at ootbc.com (Oliver Nelson) Date: Sat, 18 Aug 2007 17:02:53 GMT Subject: Canceling events on COM Objects in python In-Reply-To: <1187445274.964435.267010@q4g2000prc.googlegroups.com> References: <8Yuxi.5292$924.612@newssvr23.news.prodigy.net> <1187445274.964435.267010@q4g2000prc.googlegroups.com> Message-ID: <1DFxi.46799$Um6.17796@newssvr12.news.prodigy.net> Mike, Thank you for the suggestion. I will ask over there also. The event is sent back from the COM interface as the code illustrates. MakeActiveXClass allows me to pass the object that will receive events. I don't understand much more detail about how it works. It is certainly a different model than the standard wx event system... OLIVER kyosohma at gmail.com wrote: > On Aug 17, 11:54 pm, Oliver Nelson wrote: >> I have MapPoint working in Python, and I'm trying to cancel events on >> the map, but I can't seem to make that happen. I'm responding to the >> events successfully in my panel object. My code is like this: >> >> global MapPointMod >> MapPointMod = >> win32com.client.gencache.EnsureModule("{51C0A9CA-F7B7-4F5A-96F4-43927C6FA50F}", >> 0, 1, 0) >> >> class MyPanel(wx.Panel): >> def __init__(self, *args, **kwds): >> # begin wxGlade: MyPanel.__init__ >> kwds["style"] = wx.TAB_TRAVERSAL >> wx.Panel.__init__(self, *args, **kwds) >> self.frame = args[0] >> >> MyMap = MakeActiveXClass(MapPointMod.MappointControl, >> eventObj=self) >> self.window_1 = MyMap(self, -1) >> self.window_1.OpenMap("C:\\TEMP\\GPS_ON.ptt") >> ... >> ... >> def OnBeforeClick(self, Button, Shift, X, Y, Cancel): >> print "tada" >> >> My event fires just fine, but I can't seem to figure out how to cancel >> the event so that mappoint doesn't do its stuff with it...I've tried >> setting Cancel based on the mappoint specs, but it doesn't seem to get >> sent back anywhere... >> >> Any ideas please? >> >> Thanx, >> >> OLIVER > > This probably isn't the best place to post questions of this nature. > You should try the wxPython's user group or the pywin32 group. > > http://wxpython.org/maillist.php > http://mail.python.org/mailman/listinfo/python-win32 > > Is the event you're trying to cancel caught by wxPython's event > handlers or win32? > > Mike > From arnau at ehas.org Thu Aug 9 13:01:05 2007 From: arnau at ehas.org (Arnau Sanchez) Date: Thu, 09 Aug 2007 19:01:05 +0200 Subject: how to get command output using python In-Reply-To: References: Message-ID: <46BB4851.6040605@ehas.org> Steven Harms escribi?: > In python it is quite easy: > > import commands > status, output = commands.getstatusoutput("my command") Uhm, this module has a big issue: (http://docs.python.org/lib/module-commands.html) ---- 8.17 commands -- Utilities for running commands Availability: Unix. ---- Any non cross-platform module should be avoided unless absolutely necessary. Subprocess is the right module to use. arnau From S.Mientki-nospam at mailbox.kun.nl Sun Aug 5 04:45:11 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sun, 05 Aug 2007 10:45:11 +0200 Subject: Pyscripter In-Reply-To: <1186302328.706942.242920@q75g2000hsh.googlegroups.com> References: <1186302328.706942.242920@q75g2000hsh.googlegroups.com> Message-ID: <10a14$46b58c8d$d443bb3a$18267@news.speedlinq.nl> RichSaneSwindler wrote: > I think that pyscripter is the most promising Python IDE around but for windows only ! and I > am exciting about its possibilities. However, I find a few issues with > it annoying enough that I don't use it. They seem easily fixed in > which case I think it would be superior to most IDEs. I am wondering > if any users out there would like to add to/debate this list of > benefits and issues (for reference I am using Pyscripter > Neil, PyScripter has it's own discussion list http://groups.google.com/group/PyScripter/topics?hl=en and from my own experiences, I know that Kiriakos (the designer) is very willing to listen to good ideas, and if they are good he'll implement them in no time ! cheers, Stef From arnau at ehas.org Thu Aug 9 16:37:06 2007 From: arnau at ehas.org (Arnau Sanchez) Date: Thu, 09 Aug 2007 22:37:06 +0200 Subject: how to get command output using python In-Reply-To: <1186681910.789048.132140@z24g2000prh.googlegroups.com> References: <1186681910.789048.132140@z24g2000prh.googlegroups.com> Message-ID: <46BB7AF2.3010607@ehas.org> kyosohma at gmail.com escribi?: >> Any non cross-platform module should be avoided unless absolutely necessary. >> >> Subprocess is the right module to use. >> >> arnau > > You forgot to mention that subprocess replaces commands, so in effect, > commands is deprecated anyway. It was implicit :-) Anyway, these modules ("commands", "popen2", ...) are not officially deprecated (at least in 2.5), so it's not strange that newcomers sometimes choose (wrongly) them. From rupole at hotmail.com Thu Aug 16 20:21:45 2007 From: rupole at hotmail.com (Roger Upole) Date: Thu, 16 Aug 2007 20:21:45 -0400 Subject: Cancelling events on a COM Object References: Message-ID: <1187309979_991@sp12lax.superfeed.net> Oliver Nelson wrote: >I have MapPoint working in Python, and I'm trying to cancel events on the map, but I can't seem to make that happen. I'm >responding to the events successfully in my panel object. My code is like this: > > global MapPointMod > MapPointMod = win32com.client.gencache.EnsureModule("{51C0A9CA-F7B7-4F5A-96F4-43927C6FA50F}", 0, 1, 0) > > class MyPanel(wx.Panel): > def __init__(self, *args, **kwds): > # begin wxGlade: MyPanel.__init__ > kwds["style"] = wx.TAB_TRAVERSAL > wx.Panel.__init__(self, *args, **kwds) > self.frame = args[0] > > MyMap = MakeActiveXClass(MapPointMod.MappointControl, eventObj=self) > self.window_1 = MyMap(self, -1) > self.window_1.OpenMap("C:\\TEMP\\GPS_ON.ptt") > ... > ... > def OnBeforeClick(self, Button, Shift, X, Y, Cancel): > print "tada" > > > My event fires just fine, but I can't seem to figure out how to cancel the event so that mappoint doesn't do its stuff with > it...I've tried setting Cancel based on the mappoint specs, but it doesn't seem to get sent back anywhere... > > Any ideas please? > > Thanx, > > OLIVER Instead of assigning to the variable name, output parameters need to be returned from the method Roger From korovev76 at gmail.com Tue Aug 7 02:55:10 2007 From: korovev76 at gmail.com (korovev76 at gmail.com) Date: Mon, 06 Aug 2007 23:55:10 -0700 Subject: parsing a dbIII file Message-ID: <1186469710.277542.246430@w3g2000hsg.googlegroups.com> Hello everybody, I'm new to python (...I work with cobol...) I have to parse a file (that is a dbIII file) whose stucture look like this: |string|, |string|, |string that may contain commas inside|, 1, 2, 3, | other string| Is there anything in python that parses this stuff? thanks a lot korovev From aboudouvas at panafonet.gr Sat Aug 4 19:05:30 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Sat, 04 Aug 2007 16:05:30 -0700 Subject: Eclipse/PyDev question. In-Reply-To: References: <1186153119.391091.275860@r34g2000hsd.googlegroups.com> Message-ID: <1186268730.360593.160410@22g2000hsm.googlegroups.com> News" (or, news to me :) ) The creator of PyDev, contacted me and told me that latest version of PyDev need not require the whole SDK but only the Runtime Platfom is OK. That means that we download only the 40MB file (and not the 120 one) and this does not include all the Java stuff that we see in SDK. So, combined with PyDev, we have an editor just for Python! I test it a few hours now and it is really fast! From laurent.pointal at limsi.fr Thu Aug 16 02:47:58 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Thu, 16 Aug 2007 08:47:58 +0200 Subject: Python Book Recommendations In-Reply-To: <1187191803.845011.30400@x35g2000prf.googlegroups.com> References: <1b31ae500708141638w77614014o6f382d0389bc69df@mail.gmail.com> <1187191803.845011.30400@x35g2000prf.googlegroups.com> Message-ID: Azazello a ?crit : > On Aug 15, 7:47 am, "Shawn Milochik" wrote: >> If I could have only one book, I would buy "Core Python, Second >> Edition," by Wesley Chun. >> >> For the record, I own: >> Core Python, Second Edition (great) >> wxPython in Action (haven't used yet) >> Beginning Python (barely used) >> Python in a Nutshell (use as a reference, although interactive python >> dir() is more useful) >> Dive into Python (great book) >> Python Cookbook (great book) >> Python Pocket Reference (not very useful) >> Python Phrasebook (I love the Phrasebook series, but this isn't a >> necessary book) > > I would like to add: > > Foundations of Python Network Programming There was a review about this one on slashdot: http://books.slashdot.org/books/04/10/13/1815209.shtml?amp;tid=192&tid=6 > > I also use the Python Essential Reference. (although all of the > information is probably online it's nice to have a solid paper > reference) > From jstroud at mbi.ucla.edu Fri Aug 24 13:58:28 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 24 Aug 2007 17:58:28 GMT Subject: How to replace a method in an instance. In-Reply-To: References: <1187971953.261328.219000@q3g2000prf.googlegroups.com> Message-ID: <8%Ezi.34724$2v1.10476@newssvr14.news.prodigy.net> Steven W. Orr wrote: > Ok. I have a collection of classes that are produced by a factory. They > all inherit from a baseclass. One (maybe more) of the classes inherits a > method that he shouldn't. All I want is to be able to change that > particular class so that he will have the special method that he needs > instead of the default one that he inherits. I was thinking that instead > of making a special class for CC to inherit from which would give him his > special replacement method(s), I could simply assign them in a manner > which would more easily lend itself to later being table driven. > > If I had a choice, I'd rather not do it in init. Instead, I'd rather be > able to say something like > CC.m1 = repmeth > but since in the real world, CC inherits from his baseclass, the above > assignment causes the baseclass to be altered. :-( > > Please tell me if I need to provide more. def f1(self): print 'f1' def f2(self): print 'f2' def classfactory(replacements=None): class _C(object): def doit(self): print 'doit' def doit2(self): print 'doit2' if replacements is not None: for fname, f in replacements.items(): setattr(_C, fname, f) return _C Aclass = classfactory() Aclass().doit() Aclass2 = classfactory({'doit':f1, 'doit2':f2}) Aclass().doit2() Aclass2().doit2() Here's the output: py> def f1(self): ... print 'f1' ... py> def f2(self): ... print 'f2' ... py> def classfactory(replacements=None): ... class _C(object): ... def doit(self): ... print 'doit' ... def doit2(self): ... print 'doit2' ... if replacements is not None: ... for fname, f in replacements.items(): ... setattr(_C, fname, f) ... return _C ... py> Aclass = classfactory() py> Aclass().doit() doit py> py> Aclass2 = classfactory({'doit':f1, 'doit2':f2}) py> Aclass().doit2() doit2 py> Aclass2().doit2() f2 James From conra2004 at yahoo.com Fri Aug 17 12:27:31 2007 From: conra2004 at yahoo.com (yadin) Date: Fri, 17 Aug 2007 09:27:31 -0700 Subject: help to make program better Message-ID: <1187368051.235289.76520@w3g2000hsg.googlegroups.com> hi! Can any one tell me why is it that i can't see my second frame and why is the value of freq not Appended in the First frame ...thanks I know it is wx python but it has to do with passing variables.thanks import wx def create(parent): return Frame1(parent) [wxID_FRAME1, wxID_FRAME1FREQ, wxID_FRAME1FREQDISP, wxID_FRAME1STATICTEXT1, ] = [wx.NewId() for _init_ctrls in range(4)] class Frame1(wx.Frame): def _init_ctrls(self, prnt): # generated method, don't edit wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt, pos=wx.Point(380, 179), size=wx.Size(241, 133), style=wx.DEFAULT_FRAME_STYLE, title='Frame1') self.SetClientSize(wx.Size(233, 99)) self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1, label='frequency disp', name='staticText1', parent=self, pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) self.freqdisp = wx.TextCtrl(id=wxID_FRAME1FREQDISP, name='freqdisp', parent=self, pos=wx.Point(104, 24), size=wx.Size(100, 21), style=0, value='') self.freq = wx.Button(id=wxID_FRAME1FREQ, label='get freq', name='freq', parent=self, pos=wx.Point(24, 56), size=wx.Size(184, 23), style=0) self.freq.Bind(wx.EVT_BUTTON, self.OnButton1Button, id=wxID_FRAME1FREQ) def __init__(self, parent): self._init_ctrls(parent) def OnButton1Button(self, event): def create(parent): return Frame2(parent) [wxID_FRAME2, wxID_FRAME2FREQ, wxID_FRAME2FREQDISP, wxID_FRAME2STATICTEXT1,] = [wx.NewId() for _init_ctrls in range(4)] class Frame2: def __init__(self): # wx.Frame.__init__(self, id=wxID_FRAME2, name='', parent=prt, pos=wx.Point(400, 179), size=wx.Size(300, 133), style=wx.DEFAULT_FRAME_STYLE, title='Frame2') self.SetClientSize(wx.Size(233, 99)) self.staticText1 = wx.StaticText(id=wxID_FRAME2STATICTEXT1, label='frequency goes here first', name='staticText2', parent=self, pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) self.freqdisp2 = wx.TextCtrl(id=wxID_FRAME2FREQDISP, name='freqdisp2', parent=self, pos=wx.Point(104, 24), size=wx.Size(100, 21), style=0, value=' ') self.freq = wx.Button(id=wxID_FRAME2FREQ, label='get freq', name='freq', parent=self, pos=wx.Point(24, 56), size=wx.Size(184, 23), style=0) self.freq.Bind(wx.EVT_BUTTON, self.OnButton2Button, id=wxID_FRAME2FREQ) def __init__(self, parent): self._init_ctrls(parent) def OnButton2Button(self, event): freqdisp.Append('this is it 24HZ!') Show() if __name__ == '__main__': app = wx.PySimpleApp() frame = create(None) frame.Show() app.MainLoop() From sjdevnull at yahoo.com Sun Aug 26 14:49:12 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Sun, 26 Aug 2007 11:49:12 -0700 Subject: lisper learning python, ... could you please comment my first python program? In-Reply-To: <1188150028.716338.64390@57g2000hsv.googlegroups.com> References: <1188143768.742884.38520@r29g2000hsg.googlegroups.com> <1188150028.716338.64390@57g2000hsv.googlegroups.com> Message-ID: <1188154152.874376.195090@22g2000hsm.googlegroups.com> Michele Simionato wrote: > On Aug 26, 5:56 pm, neptundan... at gmail.com wrote: > > Hi, > > to extend my skills, I am learning python. I have written small > > program which computes math expression like "1+2*sin(y^10)/cos(x*y)" > > and similar, so far only + - * / ^ sin con tan sqrt are supported. But > > my program is quite inextensible, I have to change the code to add new > > functions... Could some fellow experienced pythonista give me some > > tips how to make my program shorter, and more extensible? > > BTW, since you are familiar with Lisp, I would recommend you > IPython for a better interactive experience. IPython's got great support for saving and using old results and a lot of other things. It's borderline unreadable for stack traces out of the box, though; putting "xtrace Plain" in your ipythonrc helps a lot. The color options (either turning it off or making it light/dark background appropriate) are also quite important to having it at all usable; depending on your default bg color that may not be an issue. And if you want to have a view of your data that's similar to the rest of the Python world (useful if you ever intend for others to look at your output or you to look at theirs), "pprint 0" is nice too. Sorry if that sounds like it's an indictment--it's a very nice shell aside from a few output weirdnesses that are easily configured. From andrew.arobert at gmail.com Thu Aug 30 19:48:43 2007 From: andrew.arobert at gmail.com (andrew.arobert at gmail.com) Date: Thu, 30 Aug 2007 23:48:43 -0000 Subject: Automation and scheduling of front page publishing using python Message-ID: <1188517723.279932.299400@x40g2000prg.googlegroups.com> Good afternoon, We have numerous web sites which are currently being manually published via Front Page. Doing one or two sites on an ad-hoc basis was not too bad but we are now over 20 or thirty at set times during a business day. What I would love to do is find a way of automating this task, ideally by the command line, and called from a central automated task scheduler such as Maestro. Using Cygwin's rsync or Microsoft's Robocopy successfully moves a site from one file system path to another but the front page extensions and navigation/etc are broken. Does anyone know of an alternative method for handling this using Python? I did a google search and a scan of the cheese shop but nothing seems to jump out as a place to start. Any advice you can give on this would be fantastic. I've been trying to introduce Python to my shop for some time but they have been most resistant, usually insisting on Perl. Thanks, Andy From bignose+hates-spam at benfinney.id.au Thu Aug 9 09:29:35 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 09 Aug 2007 23:29:35 +1000 Subject: Help with Dictionaries and Classes requested please. References: <46bacae3$0$89254$7b0f0fd3@mistral.news.newnet.co.uk> <46bacf1b$0$54289$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <87ejic6dkw.fsf@benfinney.id.au> "special_dragonfly" writes: > I've managed to solve the problem, I really was just being a > dunce. Doubtful; but at this stage we can't tell, because we still don't know what it is you're actually trying to *do*. > Here's how incase anyone is wondering: > > class MyClass: > def __init__(self): > name="" > dict={} > dict[0]=[] > dict[0].append(MyClass()) > dict[0][0].name="Hello" > print dict[0][0].name It's not clear why you are using the value 0 for a dictionary key here; nor why you're assigning an attribute to an object after creating the object. Neither of them are errors, but without context it's hard to know what advice to give. -- \ "When we call others dogmatic, what we really object to is | `\ their holding dogmas that are different from our own." -- | _o__) Charles Issawi | Ben Finney From redtiger84 at googlemail.com Tue Aug 7 14:25:43 2007 From: redtiger84 at googlemail.com (Christoph Krammer) Date: Tue, 07 Aug 2007 11:25:43 -0700 Subject: re.sub does not replace all occurences In-Reply-To: References: <1186507704.440408.20630@57g2000hsv.googlegroups.com> Message-ID: <1186511143.394471.236020@b79g2000hse.googlegroups.com> Neil Cerutti schrieb: > In other words, the fourth argument to sub is count, not a set of > re flags. I knew it had to be something very stupid. Thanks a lot. From DustanGroups at gmail.com Sun Aug 12 20:35:21 2007 From: DustanGroups at gmail.com (Dustan) Date: Mon, 13 Aug 2007 00:35:21 -0000 Subject: A dumb question about a class In-Reply-To: References: Message-ID: <1186965321.741540.108820@k79g2000hse.googlegroups.com> On Aug 12, 5:09 pm, Steven Bethard wrote: > def iter_primes(): > # an iterator of all numbers between 2 and +infinity > numbers = itertools.count(2) > > # generate primes forever > while True: > > # get the first number from the iterator (always a prime) > prime = numbers.next() > yield prime > > # remove all numbers from the (infinite) iterator that are > # divisible by the prime we just generated > numbers = itertools.ifilter(prime.__rmod__, numbers) This is kind of OT (from the thread), but in this iter_primes function, numbers is becoming an ifilter of an ifilter of an ifilter of an ifilter of an ifilter of an ifilter of... Is that really at all efficient for larger numbers (millions or billions, or even bigger)? From sbellon at sbellon.de Thu Aug 2 15:29:49 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Thu, 2 Aug 2007 21:29:49 +0200 Subject: Catching SystemExit in C API code when embedding Python? References: <20070802141906.2581c099@cube.tz.axivion.com> Message-ID: <20070802212949.222081eb@cube.tz.axivion.com> On Thu, 02 Aug, Farshid Lashkari wrote: > Also, here is some sample code that will catch system exit exceptions: > > //Call python code > ... > //Check for system exit exception > if(PyErr_Occurred()) { > if(PyErr_ExceptionMatches(PyExc_SystemExit)) { > //handle system exit > PyErr_Clear(); > } else { > PyErr_Print(); > } > } Thanks for your hints ... The interesting part is "Call python code". In my example this is done with PyRun_SimpleString which does not return if an exception is not handled but raised "out of" the interpreter. So I am unsure of what you mean with "Call python code". When installing an excepthook (see my other posting), then I can indeed catch all exceptions ... except for SystemExit which is the one I'm after. -- Stefan Bellon From labrach at gmail.com Thu Aug 30 07:19:03 2007 From: labrach at gmail.com (labrach at gmail.com) Date: Thu, 30 Aug 2007 04:19:03 -0700 Subject: python + gcov In-Reply-To: <1188404571.590476.265840@r34g2000hsd.googlegroups.com> References: <1188404571.590476.265840@r34g2000hsd.googlegroups.com> Message-ID: <1188472743.570376.120390@o80g2000hse.googlegroups.com> Some precisions : I've forced the configuration options with the followings flags in the Makefile.pre : OPT='-Wall -fprofile-arcs -ftest-coverage -pg' BASECFLAGS='-Wall -fprofile-arcs -ftest-coverage -pg' LDFLAGS='-Wall -fprofile-arcs -ftest-coverage -pg' XLINKER='-Wall -fprofile-arcs -ftest-coverage -pg' But, the coverage files are not produced by a simple : python -c 'print "Hello"' while the gmon.out is produced Another questions is: the wrapped c++ module is also compile with -pg flags (and -fprofile- arcs -ftest-coverage as well) but the profile information does not appear in the gmon.out Do I need to make a static extension of my imported module to profile it ? thanks anyone ... laurent On 29 ao?t, 18:22, labr... at gmail.com wrote: > Hi > I want to profile (and analyse coverage) some c++ code imported as apythonmodule > I've compiledpython(2.4.2) with gcc 3.4.3 and flags=-Wall -fprofile- > arcs -ftest-coverage in order to usegcov. However, thepythonbinary > does not generate any coverage file (such than *.gcno, gcda) during > execution. > any tips ? > or may be another method to profile c++ wrapped modules withinpython? > > thanks > > laurent From larry.bates at websafe.com Mon Aug 6 15:02:21 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 06 Aug 2007 14:02:21 -0500 Subject: amra and py2exe In-Reply-To: <1186175685.531985.207190@e9g2000prf.googlegroups.com> References: <1186175685.531985.207190@e9g2000prf.googlegroups.com> Message-ID: <46B7703D.3020104@websafe.com> vinod wrote: > Hi i am having trouble creating exe using py2exe for amara package > i saw some posts related to this talking about amara cat file but i > dont have any cat file for amara on my machine. > the standalone script runs fine. i am using python on windows > here is the error i am getting while creating the exe > The following modules appear to be missing > ['amara', 'ext.IsDOMString', 'ext.SplitQName'] > > can anybody please help me with this? > > Thanks, > Vinod > You should post this on gmane.comp.python.py2exe newsgroup. -Larry From kyosohma at gmail.com Sat Aug 4 11:59:53 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Sat, 04 Aug 2007 08:59:53 -0700 Subject: the one python book In-Reply-To: References: Message-ID: <1186243193.751427.39490@q3g2000prf.googlegroups.com> On Aug 4, 8:23 am, "dhr" wrote: > newbie question: > > Is there a 'K&R" type of Python book? The book that you'd better have on > your shelf if you are going into Python? I would recommend "Programming Python 3rd Ed." by Lutz or "Core Python Programming" by Chun. Lutz has more examples than Chun, but Chun has lots of good information about the language's history. Both authors share interesting facts about the language, some of which are pretty obscure. Lutz has good case studies though, so it may be slightly more valuable. Mike From steven.bethard at gmail.com Fri Aug 10 13:09:59 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 10 Aug 2007 11:09:59 -0600 Subject: is there anybody using __del__ correctly?? In-Reply-To: <1186762908.121319.35900@x35g2000prf.googlegroups.com> References: <1186731369.073644.158490@z24g2000prh.googlegroups.com> <1186762908.121319.35900@x35g2000prf.googlegroups.com> Message-ID: Raymond Hettinger wrote: > [Michele Simionato] >> Here and there I hear rumors about deprecating __del__ and >> nothing >> happens, are there any news about that? Expecially concerning Py3k? > > I was writing a Py3K PEP advocating the elimination of __del__ > because: > > * 'with closing()' and try/finally are the preferred ways of calling > close() > > * it is easy to accidently keep or introduce a reference that blocks > the __del__ logic > > * under-the-hood, the implementation of __del__ clashes badly with GC > logic and is a maintenance nightmare > > * the body of a __del__ method may unintentionally resurrect an object > that was in the process of being deleted > > For the PEP to have a chance, I neede to make build-outs to the > weakref module so that existing use cases for __del__ can be easily > migrated. That hasn't been done yet, so the campaign to eliminate > __del__ is stalled. There were also a few recipes posted during this discussion that wrap weakrefs up a bit nicer so it's easier to use them in place of __del__: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/519635 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/519610 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/519621 Since they're using weakrefs, you shouldn't have to worry about some of the weirdness of __del__. STeVe From coolmann123 at hotmail.com Sun Aug 12 05:46:15 2007 From: coolmann123 at hotmail.com (Hasipups) Date: Sun, 12 Aug 2007 02:46:15 -0700 Subject: Very Intressting Message-ID: <1186911975.907216.191110@l70g2000hse.googlegroups.com> http://www.pennergame.de/ref.php?uid=5572 From bj_666 at gmx.net Tue Aug 21 04:15:44 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Aug 2007 08:15:44 GMT Subject: File Read Cache - How to purge? References: <1187669203.698637.81990@i38g2000prf.googlegroups.com> Message-ID: <5ivl9fF3rafecU1@mid.uni-berlin.de> On Mon, 20 Aug 2007 21:06:43 -0700, Signal wrote: > 1. I don't quite understand how after one full read of a file, another > full read of the same file is "cached" so significantly while > consuming so little memory. What exactly is being cached to improve > the reading of the file a second time? What do you mean by so little memory? It (the whole file) is cached by the operating system totally independent of your program, so the memory used does of course not show up in the memory stats of your program. Just think about this: some file `a.dat` is cached by the OS and you start a program that might eventually read that file. The memory is used already *before* the program starts and the OS does not know in advance which files will be read by the program. So how, why and when should the memory used for the cache should be added to the programs memory stats. > 2. Is there anyway to somehow to take advantage of this "caching" by > initializing it without reading through the entire file first? You mean reading the file without actually reading it!? :-) > 3. If the answer to #2 is No, then is there a way to purge this > "cache" in order to get a more accurate result in my routine? That is > without having to read another large file first? AFAIK no. Ciao, Marc 'BlackJack' Rintsch From rcdailey at gmail.com Thu Aug 16 18:01:05 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 16 Aug 2007 17:01:05 -0500 Subject: Pass by reference or by value? In-Reply-To: References: <496954360708161402x58faba47x7a6eae6e68f81d4@mail.gmail.com> Message-ID: <496954360708161501s541bddb7vfe168e4863f7f1e@mail.gmail.com> So immutable objects cannot be modified directly? I guess this means integers are immutable and the act of assigning to one is a completely new definition? So if I were to create a class called Integer and give it a .set() method, this would allow me to create mutable integers, and thus passing in an object of type class Integer would allow me to modify the value from inside the function? On 8/16/07, Steve Holden wrote: > > Robert Dailey wrote: > > Hi, > > > > I previously created a topic named "Pass by reference or by value" where > > I inquired on how python's function parameters work. I received a lot of > > nice responses, however I'm still confused on the topic. Note that I > > come from a C++ background to Python, so any comparisons to C++ would be > > very helpful. > > > > I ran a few tests. There's two tests in particular I wanted to show you > > guys: > > > ------------------------------------------------------------------------------------------------ > > myvar = [] > > > > def changeme( param ): > > param.append( "blah" ) > > print param > > > > changeme( myvar ) > > > > print myvar > > > > The above code yields the following output: > > ['blah'] > > ['blah'] > > > > This means that the list passed in was modified by the function. > > > ------------------------------------------------------------------------------------------------ > > Now test case 2: > > > > myvar = 4 > > > > def changeme( param ): > > param = 5 > > print param > > > > changeme( myvar ) > > > > print myvar > > > > The above code yields the following output: > > 5 > > 4 > > > > This means that the integer passed in was NOT modified by the function. > > > ------------------------------------------------------------------------------------------------ > > > > Between these two tests, both types passed in are mutable objects. I'm > > having trouble figuring out what mandates an object to be changed from > > within a function versus not. What is happening in test case 2 to cause > > it to not be modified? > > > > Thanks for reading guys. Hopefully one day I'll understand this lol. > > > The first thin to realise is that all Python names are just bindings to > values. In C++ terms you can think of them all as pointers. > De-referencing is automatic when a value is to be retrieved. > > > >>> def changeme( param ): > ... param = 3 > ... print param > ... > >>> myvar = [] > >>> changeme(myvar) > 3 > >>> myvar > [] > >>> > > In this case there is no attempt to mutate the argument, the argument > name is simply bound to another value. Since the argument is a name > local to the function, this does not result in any change outside the > function. > > In this case the argument is bound to a mutable value, so the call to > append mutates the object (a list) referenced by the argument. > > Unlike C++ and similar languages a variable does not hold a value, it > holds a pointer to a value. When a list is passed as a function argument > the reference to the list is copied into the argument. Does this help at > all? > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Aug 20 19:00:34 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 21 Aug 2007 01:00:34 +0200 Subject: Any advice on ways for sharing a small Python application with the world? References: <1187647187.137812.158130@22g2000hsm.googlegroups.com> Message-ID: <5iukoiF3rfrd3U1@mid.individual.net> Bert Heymans wrote: > does anyone know of other ways to share something that might just > be too small for a sourceforge project but too big to be a > snippet? You could submit it to . Regards, Bj?rn -- BOFH excuse #271: The kernel license has expired From zentraders at gmail.com Fri Aug 17 17:20:21 2007 From: zentraders at gmail.com (Zentrader) Date: Fri, 17 Aug 2007 14:20:21 -0700 Subject: Array and floating point In-Reply-To: <1187384816.251783.95410@19g2000hsx.googlegroups.com> References: <1187384816.251783.95410@19g2000hsx.googlegroups.com> Message-ID: <1187385621.417047.274120@x35g2000prf.googlegroups.com> On Aug 17, 2:06 pm, Jonathan Shan wrote: > Hello, > > I'm experiencing a problem where the float being appended to the array > is not the same as the result of the appending. > > >>> from array import * > >>> x = array('f') > >>> x.append(float("0.1")) > >>> x[0] > 0.10000000149011612 > >>> float("0.1") > > 0.10000000000000001 > > I'm expecting x[0] = 0.10000000000000001 > > Thanks > Jonathan Shan Floating point precision problems on x86 type machines is well documented on the web if you want to know more about it. For your example use Python's decimal class instead of floating point. Gmpy is also available for scientific type apps, http://docs.python.org/lib/module-decimal.html http://pydoc.org/2.4.1/decimal.html http://gmpy.sourceforge.net/ import decimal x = decimal.Decimal( "0.1" ) print x y = decimal.Decimal( "0.10000000000000001" ) print y print y/x print y*x From gagsl-py2 at yahoo.com.ar Thu Aug 2 19:49:57 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 02 Aug 2007 20:49:57 -0300 Subject: frequency analysis of a DB column References: <1186021313.413443.184060@i38g2000prf.googlegroups.com> <1186057726.3388.6.camel@dot.uniqsys.com> Message-ID: En Thu, 02 Aug 2007 09:28:46 -0300, Carsten Haese escribi?: > On Thu, 2007-08-02 at 00:38 -0300, Gabriel Genellina wrote: >> >> select column, count(column), min(column), max(column) >> from table >> group by column >> order by count(column) desc > > What's the point of including min(column) and max(column)? They're > always going to be equal to column. To waste a few more microcalories moving my fingers typing nonsense? -- Gabriel Genellina From mail at timgolden.me.uk Fri Aug 24 04:14:10 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 24 Aug 2007 09:14:10 +0100 Subject: How would I go about making a file open. Not the way you might think. In-Reply-To: References: Message-ID: <46CE9352.7060007@timgolden.me.uk> [... snip extended discussion on opening text files ...] Lamonte Harris wrote: > I've completed this request and I got the answer already. Yes, but discussions here never simply end when the answer is found! :) TJG From ajmacd at ns.sympatico.ca Sun Aug 12 20:45:47 2007 From: ajmacd at ns.sympatico.ca (Aaron J. M.) Date: Sun, 12 Aug 2007 17:45:47 -0700 Subject: Pausing and Unpausing Threads In-Reply-To: <1186950645.886995.56060@w3g2000hsg.googlegroups.com> References: <1186883176.319755.304970@d55g2000hsg.googlegroups.com> <13bulsklq359q8f@corp.supernews.com> <1186950645.886995.56060@w3g2000hsg.googlegroups.com> Message-ID: <1186965947.914607.222260@o61g2000hsh.googlegroups.com> Uhg, I thought of something I didn't consider before: how to cleanly end the Server/DirectedControl(l)er process. Assuming that the Client only sends Actions to the DirectedController while the DirectedController is in its turn() method (which I would probably regulate using some flag in DirectedController) the Client will eventually need a way to order the Server to stop its processing. Stopping the Server also has to make the DirectedController break out of its turn method without letting it execute an Action. I don't want to just kill the Server thread because I may want to do serialization or other kinds of cleanup. Have people encountered something like this before? Thank you, Aaron J. M. From vasudevram at gmail.com Fri Aug 10 06:05:16 2007 From: vasudevram at gmail.com (vasudevram) Date: Fri, 10 Aug 2007 10:05:16 -0000 Subject: Python MAPI In-Reply-To: <1185196021.512126.93490@r34g2000hsd.googlegroups.com> References: <1184954229.222401.213380@k79g2000hse.googlegroups.com> <1184957337.367674.104760@i13g2000prf.googlegroups.com> <1184959701.447824.70890@q75g2000hsh.googlegroups.com> <1184960314.426690.238270@z28g2000prd.googlegroups.com> <1184965933.212060.214800@m3g2000hsh.googlegroups.com> <1185134453.934837.325310@w3g2000hsg.googlegroups.com> <1185196021.512126.93490@r34g2000hsd.googlegroups.com> Message-ID: <1186740316.816775.130500@m37g2000prh.googlegroups.com> On Jul 23, 6:07 pm, kyoso... at gmail.com wrote: >Well, I ran Process Monitor with some filters enabled to only watch Thunderbird and MS Word. Unfortunately, that didn't give me any of the registry edits, so I disabled my filters and ran it without. Now I have a log file with 28,000 entries. It's amazing to see all the stuff that happens in just a few moments, but how am I supposed to parse this mess? Explorer.exe and outlook express do thousands of the registry calls and the paths they manipulate vary wildly. Oh well, I'll be off the clock in about 15 minutes so it can wait until Monday. Thanks for your help. I'll post if I figure out anything...hopefully you'll do the same. --- Sorry for not replying earlier ... I searched this list for the topic (Python MAPI) a few times but couldn't find it - not sure why - maybe Google Groups's indexing gets messed up sometimes ... Yes, so many entries would be a problem to parse manually ... That's why I suggested using a grep for Windows - or, preferably, an egrep - which is a more powerful version of grep; e.g. basic grep only allows you to use one regexp at a time - while egrep allows you to use extended regular expressions, such as "pattern1|pattern2", also "patt(e|u)rn(1|2)" which looks in parallel for pattern1, patturn1, pattern2 and patturn2 - I used a made-up example where the spelling of pattern could be wrong, but it works for any other cases of alternative patterns and subpatterns as well. Not sure if there is any egrep for Windows - try Googling. If not, and the problem is important enough, you might want to install Cygwin (its a big download, so first check if it _does_ have egrep in it). Vasudev From goldtech at worldpost.com Sat Aug 4 14:26:09 2007 From: goldtech at worldpost.com (goldtech) Date: Sat, 04 Aug 2007 11:26:09 -0700 Subject: frequency analysis of a DB column In-Reply-To: <1186099294.343121.50240@d30g2000prg.googlegroups.com> References: <1186021313.413443.184060@i38g2000prf.googlegroups.com> <1186099294.343121.50240@d30g2000prg.googlegroups.com> Message-ID: <1186251969.622604.178940@d30g2000prg.googlegroups.com> Just wanted to thank the Posters for the help! Thanks. Lee G. From sturlamolden at yahoo.no Fri Aug 17 17:40:11 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 17 Aug 2007 14:40:11 -0700 Subject: Can python threads take advantage of use dual core ? In-Reply-To: <1187366443.621295.97020@e9g2000prf.googlegroups.com> References: <1187366443.621295.97020@e9g2000prf.googlegroups.com> Message-ID: <1187386811.454645.298710@g4g2000hsf.googlegroups.com> On Aug 17, 6:00 pm, nikhilketkar wrote: > What are the implications of the Global Interpreter Lock in Python ? This is asked every second week or so. The GIL is similar to the Big Kernel Lock (BKL) use to support SMPs in older versions of the Linux kernel. The GIL prevents the Python interpreter to be active in more than one thread at a time. If you have a single CPU with a single core, the GIL has no consequence what so ever. If you have multiple CPUs and/or multiple cores, the GIL has the consequence that you can forget about SMP scalability using Python threads. SMP scalability require more fine grained object locking, which is what the Java and .NET runtimes do, as well as current versions of the Linux kernel. Note that IronPython and Jython use fine grained locking instead of a GIL. > Does this mean that Python threads cannot exploit a dual core > processor and the only advantage of using threads is in that > computation and IO-bound operations can continue in parallel ? The Python standard library releases the GIL in read/write operations for e.g. files and sockets. This can be combined with threads to allow multiple IO operations to continue in parallel. The GIL has no or very little significance for IO-bound scalability in Python. CPU-bound tasks are a different game. This is where the GIL matter. You must either release the GIL or use multiple processes for exploiting multiple processors in an SMP computer with Python. The GIL can be released explicitely in C extension code. f2py and ctypes can also release the GIL. Note that you would NOT use threads for speeding up CPU-bound operations, even when programming in C or Fortran. Threads are neither the only nor the preferred way to exploit multicore CPUs for CPU-bound tasks. Instead of threads, use either an MPI library or OpenMP compiler pragmas. You can use MPI directly from Python (e.g. mpi4py), or you can use OpenMP pragmas in C or Fortran code which you call using ctypes or f2py. Summary: Use Python threads if you need to run IO operations in parallel. Do not use Python threads if you need to run computations in parallel. Regards, Sturla Molden From gatti at dsdata.it Mon Aug 13 07:44:45 2007 From: gatti at dsdata.it (gatti at dsdata.it) Date: Mon, 13 Aug 2007 04:44:45 -0700 Subject: Eclipse/PyDev question In-Reply-To: <1186998539.030727.279330@g4g2000hsf.googlegroups.com> References: <1186998539.030727.279330@g4g2000hsf.googlegroups.com> Message-ID: <1187005485.137101.43130@l70g2000hse.googlegroups.com> On Aug 13, 11:48 am, king kikapu wrote: > Hi, > > i am using Eclipse (Platform Runtime binary) with PyDev and i was > wondering if someone can help me with this: > > 1. I set breakpoints to a .py file and i have told Eclipse to open the > Debug perspective when it sees that some .py file(s) of my project > indeed contains breakpoints. So, i press F9, Eclipse starts, Debug > perspective opens and i can use the debugger just fine. But when the > app terminates, how can i tell Eclipse to switch automatically to the > PyDev perspective and not remain in the Debug one ? You don't, Eclipse keeps the same perspective because for what it knows you might want to debug some more and it correctly avoids to decide what is good for you. Switching to the debug perspective when you issue a debug command is an exception to the normal switching of perspectives with the respective big buttons and the menu. If you wish to switch perspective to edit code before debugging again, putting editors and appropriate accessory views in the debug perspective might be good enough. > 2. Let's say we have a project that consists of some .py files. I want > to press F9 when the editor displays anyone of these files but make > Eclipse to run the whole project (that has another .py as "default") > and not the script that i am currently working on, is that possible ?? Executing the current file is a bad habit, Eclipse remembers a list of execution/debug configurations that can be selected from a dropdown list in the toolbar and edited with a dialog box; after you setup entry points for a project you can use and edit them as needed. I'm using Eclipse for Java and my entry points include remote debugging of a GUI application, about 6 JUnit tests, about 3 command line tools with many complex parameter sets each, and some Ant builds; it would take about one hour of trial and error to reconstruct the command lines, classpaths and JVM options. I only run the current file as a draft for an edited configuration. Regards, Lorenzo Gatti From DustanGroups at gmail.com Sat Aug 11 22:10:26 2007 From: DustanGroups at gmail.com (Dustan) Date: Sun, 12 Aug 2007 02:10:26 -0000 Subject: python 2.5 bug In-Reply-To: References: <1186825286.493878.80380@l70g2000hse.googlegroups.com> Message-ID: <1186884626.597028.246990@57g2000hsv.googlegroups.com> On Aug 11, 12:32 am, Thorsten Kampe wrote: > 4. don't do something you don't fully understand (in this case > installing Python 2.5 and uninstalling Python 2.4) If we were all limited by that rule, none of us would never have used a computer in the first place. Operating a computer is a learning experience, no matter what level you're at (although admittedly the lessons learned can sometimes be hurtful). From jiapengjun at gmail.com Wed Aug 22 10:42:35 2007 From: jiapengjun at gmail.com (Jiapj) Date: Wed, 22 Aug 2007 14:42:35 -0000 Subject: libgmail failure In-Reply-To: <1187730447.621592.93740@q4g2000prc.googlegroups.com> References: <1187730447.621592.93740@q4g2000prc.googlegroups.com> Message-ID: <1187793755.710417.52730@z24g2000prh.googlegroups.com> I met the same problem now, James , do you have resolved this problem ? On Aug 22, 5:07 am, "james.p.n... at gmail.com" wrote: > Hey all, > > I've been using libgmail to send out automated notification emails for > my company's nightly regression testing. Last night these emails > started failing, though the python code has not changed. I updated to > the latest libgmail, but that isn't helping. I've logged in to the > email account directly, and the account is still working fine. > > The error I get is "HTTP Error 400: Bad Request" when using > gmailAccount.login(). This doesn't throw an exception, just prints > the error. The code crashes outright when it tries to send mail. > > This code has been up and running for several months and just started > failing last night. Does anyone have an idea what's going on? > > The code and error follow (fairly short :-) > > Thanks much, > James > > Code: > ------------------------------------------------------------------------------------------------------- > def send(TO_LIST,SUBJECT,MESSAGE): > GA = libgmail.GmailAccount("xxx... at gmail.com","xxxxxxx") > try: > print "Logging in" > GA.login() > except libgmail.GmailLoginFailure: > print "\nLogin failed. (Wrong username/password?)" > else: > print "Log in successful.\n" > for RX in TO_LIST: > MSG = libgmail.GmailComposedMessage(RX,SUBJECT,MESSAGE) > if GA.sendMessage(MSG): > print "Message successfully sent to `%s` ." % RX > else: > print "Could not send message." > ------------------------------------------------------------------------------------------------------- > > Output: > ------------------------------------------------------------------------------------------------------- > Logging in > HTTP Error 400: Bad Request > Log in successful. > > No messages found > Traceback (most recent call last): > File "C:\projects\physware\testCases\PythonTestScripts > \SendEmail.py", line 58, in > main() > File "C:\projects\physware\testCases\PythonTestScripts > \SendEmail.py", line 55, in main > send(TO_LIST,SUB,MSG) > File "C:\projects\physware\testCases\PythonTestScripts > \SendEmail.py", line 39, in send > if GA.sendMessage(MSG): > File "C:\projects\physware\testCases\PythonTestScripts\libgmail.py", > line 588, in sendMessage > U_ACTION_TOKEN: self._getActionToken(), > File "C:\projects\physware\testCases\PythonTestScripts\libgmail.py", > line 563, in _getActionToken > at = self._cookieJar._cookies[ACTION_TOKEN_COOKIE] > KeyError: 'GMAIL_AT' > ------------------------------------------------------------------------------------------------------- From rcdailey at gmail.com Mon Aug 20 12:12:47 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 20 Aug 2007 11:12:47 -0500 Subject: Problem with Thread.join() In-Reply-To: <8a6b8e350708200758w640fd7c4w5bd19fb53decde71@mail.gmail.com> References: <496954360708131610i62c0a63aneb7c39d23a052ac0@mail.gmail.com> <8a6b8e350708200758w640fd7c4w5bd19fb53decde71@mail.gmail.com> Message-ID: <496954360708200912i8479cb5l1442451944e4d714@mail.gmail.com> Hey guys, Sorry for taking so long to respond. I had actually figured out what this issue is over on the wxPython mailing list. The issue was that I was attempting to configure wxPython controls from a remote thread, which is apparently illegal due to some state persistance issues. Thanks all for responding and I do apologize for not having given proper code snippets on my first post. Take care all. On 8/20/07, James Matthews wrote: > Post some code so we can see the issue! I would say that the issue is where > your function that you are calling isn't exiting! > > > On 8/20/07, Gabriel Genellina wrote: > > En Mon, 13 Aug 2007 20:10:53 -0300, Robert Dailey > > escribi?: > > > > > I have a class that derives from threading.Thread. To signal the thread > > > to > > > exit its infinite loop, I set an Event. Once the thread checks > > > Event.isSet() > > > and it is true, it proceeds to break out of the loop and exit the > > > function. > > > In the main thread, right after calling Event.set(), I call > > > Thread.join() to > > > wait on the thread to exit. However, if I call Thread.join() the > > > application > > > locks up because for some reason calling Thread.join() prevents the > > > thread > > > from exiting. I don't know why. Any help? Thanks... > > > > Conceptually you're doing it the right way. Post some code demonstrating > > the problem... > > > > -- > > Gabriel Genellina > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -- > http://www.goldwatches.com/ > http://www.jewelerslounge.com > -- > http://mail.python.org/mailman/listinfo/python-list > From pyth0nc0d3r at gmail.com Tue Aug 28 01:04:09 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Tue, 28 Aug 2007 00:04:09 -0500 Subject: Python Classes Message-ID: How come you have to set the initialized created variables to equal the parameters, shouldn't that be default? class testing: def __init__(self,testing): self.testing = testing x = testing("testing") print x.testing How come self.testing = testing Can someone explain that in more detail, just confused on why you have to set it up like that. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eugene.vandenbulke at gmail.com Sun Aug 26 03:26:15 2007 From: eugene.vandenbulke at gmail.com (EuGeNe Van den Bulke) Date: Sun, 26 Aug 2007 09:26:15 +0200 Subject: ActiveRecord for Python/MySQL References: <1188103880.146814.110780@q4g2000prc.googlegroups.com> Message-ID: Devraj wrote: > My application uses MySQL as a backend and am using the MySQL/Python > bindings. Are there any libraries that provide a database abstraction > layer like Activerecords for Python?' SQLObject SQLAclhemy DejaVu Storm Google for Python ORM you may find more! EuGeNe -- http://www.3kwa.com From gtcopeland at gmail.com Wed Aug 22 09:01:47 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: Wed, 22 Aug 2007 13:01:47 -0000 Subject: Fast socket write In-Reply-To: <46cba22b$1_1@news.chariot.net.au> References: <1187744469.240933.149610@r23g2000prd.googlegroups.com> <46cba22b$1_1@news.chariot.net.au> Message-ID: <1187787707.377952.322280@57g2000hsv.googlegroups.com> On Aug 21, 9:40 pm, Bikal KC wrote: > Greg Copeland wrote: > > I'm having a brain cramp right now. I can't see to recall the name of > > Is your cramp gone now ? :P I wish. If anyone can remember the name of this module I'd realy appreciate it. Greg From uymqlp502 at sneakemail.com Fri Aug 31 01:56:54 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Thu, 30 Aug 2007 22:56:54 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188534061.243009.89640@m37g2000prh.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> <1188534061.243009.89640@m37g2000prh.googlegroups.com> Message-ID: <1188539814.800466.6930@r23g2000prd.googlegroups.com> > Python really isn't suitable for in-flight controls > for various > reasons, and mission critical concerns is a minor one (systems with Do you know anything about the FAA certification process for flight- critical systems? I am not an expert on it, but I know it is very expensive. If I am not mistaken, getting such code certified is more expensive than developing it in the first place. Why would that be so if, as you claim, "mission critical concerns is a minor one"? From steve at holdenweb.com Tue Aug 14 21:41:57 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 14 Aug 2007 21:41:57 -0400 Subject: What order does info get returned in by os.listdir() In-Reply-To: <1187131583.114731.279180@g12g2000prg.googlegroups.com> References: <1187131583.114731.279180@g12g2000prg.googlegroups.com> Message-ID: Zentrader wrote: > On Aug 14, 1:52 pm, Jeremy C B Nicoll wrote: >> What order does info get returned in by os.listdir() ? >> >> I'm just starting to write python code, on an Win XP Pro machine. I've got >> various directories which, when I look at them in Win XP, sorted by name, I >> see in order, eg: >> >> ~prefixed file .txt >> A.txt >> B.txt >> ... >> Z.txt >> >> ie, XP seems to think that files with a "~" as their first character are >> sorted ahead of A. >> >> When I use os.listdir() to return that list of leaf values, I do seem to get >> them in alphabetical order, A before B before C etc, but the ~-prefixed ones >> are returned after the Z-prefixed files rather than before the A-ones. >> >> I was wondering why... >> >> -- >> Jeremy C B Nicoll - my opinions are my own. > > I think that os.listdir() returns file names in chronological order, > that is in the order they were created on disk. If there is any > sorting done it will be in ASCII order. All data is stored as a > number so it is sorted that way. ord("~")= 126, and ord("Z")=90 so it > makes sense that "~" is after "Z". > You can think what you like, but reading the documentation is usually a more reliable way to resolve uncertainties, and it says: """The list is in arbitrary order.""" regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From kwmsmith at gmail.com Mon Aug 13 12:35:49 2007 From: kwmsmith at gmail.com (Kurt Smith) Date: Mon, 13 Aug 2007 11:35:49 -0500 Subject: Drawing a graph In-Reply-To: <20070812220911.fd2948e1.ghirai@ghirai.com> References: <20070812220911.fd2948e1.ghirai@ghirai.com> Message-ID: On 8/12/07, Ghirai wrote: > Hello list, > > I need to draw a graph, 2 axes, 2D, nothing fancy. > One of the axes is time, the other one is a series of integers. > > I don't care much about the output format. > > Are there any specialized libraries for this, or should i use PIL? > > Thanks. > > -- > Regards, > Ghirai. > -- > http://mail.python.org/mailman/listinfo/python-list > Checkout matplotlib: http://matplotlib.sourceforge.net/ Powerful (esp. with IPython), clean implementation, very nice output, IMHO. It does depend on some other things; primarily numpy and some sort of backend for displaying figures (usually can use a default backend -- e.g. Tkinter). Otherwise you can plot directly to file. May not be what you're looking for if you want something quick. HTH, Kurt From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Aug 16 08:58:11 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 16 Aug 2007 14:58:11 +0200 Subject: Coroutines and argument tupling References: <5ih63mF3pvnt7U1@mid.individual.net> <87k5rwo24e.fsf@seneca.iss.local> <5iikd6F3pfrhrU1@mid.individual.net> Message-ID: <5iivv3F3q6b76U1@mid.individual.net> Marshall T. Vandegrift wrote: > I'd seen the consumer decorator, and it certainly is cleaner than > just using a generator. I don't like how it hides the parameter > signature in the middle of the consumer function though, and it > also doesn't provide for argument default values. Mh, that may be. :( I didn't use it much yet. > Thanks in any case for the replies! Since I've apparently decided > my ArgPacker is worth it, the complete code for my coroutine > decorator follows. Thanks for reporting back, and happy coding. Regards, Bj?rn -- BOFH excuse #198: Post-it Note Sludge leaked into the monitor. From wdraxinger at darkstargames.de Mon Aug 6 07:27:10 2007 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Mon, 06 Aug 2007 13:27:10 +0200 Subject: Best programs written completly in Python References: Message-ID: Franz Steinh?usler wrote: > wWhat are the best programs in your opinion, written entirly > in pyhton, divided into categories like: > a) Games > b) Utilities/System > c) Office > d) Web/Newsreader/Mail/Browser BitTorrent. It may not seem much but it's a really cool package. Especially you don't have to use the standard frontends, but can also use BitTorrent modules in your own Python programs. Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 From a.harrowell at gmail.com Wed Aug 8 10:54:33 2007 From: a.harrowell at gmail.com (a.harrowell at gmail.com) Date: Wed, 08 Aug 2007 14:54:33 -0000 Subject: SciPy's site is down Message-ID: <1186584873.075215.326620@b79g2000hse.googlegroups.com> Can anyone else not reach scipy.org? Am trying to install scipy and numpy. Further, is there an equivalent of numpy that will install correctly on Python 2.5 on WinVista? From gheize at gmail.com Thu Aug 30 08:58:40 2007 From: gheize at gmail.com (Guillermo Heizenreder) Date: Thu, 30 Aug 2007 09:58:40 -0300 Subject: problem with SQLObject + mysql In-Reply-To: <1188469992.27740.14.camel@leinad-desktop> References: <1188469992.27740.14.camel@leinad-desktop> Message-ID: <1188478720.27740.42.camel@leinad-desktop> El jue, 30-08-2007 a las 07:33 -0300, Guillermo Heizenreder escribi?: > Hi list I'm new whit SQLObjet. > I'm study the tutorial:Connecting databases to Python with SQLObjet[1] > > My problem is: > >>>from sqlobject.mysql import builder > >>>con=builder()(user='dbuser',passwd='dbpassword',host='localhost',db='garbanzo') > Traceback (most recent call last): > File "", line 1, in > File > "/usr/lib/python2.5/site-packages/SQLObject-0.9.1-py2.5.egg/sqlobject/mysql/mysqlconnection.py", line 51, in __init__ > DBAPI.__init__(self, **kw) > File > "/usr/lib/python2.5/site-packages/SQLObject-0.9.1-py2.5.egg/sqlobject/dbconnection.py", line 249, in __init__ > DBConnection.__init__(self, **kw) > TypeError: __init__() got an unexpected keyword argument 'passwd' __ini__() got an keyword argument 'password' not 'passwd' > > First i creating the user mysql: > guille at leinad-desktop:~$ mysql -u root > mysql> use mysql; > Database changed > mysql> create database garbanzo; > Query OK, 1 row affected (0.02 sec) > mysql> grant all privileges on garbanzo to 'dbuser'@'localhost' > identified by 'dbpassword'; > Query OK, 0 rows affected (0.10 sec) > mysql> flush privileges; > Query OK, 0 rows affected (0.09 sec) > > > So... how i do to connect?. how create de password correctly? > Thanks and kind regards from Argentina. > P/D: my English it to bad, I'm a novice, :P. > > [1]http://www-128.ibm.com/developerworks/library/os-pythonsqlo/index.html?ca=drs#resources From eggie5 at gmail.com Thu Aug 9 19:47:41 2007 From: eggie5 at gmail.com (eggie5) Date: Thu, 09 Aug 2007 23:47:41 -0000 Subject: beginner whitespace question Message-ID: <1186703261.136506.208660@x35g2000prf.googlegroups.com> I keep getting an error for line 7, what's wrong with this? from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): return self.question def was_published_today(self): return self.pub_date.date() == datetime.date.today() class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField() def __unicode__(self): return self.choice From ninja.krmenadl at nes.com Fri Aug 10 11:47:30 2007 From: ninja.krmenadl at nes.com (Boris Ozegovic) Date: Fri, 10 Aug 2007 17:47:30 +0200 Subject: cookielib Message-ID: Hi I have HTTP client which accepts cookies. If client allready has cookie, but that cookie has expired, server sends him new cookie, and in response object Set-Cookie: header everything is fine, but if I reload request, client sends expired cookie, and not the new one. In cookiejar there is only new and valid cookie, and if I use regular browser everything is fine. The code is following: urlopen = urllib2.urlopen Request = urllib2.Request cj = cookielib.LWPCookieJar() COOKIEFILE = 'cookies.lwp' if os.path.isfile(COOKIEFILE): # if we have a cookie file already saved # then load the cookies into the Cookie Jar cj.load(COOKIEFILE) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) url = "http://localhost:8000/files/index.html" params = {'question':question} data = urllib.urlencode(params) Request(url, data) try: response = urlopen(Request) etc. Only if I create new request object the new cookie is send, but I don't want to create new object. And idea? -- Ne dajte da nas la?ljivac Bandi? truje: http://cnn.blog.hr/arhiva-2007-06.html#1622776372 From gerdusvanzyl at gmail.com Sun Aug 26 15:55:14 2007 From: gerdusvanzyl at gmail.com (Gerdus van Zyl) Date: Sun, 26 Aug 2007 12:55:14 -0700 Subject: New UI Toolkit In-Reply-To: <46d1d363$0$404$426a74cc@news.free.fr> References: <1188146822.129605.160560@22g2000hsm.googlegroups.com> <46d1d363$0$404$426a74cc@news.free.fr> Message-ID: <1188158114.580706.262150@19g2000hsx.googlegroups.com> > But I'm afraid with the Swing-like interface, i.e : did you use the same > widget positionning ? Not sure what you mean, but each parent widget is responsible for rendering and positioning the children. Can use layout managers, two currently absolute and simple flow. ( In the screenshot, the gradients are in a flow panel) From no.reply at here.com Sun Aug 19 10:41:32 2007 From: no.reply at here.com (Anonymous) Date: Sun, 19 Aug 2007 15:41:32 +0100 Subject: Newbie question Message-ID: I have exp with C/C++ (and a few other langs). I want to use Python to start doing the ff: 1). Data Munging (text processing) 2). Automating my build process 3). (Possibly) some web data retrieval jobs Can anyone point me to resurces/possibly scripts that can get me up to speed (to do these 3 things) ASAP, without having to learn the basics of programming? From oliver at ootbc.com Sat Aug 18 00:57:39 2007 From: oliver at ootbc.com (Oliver Nelson) Date: Sat, 18 Aug 2007 04:57:39 GMT Subject: Cancelling events on a COM Object In-Reply-To: References: Message-ID: <7%uxi.46771$Um6.36697@newssvr12.news.prodigy.net> James, I was getting an error everytime so I thought I had a setup problem... Sorry everybody... OLIVER James Stroud wrote: > Oliver, wait a while before you panic about your post not getting through! > > James > From ricaraoz at gmail.com Fri Aug 17 12:40:40 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 17 Aug 2007 13:40:40 -0300 Subject: Hiding / encrypting source code In-Reply-To: <1187110504.154878.317460@19g2000hsx.googlegroups.com> References: <1187107452.905165.45700@l70g2000hse.googlegroups.com> <1187110504.154878.317460@19g2000hsx.googlegroups.com> Message-ID: <46C5CF88.7040409@bigfoot.com> Hi, I'm new to this python stuff so maybe I'm stating the obvious, or worse, maybe I'm completely off track. Not long ago someone was asking about a way to hide source code. I stumbled upon zipimport standard module. It seems it lets you get your imports from zip files. The docs say it is implicitly called, so you could have your modules in a zipped file. That should make them a bit more arcane. Another idea would be to modify this module to use encrypted zip files, or to use PyCrypto or some other module as a middle man in order to keep the contents encrypted. HTH From nospam.themindstorm at gmail.com Thu Aug 2 04:06:12 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Thu, 2 Aug 2007 08:06:12 +0000 (UTC) Subject: Where do they tech Python officialy ? References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> <1185265091.276958.239910@r34g2000hsd.googlegroups.com> <1i23wyk.avc945i4dwsiN%aleax@mac.com> <1i25pjo.1mo5uqc1yxqsjkN%aleax@mac.com> <1i26u6o.pthuan2j7nufN%aleax@mac.com> Message-ID: aleax at mac.com (Alex Martelli) wrote in news:1i26u6o.pthuan2j7nufN% aleax at mac.com: > Alex Popescu wrote: > ... >> Have you seen/heard of Jim lately? Cause I haven't. By the time he was >> the lead of the AspectJ team his charismatic presence was everywhere (at >> least around that project). > > He wasn't at OSCON this year, but I hope to see him at Pycon next year. > I don't see this as a deep dark M$ plot to kidnap and hide the best and > brightest Open Sourcers, because I know what it means to get a wonderful > challenging new job and pour all you have into it (I've had to skip a > couple Pycons, myself, though I hope to be back next year). > I wasn't trying to imply that (maybe just as a joke ;-)). It was more a personal curiosity. > >> However I do agree with you. The only remark is that US trends are not >> hitting my part of Eu so quickly ;-) (things are indeed changing). > > About 3 years ago I was also getting sick and tired about my own part of > the EU, which is part of why I emigrated:-). I do see things getting > better in Southern Europe, albeit from a distance. > Guess we both know the feeling then. > >> > These are the ones you don't wan't to work for anyway !-) >> >> Well... this is sometimes debatable :-). > > A totally clueless employer may still be a way to make some quick and > dirty money right now, but it will barely be enough to pay for the extra > Maalox and Zantac you'll need. Looking back on your life when you're > closer to retirement than to when you started working, you'll see what a > mistake it was to accept clueless-employers' offers, and how much > happier your life would have been if you'd known that up front:-). > He he... been there done that :-). Escaped only with couple of Maalox, though :-). bests, ./alex -- .w( the_mindstorm )p. > > Alex From steve at holdenweb.com Mon Aug 6 19:01:12 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 06 Aug 2007 19:01:12 -0400 Subject: Something in the function tutorial confused me. In-Reply-To: <5hp6d1F3kl28iU4@mid.uni-berlin.de> References: <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <1186422680.103021.105230@l70g2000hse.googlegroups.com> <5hp6d1F3kl28iU4@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Mon, 06 Aug 2007 10:51:20 -0700, Lee Fleming wrote: > >> why isn't the y in def f (x, y = []): something >> garbage-collected? > > `y` is a name. Only objects are garbage collected. There is no `y` in > that ``def`` in the sense that a local name `y` exists when the ``def`` is > executed. The line just says there will be a local name `y` if > the function `f()` is executed and that local name will be bound to the > given object. Unless the user provides a value for the argument in the call. > Which happen to be a list. This list is referenced by the > function object, so it won't get garbage collected, and it is bound to a > local name `y` every time the function is called. It is always the > very same list object. And if you mutate it, this will be visible to > other calls to the function. > regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From saint.infidel at gmail.com Fri Aug 3 15:18:42 2007 From: saint.infidel at gmail.com (infidel) Date: Fri, 03 Aug 2007 12:18:42 -0700 Subject: draggable Tkinter.Text widget Message-ID: <1186168722.771166.118500@q3g2000prf.googlegroups.com> Inspired by effbot's recent Vroom! editor, I have been toying with my own version. I'd like to make the Text widget "draggable", kind of like how you can drag a PDF document up and down in Adobe Reader. Here's what I have so far: from Tkinter import * class Draggable(Text, object): def __init__(self, parent, **options): Text.__init__(self, parent, **options) self.config( borderwidth=0, font="{Lucida Console} 10", foreground="green", background="black", insertbackground="white", # cursor selectforeground="green", # selection selectbackground="#008000", wrap=WORD, # use word wrapping undo=True, width=80, ) self.bind('', self.handle_mousedown3) self.bind('', self.handle_drag3) def handle_mousedown3(self, event=None): self._y = event.y def handle_drag3(self, event=None): self.yview_scroll(self._y - event.y, UNITS) self._y = event.y if __name__ == '__main__': root = Tk() root.protocol("WM_DELETE_WINDOW", root.quit) root.config(background='black') root.wm_state("zoomed") text = Draggable(root) text.delete(1.0, END) text.insert(END, '\n'.join(str(x) for x in xrange(1, 1001))) text.pack(fill=Y, expand=True) root.mainloop() This works fine, but because the mouse movements are in pixels and scroll actions are in lines, the 'magnitude' of the scrolling is much larger than the mouse movements causing them. This isn't all bad, it makes scanning a long document quickly easier, but I was wondering if there was a simple way to add some "friction" to the scrolling so a tiny mouse movement doesn't cause the text to go zipping by in a flash. Thanks, infidel From python-url at phaseit.net Mon Aug 27 06:36:49 2007 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 27 Aug 2007 10:36:49 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Aug 27) Message-ID: QOTW: "There is something to be said for Python's 'elitism' ;)" - Carsten Haese "While the discipline of TDD is good and useful, there's a time and place for unstructured and informal experimentation too." - Steven D'Aprano Issue tracker migration is complete - now at http://bugs.python.org and based on Roundup. http://groups.google.com/group/comp.lang.python/browse_thread/thread/7cc2fc8f85b9e5cf/c582a66d35a03e7c How to properly cleanup resources (don't rely on __del__ for this) http://groups.google.com/group/comp.lang.python/browse_thread/thread/6f5784070d7b6b64/fee0c252b4311c1f How to open a file using its associated application (multi-platform) http://groups.google.com/group/comp.lang.python/browse_thread/thread/4913652c4cce31a4/42c670204411f000 For number-crunching lawyers: does shuffle() produce a uniform distribution()? http://groups.google.com/group/comp.lang.python/browse_thread/thread/48931f2f7ca7b49e/22fa264d9706d2d6 Replacing a method with another depending on the instance. Bonus for language lawyers: the difference between functions and methods, and how the descriptor protocol works in short. http://groups.google.com/group/comp.lang.python/browse_thread/thread/47cec38e789032be/832f0f648e6893a4#a1b7360e83905033 Sometimes -e.g. for benchmarking- one wants to purge the disk cache http://groups.google.com/group/comp.lang.python/browse_thread/thread/1273b79934a3e3e9/0b4e52a7bfa4e922 Do some foolish things when creating a class, and you'll need a Python guru to understand what really happened http://groups.google.com/group/comp.lang.python/browse_thread/thread/4373307ef75d1278/a8610ba4e2f9d9ef Learning Python using a book based on version 1.5: some people say "OK", other say "No" http://groups.google.com/group/comp.lang.python/browse_thread/thread/ffcccbdcae177ff/75b819d9c362b4ca A small trick: how to generate short exception names http://groups.google.com/group/comp.lang.python/browse_thread/thread/54c9b0f626b6a8fe/562c3a6eace389fd A proposal for a new document markup language (a LaTeX competitor) http://groups.google.com/group/comp.lang.python/browse_thread/thread/6b72f25206aacf7/7242c98c672a21e6 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From steve at holdenweb.com Tue Aug 21 07:31:53 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 21 Aug 2007 07:31:53 -0400 Subject: Newbee Question In-Reply-To: <1187650036.450645.185500@a39g2000hsc.googlegroups.com> References: <1187621470.484615.7010@i13g2000prf.googlegroups.com> <1187622390.854759.162320@q3g2000prf.googlegroups.com> <1187650036.450645.185500@a39g2000hsc.googlegroups.com> Message-ID: <46CACD29.8080200@holdenweb.com> hd1956 at yahoo.com wrote: [...] > > Thanks for the help. By the way I am trying to learn the python after > work and on weekends. If it was a dumb question, to this group, I will > not bother you all again. > Without help it will take me longer to learn. Thanks > Don't worry about it. There is also a list specifically for learners, which you can find out about at http://mail.python.org/mailman/listinfo/tutor Welcome to the Python community! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From gdonald at gmail.com Thu Aug 2 13:50:05 2007 From: gdonald at gmail.com (Greg Donald) Date: Thu, 2 Aug 2007 12:50:05 -0500 Subject: Emacs + python In-Reply-To: <4vasi.139194$wG2.61677@newsfe17.lga> References: <4vasi.139194$wG2.61677@newsfe17.lga> Message-ID: <15e66e4e0708021050n59d5dcafi58fa80ea946d5bea@mail.gmail.com> On 8/1/07, hg wrote: > Are there any cscope & ECB equivalent for Python ? ECB is not language specific. It works the same for browsing Python code as any other language. -- Greg Donald http://destiney.com/ From irmen.NOSPAM at xs4all.nl Fri Aug 3 13:21:40 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 03 Aug 2007 19:21:40 +0200 Subject: (no) fast boolean evaluation ? In-Reply-To: <1186096979.397596.36640@e16g2000pri.googlegroups.com> References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> <1186096979.397596.36640@e16g2000pri.googlegroups.com> Message-ID: <46b36424$0$239$e4fe514c@news.xs4all.nl> John Machin wrote: > > (you_are_confused and/or > function_returns_bool_but_has__side_effects()) > That above expression should be written more explicitly like: function_result = function_returning_bool_but_with_side_effects() if you_are_confused or function_result: do_something_nice() --irmen From john at clocksoft.com Sun Aug 5 04:37:41 2007 From: john at clocksoft.com (John Pinner) Date: Sun, 5 Aug 2007 09:37:41 +0100 Subject: [pyconuk] pyweek is happening august 02 - august 09 In-Reply-To: <200708041832.l74IWkRY027388@theraft.openend.se> References: <200708041832.l74IWkRY027388@theraft.openend.se> Message-ID: Hello All, On 04/08/07, Laura Creighton wrote: > 00:00 UTC 2007-09-02 to 00:00 UTC 2007-09-09 exactly. See > www.pyweek.org > > PyconUK is happening. http://www.pyconuk.org/ 8th and 9th September. > > This means that those of us who generally do not see each other but are > going to PyconUK could put together an entry and then sprint together > on it before PyCon UK. There would be this terrible torment -- do > I attend the con or get my game to work -- but it is still the > best chance some of us have to work together yet. > > Talk to me if you are interested in maybe making a PyconUK pygame > team. I think that this could be a lot of fun. Sign up on > www.pyweek.org if you think so, as well. But mail me. > > John -- assuming we want to meet up _before_ PyConUK -- can that > work? Yes, we'd really like to see you at PyCon UK, and the games! We have sprint facilities available for two days before and two days after PyCon UK. They are at 95 Broad Street, about ten minutes walk from the Conference venue. There is a fat pipe internet connection. There are three rooms available, one has 10 high spec workstations which can be pre-installed with the o/s of your choice, for the other rooms you'd need your own laptops. There are places nearby to buy cheap food (a local supermarket and the usual fast food and sandwich shops). > Can you point us at a cheap hostel for a few days? Looking at http://www.pyconuk.org/accommodation.html : The budget buys are the Etap (conference hotel) and Birmingham Backpackers, they are also furthest from the sprint location, say 25 and 30 minutes walk respectively (I haven't timed these). Basically, you can stay at either of these for less than ?20 if you share. Also worth considering are the Comfort Zone serviced apartments, the ones in Townsend Street are about ten minutes walk from the sprint venue, less to the conference. The nearest hotel is the Novotel (where we're holding the conference dinner) at 70 Broad Street, 2 minutes from the sprint and 10 from the Conference. You should be able to get an online deal for about ?69 for a double room. Just behind the Novotel is the Premier Travel Inn, slightly less at say ?65 for a double. There are two Travel Inns in the area, sprinters would want the Birmingham Broad Street (Brindley Place) one. A good compromise between cost and convenience for the sprinters would be the Travelodge, just across the road from the sprint at 230 Broad Street, where you can get a family room (sleeps 3 adults plus one child, 4 adults at a push) for ?66. One of the PyCon UK delegates has been finding cheap accommodation in the area, and I'll ask him to contact you directly, Laura. Best wishes, John -- From gagsl-py2 at yahoo.com.ar Wed Aug 29 00:27:02 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 28 Aug 2007 21:27:02 -0700 Subject: tempfile.mkstemp and os.fdopen In-Reply-To: <1188350472.508625.18780@50g2000hsm.googlegroups.com> References: <1188323759.955043.317630@19g2000hsx.googlegroups.com> <1188350472.508625.18780@50g2000hsm.googlegroups.com> Message-ID: <1188361622.967138.91690@57g2000hsv.googlegroups.com> On 28 ago, 22:21, billiejoex wrote: > Another question: I have to open file for writing ('wb') but I noticed > that both tempfile.mkstemp() and os.fdopen() accept a "mode" argument. > It's not clear *when* do I have to specify such mode. When using > tempfile.mkstemp? > > Moreover, what happens if I specify "text" mode when using mkstemp and > "binary" mode when using fdopen? > > PS - I think that tempfile.mkstemp docstring should be enhanced to > cover such and other questions (e.g. I find reasonable that every user > using tempfile.mkstemp() should use also os.fdopen() in conjunction > but this isn't mentioned). As someone already suggested, why don't you use TemporaryFile or NamedTemporaryFile and avoid such problems? -- Gabriel Genellina From horpner at yahoo.com Thu Aug 2 15:38:15 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 02 Aug 2007 19:38:15 GMT Subject: i am new to python-Please somebody help References: <1186047103.673871.150460@z24g2000prh.googlegroups.com> <1186063842.827016.95030@q3g2000prf.googlegroups.com> <1186081737.357371.232040@i13g2000prf.googlegroups.com> Message-ID: On 2007-08-02, gregarican wrote: > On Aug 2, 12:58 pm, "Terry Reedy" wrote: >> "gregarican" wrote in message >> >> news:1186063842.827016.95030 at q3g2000prf.googlegroups.com... >> | friendly than Python's. Your points are well-taken in how to properly >> | post and how to do your own homework. Message correct. Delivery >> | lacking... >> >> Sorry, I saw nothing rude in Steven's straightforward and indeed polite >> suggestion. Your post, however, .... >> >> tjr > > Maybe it's just me but the word "grovelling" just doesn't ring > of newbie friendliness. Maybe not, but it seemed to be a reasonable characterisation of the subject line. The only thing more valued than politeness on most programming newsgroups is correctness. > To each their own I guess. Kind of like the Smalltalk list > where a few respondents are really dry. Someone will post > asking something like "Can I use Smalltalk to do X so that it > talks to Y?" One guy (without pointing to a link or offering a > snippet) just posts "Yes." I guess literally they have > contributed. Or someone calls your house and asks, "Is > so-and-so there?" You just say "Yes" and hang up on them :-) Those kind of replies are posted for the fun of it, and with the knowledge that somebody else will feel less flip at the time and probably provide real help. -- Neil Cerutti The pastor will preach his farewell message, after which the choir will sing, "Break Forth Into Joy." --Church Bulletin Blooper From zentraders at gmail.com Tue Aug 14 18:41:35 2007 From: zentraders at gmail.com (Zentrader) Date: Tue, 14 Aug 2007 15:41:35 -0700 Subject: What order does info get returned in by os.listdir() In-Reply-To: References: Message-ID: <1187131295.984122.47200@q4g2000prc.googlegroups.com> On Aug 14, 1:52 pm, Jeremy C B Nicoll wrote: > What order does info get returned in by os.listdir() ? > > I'm just starting to write python code, on an Win XP Pro machine. I've got > various directories which, when I look at them in Win XP, sorted by name, I > see in order, eg: > > ~prefixed file .txt > A.txt > B.txt > ... > Z.txt > > ie, XP seems to think that files with a "~" as their first character are > sorted ahead of A. > > When I use os.listdir() to return that list of leaf values, I do seem to get > them in alphabetical order, A before B before C etc, but the ~-prefixed ones > are returned after the Z-prefixed files rather than before the A-ones. > > I was wondering why... > > -- > Jeremy C B Nicoll - my opinions are my own. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Aug 13 12:10:05 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 13 Aug 2007 18:10:05 +0200 Subject: Help with optimisation In-Reply-To: <46c06b51$0$11684$7b0f0fd3@mistral.news.newnet.co.uk> References: <46c06b51$0$11684$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <46c0825d$0$13987$426a74cc@news.free.fr> special_dragonfly a ?crit : > Hello, (snip) > The function doesn't return anything, but it's called often enough and > depending on the optimisation I'll be able to use the same style in other > areas of the program. > > previous code: > def CreatePerson(text_buffer): > dom=xml.dom.minidom.parseString(text_buffer) > reflist = dom.getElementsByTagName('Country') > Country = reflist[0].firstChild.nodeValue > reflist = dom.getElementsByTagName('Age') > Age = reflist[0].firstChild.nodeValue > reflist = dom.getElementsByTagName('Surname') > Surname = reflist[0].firstChild.nodeValue > reflist = dom.getElementsByTagName('Forename') > Forename = reflist[0].firstChild.nodeValue > cursor.execute('INSERT INTO Person VALUES(?,?,?)', (Forename + "-" + > Surname, Age, Country)) > connection.commit() > > I've changed it now to this: > def CreatePerson(text_buffer): > dom=xml.dom.minidom.parseString(text_buffer) > elements=['Country','Age','Surname','Forename'] > Values=[] > for element in elements: > reflist=dom.getElementsByTagName(element) > Values.append(reflist[0].firstChild.nodeValue) > # I can get away with the above because I know the structure of the > XML > cursor.execute('INSERT INTO Person > VALUES(?,?,?)',(Forename+"-"+Surname,Age,Country)) > connection.commit() A common python optimisation trick is to stote local references to save on attribute lookup time, ie: # local ref to parseString import dom dom_parseString=xml.dom.minidom.parseString def CreatePerson(text_buffer): dom = dom_parseString(text_buffer) elements=['Country','Age','Surname','Forename'] values=[] getElementByTagName = dom.getElementsByTagName for element in elements: reflist = getElementsByTagName(element) values.append(reflist[0].firstChild.nodeValue) But as Alex already pointed out, you'd be better using (c)ElementTree. > They both seem ugly IMO (read: longer than intuitively necessary), I'd say this is a common problem with XML :-/ From pingmaximus at gmail.com Wed Aug 1 16:10:17 2007 From: pingmaximus at gmail.com (Maximus Decimus) Date: Wed, 01 Aug 2007 20:10:17 -0000 Subject: Extending Python by Adding Keywords & Data types In-Reply-To: <1185973687.883520.227540@k79g2000hse.googlegroups.com> References: <1185913739.879602.212950@w3g2000hsg.googlegroups.com> <1185973687.883520.227540@k79g2000hse.googlegroups.com> Message-ID: <1185999017.188830.88860@d55g2000hsg.googlegroups.com> On Aug 1, 9:08 am, Paul McGuire wrote: > On Jul 31, 3:28 pm, Maximus Decimus wrote: > > > > > I am using python v2.5 and I am an amateur working on python. I am > > extending python for my research work and would like some help and > > guidance w.r.t this matter from you experienced python developers. > > > II want to add some more KEYWORDS and DATATYPES into the python script > > apart from the existing ones. > > Vishak - > > Let me echo the sentiments of the other posters who replied to your > message. It is *very* unusual for a new Python user to begin their > Pythonic journey by modifying the Python interpreter to add new > keywords and datatypes. Python is designed to be a very flexible and > extensible language just as it is. > > Since you are familiar with C, your question strikes those of us on > this group as one who would write "I'm just learning C and I would > like to modify the core library to add some new functions for my > research." And all the readers on comp.lang.c scratch their heads, > thinking "Huh? Why doesn't this guy just write the functions in his > own program, the way the language was designed for him to do in the > first place?" > > Now maybe your research is in the field of language design, and has > something to do with the relative ease/difficulty of modifying > computer languages. Then it would make sense for you to dive right in > to learning how to modify Python's compiler. > > But if your research was in just about any other field (from finite > elements analysis to genetic programming to genetics to simulations to > process control to whatever), DON'T start by modifying Python - start > by LEARNING Python. > > When a new datatype is required in a Python program, then the > programmer writes a class to implement this datatype. The class > itself is written in Python, but it can be used just like any built-in > datatype. For instance, here is a new datatype I just thought up - a > Box that can hold up to 'n' objects. > > class Box(object): > def __init__(self,n): > self.capacity = n > self.contents = [] > > def add(self,other): > if len(self.contents) < self.capacity: > self.contents.append( other ) > else: > raise ValueError("can't add any more to this Box") > > def __iadd__(self,other): > self.add(other) > return self > > box = Box(3) > > # add stuff to the box until it overflows > while(True): > box += object() > > Voila! I created a new datatype, Box, and even added support for it > to understand how to use the '+=' operator so that adding objects to > the Box looks like an addition statement. All without modifying > Python itself. (Here's an exercise - extend this example so that the > Box has a limited capacity in the *weight* of the added objects, as > well as in the number of objects.) > > This is the basic way that one extends Python with their own new > datatypes and methods. New keywords are a little rarer, but really, > start by just adding methods, like the add method above. Python users > around the world develop a wide range of applications and programs > using just these techniques, and never touch the Python compiler > itself. > > And here is a case you'd like to avoid. Let's say you start by > learning how to modify Python because you need a general-purpose > container for things. You spend two weeks learning how to do this, > getting your code mostly debugged, and then you post to > comp.lang.python your proud achievement. Immediately the replies come > back, "Congratulations, newbie, you just reinvented the built-in list > type." Without LEARNING Python, you wont know what is already > provided in the language. > > So, in general this is a helpful group, and it is possible that you DO > need to learn how to add datatypes and keywords to Python as your > first objective. We're not trying to pry, but give us a bit more > detail. Someone might even rough out for you what one of your new > datatypes might look like. So pray, tell us what sort of specialized > datatypes and keywords do you think you need to add, and we'll try to > point you in one or more directions. > > -- Paul On Aug 1, 9:08 am, Paul McGuire wrote: > On Jul 31, 3:28 pm, Maximus Decimus wrote: > > > > > I am using python v2.5 and I am an amateur working on python. I am > > extending python for my research work and would like some help and > > guidance w.r.t this matter from you experienced python developers. > > > II want to add some more KEYWORDS and DATATYPES into the python script > > apart from the existing ones. > > Vishak - > > Let me echo the sentiments of the other posters who replied to your > message. It is *very* unusual for a new Python user to begin their > Pythonic journey by modifying the Python interpreter to add new > keywords and datatypes. Python is designed to be a very flexible and > extensible language just as it is. > > Since you are familiar with C, your question strikes those of us on > this group as one who would write "I'm just learning C and I would > like to modify the core library to add some new functions for my > research." And all the readers on comp.lang.c scratch their heads, > thinking "Huh? Why doesn't this guy just write the functions in his > own program, the way the language was designed for him to do in the > first place?" > > Now maybe your research is in the field of language design, and has > something to do with the relative ease/difficulty of modifying > computer languages. Then it would make sense for you to dive right in > to learning how to modify Python's compiler. > > But if your research was in just about any other field (from finite > elements analysis to genetic programming to genetics to simulations to > process control to whatever), DON'T start by modifying Python - start > by LEARNING Python. > > When a new datatype is required in a Python program, then the > programmer writes a class to implement this datatype. The class > itself is written in Python, but it can be used just like any built-in > datatype. For instance, here is a new datatype I just thought up - a > Box that can hold up to 'n' objects. > > class Box(object): > def __init__(self,n): > self.capacity = n > self.contents = [] > > def add(self,other): > if len(self.contents) < self.capacity: > self.contents.append( other ) > else: > raise ValueError("can't add any more to this Box") > > def __iadd__(self,other): > self.add(other) > return self > > box = Box(3) > > # add stuff to the box until it overflows > while(True): > box += object() > > Voila! I created a new datatype, Box, and even added support for it > to understand how to use the '+=' operator so that adding objects to > the Box looks like an addition statement. All without modifying > Python itself. (Here's an exercise - extend this example so that the > Box has a limited capacity in the *weight* of the added objects, as > well as in the number of objects.) > > This is the basic way that one extends Python with their own new > datatypes and methods. New keywords are a little rarer, but really, > start by just adding methods, like the add method above. Python users > around the world develop a wide range of applications and programs > using just these techniques, and never touch the Python compiler > itself. > > And here is a case you'd like to avoid. Let's say you start by > learning how to modify Python because you need a general-purpose > container for things. You spend two weeks learning how to do this, > getting your code mostly debugged, and then you post to > comp.lang.python your proud achievement. Immediately the replies come > back, "Congratulations, newbie, you just reinvented the built-in list > type." Without LEARNING Python, you wont know what is already > provided in the language. > > So, in general this is a helpful group, and it is possible that you DO > need to learn how to add datatypes and keywords to Python as your > first objective. We're not trying to pry, but give us a bit more > detail. Someone might even rough out for you what one of your new > datatypes might look like. So pray, tell us what sort of specialized > datatypes and keywords do you think you need to add, and we'll try to > point you in one or more directions. > > -- Paul Firstly to Paul, I clearly got your reply and I am working hard to know more about python by going through the tutorials. I did start with the doc tutorial available along with the package. I have done the basic learning of python which is way simple compared to the stuffs you are talking about. I have just jumped into the extending python part of the document. I think I need to master that portion. Your code snippet was quite simple and it explained me very well than the tutorial. HAts off to u!! Bjorn, Marc, Ben, I also noted your comments and I am working on them. I have gone through the Python Classes portion and I need to workout quite a lot excercises to make myself familiar with Python. I am gonna start doing that right away. Coming to the complete explanation of what I am upto: I am doing my research in Pervasive space environments filled with sensors and actuators. I am just trying to modify an existing language which suits that kind of environment. Pervasive space environment is filled with sensors and actuators and everything depends on their state and behavior ie on the sensor readings and actuator states. So why not express a language variable in terms of sensors and actuators? THis is my idea of working around and trying to introduce new data types for these sensor and actuator variables which store sensor readings and actuator states. I think this explains a bit clearly on what I am looking for..Suggestion and ideas are kindly appreciated. Thanks in advance and for your time. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Aug 13 16:12:25 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 13 Aug 2007 22:12:25 +0200 Subject: decorators - more than just syntactic sugar References: <46be005e$0$13866$ba620e4c@news.skynet.be> Message-ID: <5ibs99F3nq29uU1@mid.individual.net> BJ?rn Lindqvist wrote: > unpedagogically not separated from ordinary functions. Decorators _are_ ordinary functions. Remember the "syntactic sugar" in this thread? Regards, Bj?rn -- BOFH excuse #338: old inkjet cartridges emanate barium-based fumes From aahz at pythoncraft.com Sat Aug 11 17:25:29 2007 From: aahz at pythoncraft.com (Aahz) Date: 11 Aug 2007 14:25:29 -0700 Subject: Augmented assignment (was Re: Something in the function tutorial confused me.) References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> Message-ID: In article , OKB (not okblacke) wrote: > > This sentence is phrased as though it is the whole story, but it >isn't, because the operation might not in fact wind up being an >assignment. Shouldn't there be an "except see below" or something >there, to alert the reader that in some cases a true assignment doesn't >occur? (I realize that the exception follows quite closely on the heels >of this sentence, but it doesn't follow immediately, and is separated by >a paragraph break and intervening material about the parallel to >unaugmented x = x + 1. On initial reading my tendency is to read the >end of the sentence quoted above, see a paragraph break and apparently >explanatory material, and go "oh, okay, I now have the full >specification of this syntax" when in fact I don't.) That's a good idea -- doc patches are always welcome! -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "And if that makes me an elitist...I couldn't be happier." --JMS From daniels at dsl-only.net Fri Aug 17 09:09:29 2007 From: daniels at dsl-only.net (Scott David Daniels) Date: Fri, 17 Aug 2007 06:09:29 -0700 Subject: clarification In-Reply-To: References: Message-ID: <13cb7frnqs8f6d9@corp.supernews.com> Laurent Pointal wrote: > Thomas Jollans a ?crit : >> On Friday 17 August 2007, Beema shafreen wrote: >>> hi everybody, >>> i have a file with data separated by tab >>> mydata: >>> fhl1 fkh2 > >>> shows these two are separated by tab represented as columns >>> i have to check the common data between these two coloumn1 an coloumn2 >>> my code: >>> data = [] >>> data1 = [] >>> result = [] >>> fh = open('sheet1','r') >>> for line in fh.readlines(): >>> splitted = line.strip().split('\t') >>> data.append(splitted[0]) >>> data1.append(splitted[1]) >>> for k in data: >>> if k in data1: >>> result.append(k) >>> print result >>> fh.close() > > Use set data type for data and data1 (you fill them with an algo like th > one you wrote - just use add() in place of appen()) then use set > intersection to get common data. > > See doc for set data type: > http://docs.python.org/lib/types-set.html > > Would look like (not tested): > data = set() > data1 = set() > fh = open('sheet1','r') > for line in fh.readlines(): > splitted = line.strip().split('\t') > data.add(splitted[0]) > data1.add(splitted[1]) > > result = data.intersection(data1) lefts = set() rights = set() with open('sheet1', 'r') as fh: for line in fh: trimmed = line.strip() if trimmed: # Skip blanks (file end often looks like that) left, right = line.strip().split('\t') lefts.add(left) rights.add(right) result = lefts & rights -Scott From python at jayloden.com Mon Aug 27 13:20:37 2007 From: python at jayloden.com (Jay Loden) Date: Mon, 27 Aug 2007 13:20:37 -0400 Subject: Python error on Mac In-Reply-To: <46D0EC54.8030806@gmail.com> References: <46D0EC54.8030806@gmail.com> Message-ID: <46D307E5.2010706@jayloden.com> Clover wrote: > When trying to do some things on my Mac (starting Lyx, compiling Latex > via TextMate) I get this error: > > python: execv: > /Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python: > No such file or directory > > I (and people on Lyx and TextMate lists) are at a complete loss as to > why this is happening. I didn't (at least intentionally) fiddle with > Python setup. > > Thanks! what is the output of 'which python' - this should show what python executable is running: [jloden at macbook jloden]$ which python /Library/Frameworks/Python.framework/Versions/Current/bin/python You should then check the output of ls -l agains the value of the above: [jloden at macbook jloden]$ ls -l /Library/Frameworks/Python.framework/Versions/Current/bin/python lrwxr-xr-x 1 root admin 9 Jul 14 01:53 /Library/Frameworks/Python.framework/Versions/Current/bin/python -> python2.5 That will show what the executable is actually linked to. Other thoughts would be to check if the /Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python directory exists, or even if /Library/Frameworks/Python.framework/Versions/2.5/ exists. Perhaps you are trying to execute Python 2.5 but don't actually have it installed? -Jay From aleax at mac.com Wed Aug 1 11:04:56 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 1 Aug 2007 08:04:56 -0700 Subject: Where do they tech Python officialy ? References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> <1185265091.276958.239910@r34g2000hsd.googlegroups.com> <1i23wyk.avc945i4dwsiN%aleax@mac.com> <1185951027.061072.188280@g4g2000hsf.googlegroups.com> Message-ID: <1i25pbm.7op8wk21hjzwN%aleax@mac.com> NicolasG wrote: > > Open source projects do not require previous professional experience to > > accept volunteers. So, one way out of your dilemma is to make a name > > for yourself as an open source contributor -- help out with Python > > itself and/or with any of the many open source projects that use Python, > > and you will both learn a lot _and_ acquire "professional experience" > > that any enlightened employer will recognize as such. That will take a > > while, but not as long as getting a college degree (and it will be far > > cheaper than the degree). > > > > Alex > > I think this is the best idea to escape the python amateur circle and > go in to open source project that are considered to be professional > projects. I don't know if it will be better to find a project to > contribute or to start a new one .. Will have a look around and think > about. Unless you have some specific new idea that you're keen to address and can't be met by existing projects, joining an existing project would normally be a better bet. One-person projects are rarely as important as larger ones, and it's quite hard to get other collaborators to a new project; working in a project with existing code and contributors will also be more instructive. As for which OS projects are "considered to be professional", just about all large successful ones are so considered: after all, even games, say, are "professional projects" from the POV of firms that develop and sell them, such as EA!-) Alex From neptundancer at gmail.com Sun Aug 26 12:49:53 2007 From: neptundancer at gmail.com (neptundancer at gmail.com) Date: Sun, 26 Aug 2007 16:49:53 -0000 Subject: lisper learning python, ... could you please comment my first python program? In-Reply-To: <13d3aot56lq4l58@corp.supernews.com> References: <1188143768.742884.38520@r29g2000hsg.googlegroups.com> <13d3aot56lq4l58@corp.supernews.com> Message-ID: <1188146993.825966.189520@50g2000hsm.googlegroups.com> Thanks a lot for comments! I am going to fix the source according to your advices ;) Nep On Aug 26, 6:32 pm, Steven D'Aprano wrote: > On Sun, 26 Aug 2007 15:56:08 +0000, neptundancer wrote: > > Hi, > > to extend my skills, I am learning python. I have written small > > program which computes math expression like "1+2*sin(y^10)/cos(x*y)" and > > similar, so far only + - * / ^ sin con tan sqrt are supported. But my > > program is quite inextensible, I have to change the code to add new > > functions... Could some fellow experienced pythonista give me some tips > > how to make my program shorter, and more extensible? > > Just a few comments at random. This is certainly not meant to be > exhaustive: > > > def normalize(string): > > tmp = "".join([c for c in string if c != " "]) > > return "(" + tmp + ")" > > Try this instead: > > def normalize(astring): > return "(" + astring.replace(" ", "") + ")" > > > > > def most_nested_expression(string): > [snip code] > > if level != 0: > > raise IOError("mismatched parens") > > You raise IOError quite often, but that's a misuse of it. IOError is a > subclass of EnvironmentError, and is meant to indicate (e.g.) a failed > read from a disk. > > If you execute help(IOError) at the interactive prompt, you will see: > > class IOError(EnvironmentError) > | I/O operation failed. > > I suggest a better exception to use would be ValueError, or even create > your own: > > class MyCustomError(ValueError): > pass > > would be a minimal example. > > > def is_reduced_expression(string): > > for c in string: > > if c == "^" or c == "*" or c == "/" or c == "+" or c == "-": > > return False > > return True > > Change that to: > > for c in string: > if c in "^*/+-": return False > return True > > [snip] > > > def add(a, b): return a + b > > def sub(a, b): return a - b > > def mul(a, b): return a * b > > def div(a, b): return a / b > > Replace the above four functions with: > > from operator import add, sub, mul > from operator import truediv as div > > > def translate_function(fn_str): > > if fn_str == "+": return add > > elif fn_str == "-": return sub > > elif fn_str == "*": return mul > > elif fn_str == "/": return div > > elif fn_str == "^": return math.pow > > elif fn_str == "sin": return math.sin elif fn_str == "cos": return > > math.cos elif fn_str == "tan": return math.tan elif fn_str == > > "sqrt": return math.sqrt else: raise IOError("unknown function %s" % > > fn_str) > > fn_map = {"+": add, "-": sub, "*": mul, "/": div, > "^": math.pow, "sin": math.sin } # etc. > > def translate_function(fn_str): > try: > return fn_map[fn_str] > except KeyError: > raise ValueError("unknown function '%s'" % fn_str) > > Hope that helps. > > -- > Steven. From horpner at yahoo.com Mon Aug 6 14:04:12 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 06 Aug 2007 18:04:12 GMT Subject: Something in the function tutorial confused me. References: <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <1186422680.103021.105230@l70g2000hse.googlegroups.com> Message-ID: On 2007-08-06, Lee Fleming wrote: > On Aug 6, 12:30 pm, "Hamilton, William " wrote: >> When you call f(23), the variable y within it gets created and points at >> None. When f(23) exits, the y that it created gets destroyed. (Well, >> goes out of scope, but even if it's not garbage collected it won't ever >> come back into scope.) When you then call f(24), a new y is created >> that also points to None, and disappears forever when f(24) exits. >> >> The values in a def statement are created when the def is executed, but >> the variables are only created when the function is actually called, and >> new ones are created every time the function is called. >> >> -- >> -Bill Hamilton- Hide quoted text - >> >> - Show quoted text - > > why isn't the y in def f (x, y = []): something > garbage-collected? Because the result of evaluating [] is stored somewhere in f as a default argument. The result of evaluating [] is a new empty list. It will never be garbage collected, because f maintains a reference to it. Note that while [] and None may appear to be similar expressions, they are not. None evaluated to itself, while [] evaluates to a new empty list. >>> None is None True >>> [] is [] False -- Neil Cerutti 8 new choir robes are currently needed, due to the addition of several new members and to the deterioration of some of the older ones. --Church Bulletin Blooper From semanticist at gmail.com Fri Aug 31 11:33:03 2007 From: semanticist at gmail.com (Miles) Date: Fri, 31 Aug 2007 11:33:03 -0400 Subject: fcntl problems In-Reply-To: <1188573280.155018.109360@o80g2000hse.googlegroups.com> References: <1188512377.441241.107900@q4g2000prc.googlegroups.com> <1188515889.352267.220790@q5g2000prf.googlegroups.com> <1188568022.988154.188230@y42g2000hsy.googlegroups.com> <1188573280.155018.109360@o80g2000hse.googlegroups.com> Message-ID: On 8/31/07, mhearne808 wrote: > Looking at my flock(3) man page, I'm guessing that "35" is the error > code for EWOULDBLOCK. Which system header file am I supposed to look > in to figure that magic number out? I got the error number by looking at the IOError exception raised when playing with the interactive interpreter, but I really should have written: from errno import EWOULDBLOCK ... if e.args[0] == EWOULDBLOCK: ... - Miles From mkb at incubus.de Thu Aug 23 03:38:23 2007 From: mkb at incubus.de (Matthias Buelow) Date: 23 Aug 2007 07:38:23 GMT Subject: Xah's Edu Corner: Under the spell of Leibniz's dream References: <1187567809.896668.228650@z24g2000prh.googlegroups.com> <1187598193.118227.270460@19g2000hsx.googlegroups.com> <46ca1e65$1_3@news.chariot.net.au> Message-ID: <5j4rrfF3s3h2rU1@mid.dfncis.de> In comp.lang.lisp Bikal KC wrote: > I used usenet years ago then stopped for couple of years. I remember > seeing him/her on c.l.perl I believe doing the same thing he/she is > doing atm. I'd say the ultimate usenet superstar. Wow! I think it's some (probably mild) form of autism. No offense intended, Xah. From chicorbleak at gmail.com Tue Aug 21 15:29:46 2007 From: chicorbleak at gmail.com (chicorbleak at gmail.com) Date: Tue, 21 Aug 2007 19:29:46 -0000 Subject: Partial Blur Message-ID: <1187724586.607512.227110@m37g2000prh.googlegroups.com> Hello, I'm looking for an image manipulation library which would allow me to blur an oval-shaped part of my picture, instead of the whole thing. I couldn't find a way to do this using the tools I see in the API of Python Imaging Library. If you know how to do this, I'd appreciate it if you left a note. Thanks CB From wolf_tracks at invalid.com Wed Aug 22 13:28:58 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Wed, 22 Aug 2007 17:28:58 GMT Subject: What Are These Import/From Statements about? Message-ID: Is there a single source that explains these statements? ------------------------------ from Tkinter import * from Numeric import * import Image import ImageChops import ImageTk import time import binascii import tkMessageBox import tkSimpleDialog from tkFileDialog import asksaveasfilename from tkFileDialog import askopenfilename import MakeQTE import socket import struct import glob import bisect import os, os.path import datetime from os.path import basename, splitext --------------------------------------------- -- Wayne Watson (Nevada City, CA) Web Page: From mfglinux at gmail.com Wed Aug 15 13:42:02 2007 From: mfglinux at gmail.com (mfglinux) Date: Wed, 15 Aug 2007 10:42:02 -0700 Subject: "Variable variable name" or "variable lvalue" Message-ID: <1187199722.618893.281170@r29g2000hsg.googlegroups.com> Hello to everybody I would like to know how to declare in python a "variable name" that it is in turn a variable In bash shell I would wrote sthg like: for x in `seq 1 3` do M$i=Material(x) #Material is a python class done Why I need this? Cause I have a python module that obliges me to build a variable called Period, which should have a variable name of summands (depends on the value of x) #Let's say x=3, then Period definition is Period=Slab(Material1(12.5)+Material2(25)+Material3(12.5)) #Slab is a python class I dont know how to automatize last piece of code for any x thank you Marcos From python at jayloden.com Thu Aug 9 12:17:02 2007 From: python at jayloden.com (Jay Loden) Date: Thu, 09 Aug 2007 12:17:02 -0400 Subject: Issues of state In-Reply-To: References: <7x8x8mpn37.fsf@ruckus.brouhaha.com> <7xfy2t8l5n.fsf@ruckus.brouhaha.com> <5uhro4-st8.ln1@lairds.us> Message-ID: <46BB3DFE.5030504@jayloden.com> Steve Holden wrote: > As far as I'm concerned the major issue with trying to have "desktop web > apps" compete with true windowed applications is the difficulty of > maintaining sensible interactions with the interface. AJAX designs have > increased the interaction level at the expense of greater complexity - > there is more state to be transferred, and a much higher interaction > rate with the server. But the browser is a terrible front-end for AJAX > designs because it doesn't record the state changes that take place as a > result of requests for updated InnerHTML content, so if the user is > unwise enough to press the "back" button she loses all traces of the > non-page interactions that have taken place since the page was loaded. > > So "desktop web apps" should ensure that they get displayed in browser > windows with minimal user interface decoration. But even then there's > always that chance that sophisticated users will use keyboard shortcuts > like ALT-left-arrow. > > That, in summary, is why my 2004 PyCon paper[1] was subtitled "The Back > Button is Not Your Friend". > > regards > Steve > > [1]: http://www.python.org/pycon/dc2004/papers/18/Setting_A_Context.pdf There's been some interesting work done in that area as well: http://dev2dev.bea.com/pub/a/2006/01/ajax-back-button.html http://www.isolani.co.uk/blog/javascript/FixingTheBackButtonThatAjaxBroke In particular, the RSH (Really Simple History) Framework is an open source solution to the problem: http://www.onjava.com/pub/a/onjava/2005/10/26/ajax-handling-bookmarks-and-back-button.html Like most things involving dynamic client side-javascript code and AJAX technology, it's a lot harder than you'd like it to be to solve the problem, but in cases where the Back button is really an issue, it's worth the effort. -Jay From evan at yelp.com Sat Aug 18 01:19:06 2007 From: evan at yelp.com (Evan Klitzke) Date: Fri, 17 Aug 2007 22:19:06 -0700 Subject: using super() to call two parent classes __init__() method In-Reply-To: <1187328619.039289.244900@g4g2000hsf.googlegroups.com> References: <1187328619.039289.244900@g4g2000hsf.googlegroups.com> Message-ID: On 8/16/07, 7stud wrote: > When I run the following code and call super() in the Base class's > __init__ () method, only one Parent's __init__() method is called. As the other posters have mentioned, each class needs to make a call to super. This is because the super call doesn't really call the parent class' method, it actually calls the next method in the MRO. The MRO in this case will be Base -> Parent1 -> Parent2 -> object. You can read the details of Python's MRO here http://www.python.org/download/releases/2.3/mro/ -- Evan Klitzke From bronger at physik.rwth-aachen.de Fri Aug 24 02:45:41 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 24 Aug 2007 08:45:41 +0200 Subject: Co-developers wanted: document markup language References: <87odgyyx9u.fsf@wilson.homeunix.com> <87tzqpew22.fsf@wilson.homeunix.com> Message-ID: <87tzqp77my.fsf@wilson.homeunix.com> Hall?chen! Aahz writes: > Torsten Bronger wrote: > >> Aahz writes: >> >>> Torsten Bronger wrote: >>> >>>> Some LaTeX users in Aachen thought about a general-use markup >>>> language this spring. I wrote some code and a rough project >>>> description, however, we could need some help. >>> >>> [...] > > My point is that docutils already exists; given the combined > competition from LaTeX and docutils and OpenOffice, you should > probably explain what differentiates your project and why people > should support your project instead of (or in addition to) others. reStructuredText, AsciiDoc, and some others focus on source code documentation, or on software documentation. In contrast to that, our markup should be suitable for PhD theses, papers and the like. Thus, it has weaker means for code snippets, RFC citation etc, but rich syntax for bibliographic entries, index entries, math, and floating figures. Additionally, input methods simplify using characters like ?, ?, or ?. The differences to LaTeX are explained comprehensively on the webpage, and actually LaTeX is the real competitor rather than reStructuredText. OOo isn't a plain text format, and has no strong semantic markup. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From bj_666 at gmx.net Tue Aug 7 13:49:42 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Aug 2007 17:49:42 GMT Subject: re.sub does not replace all occurences References: <1186507704.440408.20630@57g2000hsv.googlegroups.com> Message-ID: <5hrplmF3ldifeU7@mid.uni-berlin.de> On Tue, 07 Aug 2007 10:28:24 -0700, Christoph Krammer wrote: > Hello everybody, > > I wanted to use re.sub to strip all HTML tags out of a given string. I > learned that there are better ways to do this without the re module, > but I would like to know why my code is not working. I use the > following: > > def stripHtml(source): > source = re.sub("[\n\r\f]", " ", source) > source = re.sub("<.*?>", "", source, re.S | re.I | re.M) > source = re.sub("&(#[0-9]{1,3}|[a-z]{3,6});", "", source, re.I) > return source > > But the result still has some tags in it. When I call the second line > multiple times, all tags disappear, but since HTML tags cannot be > overlapping, I do not understand this behavior. There is even a > difference when I omit the re.I (IGNORECASE) option. Without this > option, some tags containing only capital letters (like ) were > kept in the string when doing one processing run but removed when > doing multiple runs. Can you give some example HTML where it fails? Ciao, Marc 'BlackJack' Rintsch From ajmacd at ns.sympatico.ca Mon Aug 13 09:50:22 2007 From: ajmacd at ns.sympatico.ca (Aaron J. M.) Date: Mon, 13 Aug 2007 06:50:22 -0700 Subject: Pausing and Unpausing Threads In-Reply-To: References: <1186883176.319755.304970@d55g2000hsg.googlegroups.com> <13bulsklq359q8f@corp.supernews.com> <1186950645.886995.56060@w3g2000hsg.googlegroups.com> <1186965947.914607.222260@o61g2000hsh.googlegroups.com> Message-ID: <1187013022.310789.139750@b79g2000hse.googlegroups.com> On Aug 13, 2:31 am, "Gabriel Genellina" wrote: > Use the same Queue; put a special kind of Action, or just a None object, > to tell the thread that there are no more things to process. > From the main thread, you can join() the others, waiting for them to > finish. Ah, thank you very much. :) - Aaron J. M. From sbellon at sbellon.de Fri Aug 3 04:31:03 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Fri, 3 Aug 2007 10:31:03 +0200 Subject: replacement for execfile References: Message-ID: <20070803103103.7820a34e@cube.tz.axivion.com> On Sun, 29 Jul, Steven D'Aprano wrote: > (1) Don't use eval, exec or execfile. Ok, then I would really like to ask a question about how to solve my problem without execfile ... ;-) I am embedding Python on Windows using MinGW. In order to execute a Python script file, calling any of the PyRun_File functions does not work but crashes (I assume this is because the Python DLL was built using Microsoft tools and those tools and MinGW have different FILE structures, so a FILE *fp cannot be passed from my MinGW C code to the Python DLL). Therefore my current solution is to call PyRun_String functions and execute a string with the content "execfile('filename')". Is there a way to solve this problem with PyRun_File? -- Stefan Bellon From wooshi at gmail.com Sun Aug 26 04:20:35 2007 From: wooshi at gmail.com (shi wu) Date: Sun, 26 Aug 2007 16:20:35 +0800 Subject: A online python decompiler Message-ID: depython [http://www.depython.net depython online service] could decompile python bytecodes. Depython online service supports Python versions from 2.4up to 2.5.You can freely test its function online. -------------- next part -------------- An HTML attachment was scrubbed... URL: From byte8bits at gmail.com Wed Aug 8 09:55:58 2007 From: byte8bits at gmail.com (brad) Date: Wed, 08 Aug 2007 09:55:58 -0400 Subject: This bit of code hangs Python Indefinitely In-Reply-To: References: Message-ID: Chris Mellon wrote: > ... the producer is designed to block if > the queue is full. You can use the put_nowait method to have it raise > an exception instead of blocking. I assumed that the behavior would have been the other way around. I should not have made that assumption. From aleax at mac.com Wed Aug 29 10:44:56 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 29 Aug 2007 07:44:56 -0700 Subject: What's the difference ? References: <1188394767.333396.129020@r29g2000hsg.googlegroups.com> Message-ID: <1i3ljrn.nrie0r1227d9jN%aleax@mac.com> Alex wrote: > Hye, > > I was just wondering what is the difference between > > >> if my_key in mydict: > >> ... > > and > > >> if mydict.has_keys(my_key): Mis-spelled (no final s in the method name). > >> ... > > I've search a bit in the python documentation, and the only things I > found was that they are "equivalent". Semantically they are, but `in' is faster, more concise, & readable. > But in this (quiet old) sample ( "http://aspn.activestate.com/ASPN/ > Cookbook/Python/Recipe/59875" ), there is difference between the two > notation. What that example is pointing to as "wrong way" is a NON-equivalent approach that's extremely slow: if my_key in mydict.keys(): The call to keys() takes time and memory to build a list of all keys, after which the ``in'' operator, having a list as the RHS operand, is also quite slow (O(N), vs O(1)!). So, never use that useless and silly call to keys() in this context! Alex From steve at holdenweb.com Fri Aug 31 12:14:40 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 31 Aug 2007 12:14:40 -0400 Subject: Setting a read-only attribute In-Reply-To: <1188574216.529447.140390@i38g2000prf.googlegroups.com> References: <1188509700.915517.178440@z24g2000prh.googlegroups.com> <1188548061.663133.273160@q5g2000prf.googlegroups.com> <1188574216.529447.140390@i38g2000prf.googlegroups.com> Message-ID: tleeuwenburg at gmail.com wrote: > On Aug 31, 6:14 pm, Alexandre Badez wrote: >> On Aug 30, 11:35 pm, "tleeuwenb... at gmail.com" >> wrote: >> >>> I have an object and wish to set an attribute on it which, >>> unfortunately for me, is read-only. >>> How can I go about this? >>> Cheers. >>> -T >> Could you show the object you want to set his attribute? >> Until that, it's difficult to answer to you. >> >> PS: If the attribut is on read only, their must a good reason for >> that ;) > > Hi all, > > Thanks for all the responses. What I'm trying to do is kludge around > something. sys.settrace takes a method whose arguments are (frame, > event, arg). I want to have a tracer class which can be instantiated > and listen in on these trace calls. > > Another way to go about it *might* be to have a module-level list of > registered Tracer objects which a module-level trace method informs of > events. It would probably be easier. In fact, I'll go do that. > > *That said*, I still think it makes sense to be able to have objects > register with sys.settrace. > > So what I did then was declare a static method with the same pattern > expected by sys.settrace. I then want to use something like __dict__ > or __setattr__ to give that method a reference to the owning object. > And this is what I'm trying to do -- declare a static method, then "un- > static it" by adding a reference to the callable object... > > Here's some code: > ------------------------------------------------------------ > > import sys > > > class Tracer: > ''' > Instantiate this in order to access program trace information. > > ''' > > def _getcallback(self): > > @staticmethod > def callback(frame, event, arg): > print "tracing ...", tracerReference > #print "line ", frame.f_lineno, frame.f_locals > > return callback > > def startTrace(self): > callback = self._getcallback() > callback.__dict__['tracerReference'] = self > sys.settrace(callback) > > > def foo(dict): > for i in range(2): > pass > > if __name__ == "__main__": > t = Tracer() > t.startTrace() > foo({1 : 5}) > Surely the thing to do, if I understand you, is to declare callback as a standard method and then pass a reference to a bound method (the most obvious candidate being self.callback) to sys.settrace(). sholden at bigboy ~/Projects/Python $ cat test05.py import sys class Tracer: ''' Instantiate this in order to access program trace information. ''' def callback(self, frame, event, arg): print "tracing ...", self print "line ", frame.f_lineno, frame.f_locals def startTrace(self): sys.settrace(self.callback) def foo(dict): for i in range(2): pass if __name__ == "__main__": t = Tracer() t.startTrace() foo({1 : 5}) sholden at bigboy ~/Projects/Python $ python test05.py tracing ... <__main__.Tracer instance at 0x7ff2514c> line 19 {'dict': {1: 5}} sholden at bigboy ~/Projects/Python $ Does this do what you want? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From greg.kujawa at gmail.com Fri Aug 3 11:00:59 2007 From: greg.kujawa at gmail.com (gregarican) Date: Fri, 03 Aug 2007 15:00:59 -0000 Subject: Eclipse/PyDev question. In-Reply-To: <1186153119.391091.275860@r34g2000hsd.googlegroups.com> References: <1186153119.391091.275860@r34g2000hsd.googlegroups.com> Message-ID: <1186153259.372809.230110@d30g2000prg.googlegroups.com> On Aug 3, 10:58 am, king kikapu wrote: > Hi, > this is actually a question to those of us who use Eclipse and Pydev > as their main Python developing environment. As i use Eclipse (3.3 > Europa) only for Python and i have nothing to do with Java, is there a > way to disable/uninstall some Java-specific stuff and make the > environment actually more snappy ?? > > thanks for any help I've used Eclipse for Java, Python, and Ruby development and can say that AFAIK "Eclipse" and "snappy" are contradictions. Like "jumbo" "shrimp" :-/ From sbassi at clubdelarazon.org Mon Aug 27 19:04:03 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Mon, 27 Aug 2007 20:04:03 -0300 Subject: Biased random? In-Reply-To: <46D34ECF.8060106@sdf.lonestar.org> References: <13d6i72s8b2a3ad@corp.supernews.com> <46D34ECF.8060106@sdf.lonestar.org> Message-ID: <9e2f512b0708271604r8628f52pa576334579b42b43@mail.gmail.com> On 8/27/07, J. Cliff Dyer wrote: > Play with your log to get the range you want Here you can get "true" random numbers (not pseudorandom, they claim to use a quatum generaton (?)) by fetching them from: http://random.irb.hr/ They give you a python class t insert into your code, but you need to register to use it (free). I am not affiliated to them in any way, I just used it once to play with it and it worked. Best, -- Sebasti?n Bassi (???????) Diplomado en Ciencia y Tecnolog?a. GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D From __peter__ at web.de Fri Aug 3 04:27:14 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 03 Aug 2007 10:27:14 +0200 Subject: Bug in execfile? References: Message-ID: Fernando Perez wrote: > I'm finding the following behavior truly puzzling, but before I post a bug > report on the site, I'd rather be corrected if I'm just missing somethin > obvious. > > Consider the following trivial script: > > from math import sin, pi > wav = lambda k,x: sin(2*pi*k*x) > print wav(1,0.25) > The above runs just fine from a prompt, or even interactively via > execfile(). Now, consider calling it by using this instead: > > #!/usr/bin/env python > def runscript(fname): > """Run a file by calling execfile().""" > execfile(fname) > runscript('execfilebugscript.py') > If I run the above, calling the first script 'execfilebugscript.py' and > the second 'execfilebug.py', I get this: > NameError: global name 'sin' is not defined > I'm really, really puzzled by this. From reading the execfile() docs, I > had the hunch to change the call to: > > execfile(fname,{}) > > and now the problem disappears, so I can keep on working. If you execfile() a script names not known in the context of a function are looked up in the global namespace, but assignments set names in the local namespace. Consider execfile(filename) for a file x = 42 def f(): print x f() x and f are put into the local namespace, but x is not local to the function f and therefore looked up in f's globals. Now if you call execfile() in the global namespace of the client script the global and local namespace are identical >>> globals() is locals() True so x although put into the local namespace will still be found when looked up in the global namespace. That is the same situation as in your workaround execfile(filename, {}). This however is not the case if you call execfile() inside a function. Here global and local namespace differ. In your example, when you put another execfile() into the global namespace of the client script the sin() imported there is the only one that your wav() function sees. You can verify that by putting def sin(phi): return "I'm not math.sin()" instead of if 1: .... into execfilebug.py. Can the current behaviour of execfile() be changed into a more intuitive one? Not with only two namespaces. You'd probably need something similar to closures, and I don't think the necessary work would be worth the effort. Peter From a.schmolck at gmail.com Fri Aug 17 18:30:34 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Fri, 17 Aug 2007 23:30:34 +0100 Subject: best GUI library for vector drawing program References: <1187357244.883516.79840@j4g2000prf.googlegroups.com> <1187366824.140017.285150@z24g2000prh.googlegroups.com> <1187373155.876788.25610@e9g2000prf.googlegroups.com> Message-ID: [x-posts removed] chewie54 writes: > I should have also mentioned that is for a commercial application. That > doesn't rule Qt or PyQt out, but this is a startup company with very little > income so my first choice would be to use some GUI library that is free to > use for commercial apps. Check out the trolltech webpage: IIRC although it normally costs a few k$, you can get it much cheaper if you are a startup (you yearly revenue must be lower than 200k$ or something; this also only works once and maybe up to 2 licenses or so etc). 'as From goldtech at worldpost.com Wed Aug 1 22:21:53 2007 From: goldtech at worldpost.com (goldtech) Date: Wed, 01 Aug 2007 19:21:53 -0700 Subject: frequency analysis of a DB column Message-ID: <1186021313.413443.184060@i38g2000prf.googlegroups.com> In Python 2.1 are there any tools to take a column from a DB and do a frequency analysis - a breakdown of the values for this column? Possibly a histogram or a table saying out of 500 records I have one hundred and two "301" ninety-eight "212" values and three-hundred "410"? Is SQL the way to for this? Of course there'd be 1000's of values.... I'm not asking about connecting to the DB, just tools to collate and tally this sort of thing. Thanks, Lee G. From fabioztessitore at libero.it Fri Aug 3 04:42:45 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 03 Aug 2007 08:42:45 GMT Subject: Error with Tkinter and tkMessageBox References: <46af71b7$0$10619$4fafbaef@reader2.news.tin.it> <46b19caa$0$17951$4fafbaef@reader1.news.tin.it> <46b19fe4$0$17952$4fafbaef@reader1.news.tin.it> Message-ID: <46b2ea85$0$36452$4fafbaef@reader5.news.tin.it> Il Fri, 03 Aug 2007 12:38:09 +1000, John McMonagle ha scritto: > Fabio Z Tessitore wrote: >> I've tried to use Twm and SURPRISE! it works!!! >> >> Can you say why? How can I fix the prob with Gnome? >> >> Thanks > > I don't know why it doesn't work correctly on the version of gnome which > you are running (I run KDE). Perhaps the question needs to be posed to > a gnome group ? Thank you, very much, John. Best wishes. Bye From olsongt at verizon.net Mon Aug 13 12:01:15 2007 From: olsongt at verizon.net (olsongt at verizon.net) Date: Mon, 13 Aug 2007 09:01:15 -0700 Subject: ANN: Compyler 0.1 In-Reply-To: <46bf2ea3$0$240$e4fe514c@news.xs4all.nl> References: <46bf2ea3$0$240$e4fe514c@news.xs4all.nl> Message-ID: <1187020875.575423.58000@o61g2000hsh.googlegroups.com> > Grant Olson wrote: > > Compyler is a pre-alpha x86 native code compiler. > > In what ways is this similar or different to Shed Skin?http://mark.dufour.googlepages.com/ > > --Irmen I've never actually downloaded shedskin, but my understanding is that it: + does type inference for speed, but means you're working with a subset of python. + Generates C++ so you need an intermediate compiler (probably only an issue on windows) + Generates code via the AST. OTOH, compyler: + has the exact same semantics as compiler code. I was more concerned with this than performance payoffs. + generates .COFF files that are ready for linking. + Skips syntax tree processing and just assumes the default bytecode is a good enough starting point. I was going to say you couldn't make a .pyd in ShedSkin, but it looks like you can do that too. -Grant From dejanews at email.com Sun Aug 19 08:54:35 2007 From: dejanews at email.com (samwyse) Date: Sun, 19 Aug 2007 12:54:35 GMT Subject: 1)URL QueryString Parsing 2)Search Engine Spiders In-Reply-To: <1187513415.188232.187270@50g2000hsm.googlegroups.com> References: <1187513415.188232.187270@50g2000hsm.googlegroups.com> Message-ID: mosscliffe wrote: > I am trying to create a back link, equivalent to the browser back > action and I can not use java script. The target user does not allow > java script. > > I am using HTTP_REFERER. > > I need to add the original Query String values. > > Is there a way to get the QueryString element other than by using > cgi.FieldStorage, as I just want to return with the values that were > current in the calling page. > > gv.orgQueryString = "" > > gv.BackButton = ' gv.orgQueryString + '">BACK' I'm not sure I understand your problem. Does the above code not work? > Am I right in thinking Search Engine Spiders will never see my script > pages as they exist only for the duration of the python script's > execution ? And even then as they are xxx.py, they would not be > seen. Anyone who accesses your web server will see the pages that you serve. If you serve the xxx.py files, then they can be seen and indexed, otherwise they are invisible. From pavlovevidence at gmail.com Thu Aug 30 02:43:14 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 30 Aug 2007 02:43:14 -0400 Subject: We need PIGs :) References: Message-ID: <46d66ef1$0$18792$4c368faf@roadrunner.com> On Thu, 30 Aug 2007 07:10:47 +0200, Martin Marcher wrote: > My idea was to define "Python Implementation Guidelines" (PIGs) that > specify a problem formalize it enough so that implementations are > interchangeable (in this example create a module that has an > "authenticate(username, password)" method so that one could easily take > that module for any given app and then authenticate against postgres, > and also against my plaintext file (which was the original - quite > useless - implementation). > > Does that sound like a good idea or would that be over formalization? The Python community already did something for web applications (WSGI, I think). Not sure how well that's working out. Doing this kind of thing is not, of course, something that can be done in general for all problems. It would only help if there's enough demand for interoperability that developers make the effort to adhere to the guidelines (which are rarely ideal for any particular situation). Although there are some informal standards that Python programmers often observe (for example, the interface of file-like objects), there isn't too much demand to standardize them. I believe the Python language itself makes formal guidelines less helpful, because its dynamicism (among other things) makes is so good at interfacing. That is, if you have two pieces of code that don't work together, it's easy to connect them. Many people often call Python a good "glue" language for this reason. And when you have a good "glue" language, formal interface guidelines aren't so important. Carl Banks From beliavsky at aol.com Wed Aug 15 13:21:49 2007 From: beliavsky at aol.com (Beliavsky) Date: Wed, 15 Aug 2007 10:21:49 -0700 Subject: Python Book Recommendations In-Reply-To: References: <1b31ae500708141638w77614014o6f382d0389bc69df@mail.gmail.com> Message-ID: <1187198509.037033.79780@a39g2000hsc.googlegroups.com> On Aug 15, 10:47 am, "Shawn Milochik" wrote: > If I could have only one book, I would buy "Core Python, Second > Edition," by Wesley Chun. I have bought about half a dozen Python books but will purchase only Python 3 books in the future, when they become available. I wonder when that will be and if most of the current books will be revised to conform to Python 3. From bignose+hates-spam at benfinney.id.au Thu Aug 2 02:12:03 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 02 Aug 2007 16:12:03 +1000 Subject: Emacs + python References: <4vasi.139194$wG2.61677@newsfe17.lga> Message-ID: <87myxabh3g.fsf@benfinney.id.au> hg writes: > Are there any cscope & ECB equivalent for Python ? Can you describe these things, for those who don't have any experience of them but may know of an equivalent? -- \ "With Lisp or Forth, a master programmer has unlimited power | `\ and expressiveness. With Python, even a regular guy can reach | _o__) for the stars." -- Raymond Hettinger | Ben Finney From grante at visi.com Fri Aug 24 17:46:11 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 24 Aug 2007 21:46:11 -0000 Subject: py2exe/distutils: how to include a tree of files? References: <13cuhdr58m5one7@corp.supernews.com> Message-ID: <13cukd39lgsfgb4@corp.supernews.com> On 2007-08-24, Grant Edwards wrote: > I'm packaging up a python program and need to include an entire > directory tree in the distribution. I've cobbled together something using package_dir/package_data and os.path.walk(), but it seems like a bit of a kludge... -- Grant Edwards grante Yow! You mean you don't at want to watch WRESTLING visi.com from ATLANTA? From kyosohma at gmail.com Tue Aug 21 12:14:02 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 21 Aug 2007 09:14:02 -0700 Subject: How to optimise this code? In-Reply-To: References: Message-ID: <1187712842.807766.118430@i38g2000prf.googlegroups.com> On Aug 21, 10:59 am, "David N Montgomery" wrote: > class testCase: > def __init__(self, tc): > if tc == 1:self.testCase1() > if tc == 2:self.testCase2() > if tc == 3:self.testCase3() > if tc == 4:self.testCase4() > if tc == 5:self.testCase5() > if tc == 6:self.testCase6() > > def testCase1(self): > print "tc1" > > def testCase2(self): > print "tc2" > > def testCase3(self): > print "tc3" > > def testCase4(self): > print "tc4" > > def testCase5(self): > print "tc5" > > def testCase6(self): > print "tc6" > > def testCaseX(self): > print "tcX" > > totalNumberOfTestCases = 6 > x = 0 > while x <= totalNumberOfTestCases: > x += 1 > testCase(x) > > This template code is working, but I envisage having 100+ test cases and > am concerned about my useage of if statements. I would be grateful for > any pointers as to how I can run all tests cases, regardless of how > many, in a more efficient manner. > > Thank you in advance. You're code doesn't make sense to me. You create a class and then you call a method within the class without instantiating said class. What the!? Can't you just create a function? def testCase(x): print "tc%s" % x totalNumberOfTestCases = 6 x = 0 while x <= totalNumberOfTestCases: x += 1 testCase(x) Am I missing something? Mike From mclaugb at nospm.yahoo.com Tue Aug 7 12:07:12 2007 From: mclaugb at nospm.yahoo.com (mclaugb) Date: Tue, 7 Aug 2007 17:07:12 +0100 Subject: python system subprocess win32 References: <1186500091.063514.178640@e9g2000prf.googlegroups.com> Message-ID: At the moment, I cannot figure a way of running this precompiled "conv.exe" using commandline arguments. Thus, I need Python to call the program, wait until it loads up, then enter a known sequence of characters so that the function will run. The program conv.exe I call looks like this. -------------------------- Welcome to conv.exe This program was written by .... Please select from the following options: h- (help) r- (read) ...etc Enter your request: --------------------------------- I need Python to start the program, wait a second and then issue a few characters to the program. Hope this makes more sense! Bryan wrote in message news:1186500091.063514.178640 at e9g2000prf.googlegroups.com... > On Aug 7, 9:48 am, "mclaugb" wrote: >> Hello ALl, >> I have a compiled program "conv.exe" that works as follows:>>conv.exe >> >> ----------------------------- >> Please selection from the following options. press "h" for help, "p" for >> print, "r" for readfile. >> Enter your request now: >> ... >> -------------------- >> Is there a way to script python using the subprocess method to start this >> program "conv.exe" and then send a "r" to the command line to make it, >> say, >> readfile. >> >> I have tried the following but the .communicate("r) is not doing anything >> >> import subprocess >> import time >> >> a=subprocess.Popen("c:\\mcml\\conv.exe") >> time.sleep(1) >> (stdout, stderr) = a.communicate("r") >> >> Many thanks, >> Bryan > > Use the sys.argv method. In the code that you have compiled, put the > following lines in: > > > > import sys > default = sys.argv[1] > if default: > # check which option it is and run it appropriately > else: > # print your menu here > > > > Then you should be able to do the subprocess Popen command: > > subprocess.Popen("c:\\mcml\\conv.exe r") > > You may need to turn the shell on... > > subprocess.Popen("c:\\mcml\\conv.exe r", shell=True) > > Hopefully that gives you some ideas anyway. > > Mike > From steve at holdenweb.com Thu Aug 2 08:42:44 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 02 Aug 2007 08:42:44 -0400 Subject: Use variable in regular expression In-Reply-To: <1186051401.122847.114690@d55g2000hsg.googlegroups.com> References: <1186051401.122847.114690@d55g2000hsg.googlegroups.com> Message-ID: <46B1D144.8060108@holdenweb.com> CarpeSkium at gmail.com wrote: > I know I can use a variable in regular expressions. I want to use a > regex to find something based on the beginning of the string. I am > using yesterday's date to find all of my data from yesterday. > Yesterday's date is 20070731, and assigned to the variable > "yesterday_date". I want to loop thru a directory and find all of the > yesterday's data ONLY IF the feature class has the date at the > BEGINNING of the filename. > > Sample strings: > 20070731_test1 > Copy20070731_test1 > 20070731_test2 > Copy20070731_test2 > 20070731_test3 > Copy20070731_test3 > > I don't want the one's that start with "Copy". I can't figure out the > syntax of inserting the "^" into the regex. I've tried all of the > following, with no luck: > > re.compile(^yesterday_date) > re.compile(r'^yesterday_date') > re.compile(r'^[yesterday_date]') > re.compile(r'[^yesterday_date]') > > I don't know what I'm doing and I'm just guessing at this point. Can > anyone help? Thanks. > As is often the case, taking a larger look at the problem can reveal that Python has features that can help you without even getting down to more complex stuff. You appear to require a list of the files whose names begin with a string representation of yesterday's date. If you take a look at the glob module you will see that it has a glob() function, and if you were to call it as names = glob.glob(yesterday_date + "*") it would return a list of the names of the files you are interested in. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From aboudouvas at panafonet.gr Mon Aug 13 08:08:32 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Mon, 13 Aug 2007 05:08:32 -0700 Subject: Eclipse/PyDev question In-Reply-To: <1187005485.137101.43130@l70g2000hse.googlegroups.com> References: <1186998539.030727.279330@g4g2000hsf.googlegroups.com> <1187005485.137101.43130@l70g2000hse.googlegroups.com> Message-ID: <1187006912.494455.86830@w3g2000hsg.googlegroups.com> On Aug 13, 1:44 pm, ga... at dsdata.it wrote: > On Aug 13, 11:48 am, king kikapu wrote: > > > Hi, > > > i am using Eclipse (Platform Runtime binary) with PyDev and i was > > wondering if someone can help me with this: > > > 1. I set breakpoints to a .py file and i have told Eclipse to open the > > Debug perspective when it sees that some .py file(s) of my project > > indeed contains breakpoints. So, i press F9, Eclipse starts, Debug > > perspective opens and i can use the debugger just fine. But when the > > app terminates, how can i tell Eclipse to switch automatically to the > > PyDev perspective and not remain in the Debug one ? > > You don't, Eclipse keeps the same perspective because for what it > knows you might want to debug some more and it correctly avoids to > decide what is good for you. Switching to the debug perspective when > you issue a debug command is an exception to the normal switching of > perspectives with the respective big buttons and the menu. > If you wish to switch perspective to edit code before debugging again, > putting editors and appropriate accessory views in the debug > perspective might be good enough. > > > 2. Let's say we have a project that consists of some .py files. I want > > to press F9 when the editor displays anyone of these files but make > > Eclipse to run the whole project (that has another .py as "default") > > and not the script that i am currently working on, is that possible ?? > > Executing the current file is a bad habit, Eclipse remembers a list of > execution/debug configurations that can be selected from a dropdown > list in the toolbar and edited with a dialog box; after you setup > entry points for a project you can use and edit them as needed. > I'm using Eclipse for Java and my entry points include remote > debugging of a GUI application, about 6 JUnit tests, about 3 command > line tools with many complex parameter sets each, and some Ant builds; > it would take about one hour of trial and error to reconstruct the > command lines, classpaths and JVM options. I only run the current file > as a draft for an edited configuration. > > Regards, > Lorenzo Gatti Hey Lorenzo, thanks for the help! I understood that with the Debug perspective. Ok, i will, as currently, have to swtick manually to PyDev. But i cannot figgre out how i can tell Eclipse to run the whole Project and not the currently active script that i work on... From __peter__ at web.de Wed Aug 22 14:47:33 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Aug 2007 20:47:33 +0200 Subject: Problems with dynamic function creation. References: Message-ID: Steven W. Orr wrote: [snip mess] > Everything works just fine (that I know of) except Sometimes you have to just fix the code you have. This however doesn't just smell funny, it's hopeless. Start with clearly stating your goals and then do a rewrite. Should you need help again, remember post a self-contained example and an actual traceback. Peter From steve at holdenweb.com Mon Aug 13 06:48:57 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 13 Aug 2007 06:48:57 -0400 Subject: Module imports during object instantiation In-Reply-To: <4c3vo4-u7k.ln1@learner.hq.netapp.com> References: <4c3vo4-u7k.ln1@learner.hq.netapp.com> Message-ID: Ritesh Raj Sarraf wrote: > Hi, > > I've been very confused about why this doesn't work. I mean I don't see any > reason why this has been made not to work. > > class Log: > > def __init__(self, verbose, lock = None): > > if verbose is True: > self.VERBOSE = True > else: self.VERBOSE = False > Better: self.VERBOSE = verbose or, if you suspect verbose might pass in a mutable value, self.VERBOSE bool(verbose) > > if lock is None or lock != 1: > self.DispLock = False do you want to set self.lock here? IF so, a similar improvement could be made (though you would still need a test to create the lock object). > else: > self.DispLock = threading.Lock() > self.lock = True > > if os.name == 'posix': > self.platform = 'posix' > self.color = get_colors() > > elif os.name in ['nt', 'dos']: > self.platform = 'microsoft' > > try: > import SomeModule > except ImportError: > self.Set_Flag = None > > if self.Set_Flag is not None: > self.color = SomeModule.get_colors_windows() > > else: > self.platform = None > self.color = None > > When I create an object the "import" part never gets executed. Is there a > reason behind it ? > I mean I'd like to keep my class as independent as I want. So that when > later I need to use it somewhere else, I don't need to know if it depends > on any modules. > > Currently, the way I'm left is to globally go and import the module and set > a flag there. > What's leading you to conclude the import isn't being executed? You realise, I trust, that the module's code will only be executed on the first call to __init__()? You are right in assuming that __init__() is called once per instance created, and it's legitimate to make an import conditional in the way you have because of the "execute code only once" behavior - if the module is already in sys.modules then it won't be re-imported, the existing one will be used. Having said all that, I still don't see why you can't just put the try/except at the top level of your code and have color be a global. Why repeat the attempted import and the computation for each object you create? Alternatively, do it at the class level, so it's only executed once when the class is declared? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From kyosohma at gmail.com Wed Aug 29 09:25:23 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 29 Aug 2007 06:25:23 -0700 Subject: Pythonwin Install COM exceptions on Windows Vista Ultimate In-Reply-To: References: Message-ID: <1188393923.239537.20590@50g2000hsm.googlegroups.com> On Aug 28, 8:20 pm, "Sandipan News" wrote: > What do I do? Can't do without Python! > Any experience, advice, hope is welcome. > Thanks. > Sandipan You need to post the error traceback along with some more information so the community can help. Mike From sullivanz.pku at gmail.com Wed Aug 8 02:41:37 2007 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: Wed, 08 Aug 2007 06:41:37 -0000 Subject: Seek the one billionth line in a file containing 3 billion lines. In-Reply-To: <7xzm12o7o7.fsf@ruckus.brouhaha.com> References: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> <7xzm12o7o7.fsf@ruckus.brouhaha.com> Message-ID: <1186555297.877273.40540@o61g2000hsh.googlegroups.com> On Aug 8, 2:35 am, Paul Rubin wrote: > Sullivan WxPyQtKinter writes: > > This program: > > for i in range(1000000000): > > f.readline() > > is absolutely every slow.... > > There are two problems: > > 1) range(1000000000) builds a list of a billion elements in memory, > which is many gigabytes and probably thrashing your machine. > You want to use xrange instead of range, which builds an iterator > (i.e. something that uses just a small amount of memory, and > generates the values on the fly instead of precomputing a list). > > 2) f.readline() reads an entire line of input which (depending on > the nature of the log file) could also be of very large size. > If you're sure the log file contents are sensible (lines up to > several megabytes shouldn't cause a problem) then you can do it > that way, but otherwise you want to read fixed size units. Thank you for pointing out these two problem. I wrote this program just to say that how inefficient it is to use a seemingly NATIVE way to seek a such a big file. No other intention........ From arnau at ehas.org Wed Aug 8 15:35:12 2007 From: arnau at ehas.org (Arnau Sanchez) Date: Wed, 08 Aug 2007 21:35:12 +0200 Subject: Launch file from Python In-Reply-To: <1186594611.490723.251870@m37g2000prh.googlegroups.com> References: <1186594137.971393.128780@57g2000hsv.googlegroups.com> <1186594611.490723.251870@m37g2000prh.googlegroups.com> Message-ID: <46BA1AF0.8020302@ehas.org> kyosohma at gmail.com escribi?: > That's just the exit status or run status, if I recall correctly. I > think 0 (i.e. False) means it didn't run properly and anything else is > True, or ok. Something like that. The other way: 0 means "ok" while everything else means error (at least in UNIX). The reason is clear: there is usually only one way to do things well, but many to fail :-) > Technically speaking, you should > probably switch to using the subprocess module as it is replacing that > os module's functionality: http://www.python.org/doc/2.4/lib/module-subprocess.html Correct, subprocess replaces low-level os.system, os.popen*, os.spawn*, popen* functions. From andrew.sain at gmail.com Tue Aug 21 13:48:12 2007 From: andrew.sain at gmail.com (andrew.sain at gmail.com) Date: Tue, 21 Aug 2007 10:48:12 -0700 Subject: Submit Your Python Scripts Message-ID: <1187718492.549619.164440@w3g2000hsg.googlegroups.com> Hi, just wanted to invite any Python script authors to submit their Python script to our popular software site at http://www.myzips.com We have just today added a "Scripts" directory which includes a Python subdirectory http://www.myzips.com/category/Scripts/ The first submissions usually maintain a high position in our directories so the sooner you can get your script listed the more exposure you should be able to receive for your script. You can also submit PHP, AJAX, ASP, Ruby on Rails, CGI, Flash, Python, CFML, .NET, Java, XML and C/C++ scripts and coding. Thanks for your time, Andy From claird at lairds.us Wed Aug 8 16:23:45 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 8 Aug 2007 20:23:45 +0000 Subject: Issues of state (was: Tkinter or wxpython?) References: <7x8x8mpn37.fsf@ruckus.brouhaha.com> Message-ID: In article <7x8x8mpn37.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: . . . >I'm not sure what you're getting at in this context. You can write a >desktop app where the window system communicates with a gui toolkit >through a socket (at least that's how X windows works), or you can >write a web app where a browser communicates with an http listener >through a socket. What's the difference, as far as application state >is concerned? > >I haven't used wxpython but for tkinter you'd typically have a gui >event loop in its own thread, communicating with the application >through queues. Similarly you can use BaseHTTPServer to collect >browser hits and get the data out of them with the cgi module >functions before passing them to the app. If you want to handle >multiple concurrent users you get into the usual issues of web >servers, but if you're just doing a single user web implementation as >an alternative to a desktop gui, some rudimentary locking is probably >enough to stop accidental simultaneous connections. > >If the application is simple enough, you can just write it as a cgi >and keep the state in disk files. Others have answered this at other levels. In elementary terms, there truly is a difference, Paul, and one that's widely reified: a "desktop client-server" application typically listens through one socket, which therefore constitutes an index of the connection or client, while a Web application communicates through a sequence of independent HTTP transactions. The latter can manage state only to the extent it passes session information around. As you correctly point out, there certainly are plenty of Web appli- cations which cheerfully *do* pass session information. As common as it is, though--and I'm *still* writing CGI on occasion, a decade after I was convinced it was a dead technique--it's not automatic. HTTP is a stateless protocol, and therefore state management must remain an issue. From kyosohma at gmail.com Wed Aug 29 11:32:35 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 29 Aug 2007 08:32:35 -0700 Subject: What's the difference ? In-Reply-To: <1i3ljx0.et1tyg1lxph4nN%aleax@mac.com> References: <1188394767.333396.129020@r29g2000hsg.googlegroups.com> <1188396199.136398.321900@r34g2000hsd.googlegroups.com> <1i3ljx0.et1tyg1lxph4nN%aleax@mac.com> Message-ID: <1188401555.590025.175330@o80g2000hse.googlegroups.com> On Aug 29, 9:44 am, al... at mac.com (Alex Martelli) wrote: > wrote: > > ... > > > Weird. Hetland's book, "Beginning Python" states that it's a matter of > > taste. > > If your taste is for more verbose AND slower notation without any > compensating advantage, sure. > > > Martelli's "Python Cookbook 2nd Ed." says to use the get() > > method instead as you never know if a key is in the dict. However, I > > can't seem to find any reference to has_key in his book. > > .get is not a direct alternative to ``in'' (it's an alternative to an > idiom where you key into the dict if the key is present and otherwise > supply a default value, and it's MUCH better in that case). has_key is > probably not even mentioned in the Cookbook (2nd edition) since there is > never a good need for it in the Python versions it covers (2.2 and up), > but you can probably find traces in the 1st edition (which also covered > Python back to 1.5.2, where has_key *was* needed); the Nutshell (2nd ed) > mentions it briefly in a table on p. 60. > > > According to Chun in "Core Python Programming", has_key will be > > obsoleted in future versions of Python, so he recommends using "in" or > > "not in". > > Yes, we're removing has_key in Python 3.0 (whose first alpha will be out > reasonably soon, but is not going to be ready for production use for > quite a bit longer), among other redundant things that exist in 2.* only > for legacy and backwards compatibility reasons. This makes 3.0 simpler > (a little closer to the "only one obvious way" ideal). > > But you should use ``in'' and ``not in'' anyway, even if you don't care > about 3.* at all, because they only have advantages wrt has_key, without > any compensating disadvantage. > > Alex Martelli, I kind of figured .get wasn't a direct alternative to "in", but I thought the OP might be able to use it since (s)he didn't mention what they wanted to do. Mike From hide1713 at gmail.com Wed Aug 1 01:32:14 2007 From: hide1713 at gmail.com (hide1713 at gmail.com) Date: Wed, 01 Aug 2007 05:32:14 -0000 Subject: How does xmlrpc work ? Message-ID: <1185946334.436503.326920@x40g2000prg.googlegroups.com> Hi everyone I am working on a system which used XMLRPC to communicate between hundreds of computer. One administrative computer keeps hundreds of xmlrpc instance of other computers. I want to know if evey instance use a single connection and keep it alive forever OR create a new connection when a method is called and end it after the call is finished? Thank you From pavlovevidence at gmail.com Fri Aug 31 00:21:01 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 30 Aug 2007 21:21:01 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1i3o9kr.2gmni61g62moaN%aleax@mac.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> Message-ID: <1188534061.243009.89640@m37g2000prh.googlegroups.com> On Aug 30, 10:20 pm, al... at mac.com (Alex Martelli) wrote: > Russ wrote: > > ... > > > programs." Any idea how much Python is used for flight control systems > > in commercial > > transport aircraft or jet fighters? > > Are there differences in reliability requirements between the parts of > such control systems that run on aircraft themselves, and those that run > in airports' control towers? Yes. > Because Python *IS* used in the latter > case, cfr ... if > on-plane control SW requires hard-real-time response, Yes. > that might be a > more credible reason why Python would be inappropriate (any garbage > collected language is NOT a candidate for hard-real-time SW!) than your > implied aspersions against Python's reliability. Not really relevant, since there is no (or very little) dynamic memory allocation. Python really isn't suitable for in-flight controls for various reasons, and mission critical concerns is a minor one (systems with less underlying complexity tend to have fewer failure modes). But mostly it's raw throughput: Python is just too slow. Flight control computers have to be powerful enough make a ton of mathematical calculations in a matter of milliseconds, and under strict weight and power constraints. The cost of running 100 times slower than optimal is just too high. At my current project, we're struggling with throughput even though we use highly optimized code. Python would be completely out of the question. Now, control towers don't have these constraints, and system failure is not nearly as critical, so Python is a better option there. Carl Banks From martin at v.loewis.de Sun Aug 5 14:06:59 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 05 Aug 2007 20:06:59 +0200 Subject: Misleading wikipedia article on Python 3? In-Reply-To: <87bqdlswbn.fsf@pobox.com> References: <87bqdlswbn.fsf@pobox.com> Message-ID: <46b611c4$0$24872$9b622d9e@news.freenet.de> > I'm surprised to read this: > > http://en.wikipedia.org/wiki/Python_3 > > """Note that while there is no explicit requirement that code be able > to run unmodified in both versions, in practice it is quite likely for > most code. As of January 2007, it looks like most reasonable code > should run quite well under either branch.""" It's difficult to predict the future, but I think this statement is a fair description. > > I haven't been following Python 3 development recently. Have things > really changed that much? Last time I looked, e.g. dict.items() no > longer returned a list. Correct. > Seems unlikely that most code will run on 2 > and 3, in that case, Why that? Most reasonable code doesn't care what dict.items returns, as it reads like for k,v in dict.items(): do_something_with(k,v) > and IIUC Guido has said all along that not much > code will run on both. I think you misunderstood. It's not a design goal that code works without modifications, yet most reasonable code will even without that being an explicit goal. Regards, Martin From iansan at gmail.com Thu Aug 30 18:16:30 2007 From: iansan at gmail.com (IamIan) Date: Thu, 30 Aug 2007 22:16:30 -0000 Subject: Simple elementtree question In-Reply-To: <46D71A5E.1000005@web.de> References: <1188495178.701968.246690@50g2000hsm.googlegroups.com> <46D71A5E.1000005@web.de> Message-ID: <1188512190.384302.125730@m37g2000prh.googlegroups.com> Thank you very much! That did it. In the source XML tags have rdf:about attributes with the link to the story, and it was here I planned on grabbing the link and matching it up with the child text. After seeing the output of elmenttree's getiterator() though, it now looks like each item, title, description, and link is a separate element... I could use a dictionary or lists to match the first title to the first link, but is there a more elegant way in elementtree (or otherwise) to do this? Thanks again, Ian From rcdailey at gmail.com Mon Aug 20 15:51:02 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 20 Aug 2007 14:51:02 -0500 Subject: optparse - required options Message-ID: <496954360708201251r137dfaedqe632361891eae343@mail.gmail.com> Hi, I've been reading through the python documentation on the optparse module and I was unable to find out how to specify if an option is optional or required. The documentation vaguely states that actions can be used to do this, however I was not able to figure out how. If anyone could help I'd greatly appreciate it. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070820/64ab9e4d/attachment.html> From mail at timgolden.me.uk Fri Aug 31 06:19:31 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 31 Aug 2007 11:19:31 +0100 Subject: OT: pronounciation [was: list index()] In-Reply-To: <46D7E36D.4000301@timgolden.me.uk> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188497498.3468.60.camel@dot.uniqsys.com> <mailman.188.1188546300.28954.python-list@python.org> <0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net> <1188551958.728836.137370@x35g2000prf.googlegroups.com> <fOadnfwlCJbQfErbnZ2dnUVZ_jCdnZ2d@speakeasy.net> <46D7E36D.4000301@timgolden.me.uk> Message-ID: <46D7EB33.7030908@timgolden.me.uk> Tim Golden wrote: > Erik Max Francis wrote: >> Paddy wrote: >> >>> I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll >>> and role similarly. >>> >>> My accent is probably from the East Midlands of the UK, but is not >>> pronounced. >> _Troll_ and _frolic_ aren't pronounced with the same "o" sound in any >> accent I've ever heard of. Which you pronounce _boat_ and _bot_ the >> same way, too? > > [Amusingly contemplating a trolling war about the pronunciation of "troll"] > > Well they sound the same in my more-or-less South London accent. > I can't write those funny phonetic symbols (and I hate to > imagine the Unicode encoding hoops I'd have to jump through > to make them readable anyway) but both "o"s sound short to me. > Like "bot" rather than "boat" using your example. Since we're talking... I'm still a little startled when I listen to some of the excellent webcasts that are being produced these days (showmedo.com and friends) and hear American voices pronounce Python... well, the way they do, with the stress and something of a drawl on the second syllable. I'm sure it's just as amusing the other way round: we pronounce it with the stress on the first syllable and the characteristic short vowel sound in the second. (Something like: Pie'thun). TJG From vijay.kumar.75in at gmail.com Mon Aug 20 02:41:46 2007 From: vijay.kumar.75in at gmail.com (vijay.kumar.75in at gmail.com) Date: 19 Aug 2007 23:41:46 -0700 Subject: best GUI library for vector drawing program In-Reply-To: <1187357244.883516.79840@j4g2000prf.googlegroups.com> References: <1187357244.883516.79840@j4g2000prf.googlegroups.com> Message-ID: <1187361616.270300.246480@e9g2000prf.googlegroups.com> Hi All, Today I have downloaded a SWT Software which is great to its features. You can learn many GUI details out of it. The basic functionality is it lists IP Addresses of the remote PC's your system is accessing. You may find the project under sourceforge.net http://sourceforge.net/projects/nettymaster You can customize this software, please let me know your views From http Fri Aug 31 01:07:47 2007 From: http (Paul Rubin) Date: 30 Aug 2007 22:07:47 -0700 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> <m2wsvc1g12.fsf@manolo-blahnik.bibliotech.com> Message-ID: <7xr6lk5m1o.fsf@ruckus.brouhaha.com> Robert Brown <bbrown at speakeasy.net> writes: > In any case, I'm still not sure whether it would be useful to integrate DbC > into Python. I guess I'm a little confused about what it would mean. Suppose you want to write a function that looks for a value using binary search in a sorted list, n = bsearch(a,x). The contract is: precondition: the input list a is sorted. postcondition: the output is an integer n, such that if x is an element of the list, then a[n] == x. If x is not in the list, then n is -1. This is a reasonable application of dbc since the precondition and postcondition are easy to specify and check, but the binary search algorithm is tricky enough to be susceptible to implementation errors. The trouble is, the obvious way to write the precondition and postcondition take linear time, while the binary search should take log(n) time. In the traditional unit test approach, that's ok, you'd run the test as part of the build process but not each time the function is actually called. With something like SPARK/Ada (and maybe Eiffel), you'd statically validate the conditions. But in Python, the check occurs at runtime unless you disable it, famously compared to wearing your parachute on the ground but taking it off once your plane is in the air. I guess one difference from unit test philosophy is that at least sometime, you'd run the entire application with all the dbc checks enabled, and just live with the slowdown. From nepbabucxspamfree at yahoo.ca Mon Aug 20 19:06:21 2007 From: nepbabucxspamfree at yahoo.ca (Bikal KC) Date: Tue, 21 Aug 2007 08:36:21 +0930 Subject: Xah's Edu Corner: Under the spell of Leibniz's dream In-Reply-To: <1187598193.118227.270460@19g2000hsx.googlegroups.com> References: <1187567809.896668.228650@z24g2000prh.googlegroups.com> <1187598193.118227.270460@19g2000hsx.googlegroups.com> Message-ID: <46ca1e65$1_3@news.chariot.net.au> Ingo Menger wrote: > On 20 Aug., 01:56, Xah Lee <x... at xahlee.org> wrote: > >> (for you math illiterates out there: ... >> (for you mathematicians out there: ... > > Please, Xah Lee, could you possibly stop to "explain" things that are > absolutely trivial? If somebody has doubts about the etymology of a > word, he may use the dictionary, or he could ask. > > I used usenet years ago then stopped for couple of years. I remember seeing him/her on c.l.perl I believe doing the same thing he/she is doing atm. I'd say the ultimate usenet superstar. Wow! From jmtulloss at gmail.com Fri Aug 10 19:17:52 2007 From: jmtulloss at gmail.com (Justin T.) Date: Fri, 10 Aug 2007 23:17:52 -0000 Subject: The Future of Python Threading In-Reply-To: <mailman.1838.1186767296.22759.python-list@python.org> References: <1186763839.203679.110810@z24g2000prh.googlegroups.com> <mailman.1838.1186767296.22759.python-list@python.org> Message-ID: <1186787872.040419.132630@g12g2000prg.googlegroups.com> On Aug 10, 10:34 am, Jean-Paul Calderone <exar... at divmod.com> wrote: > >I'm not an expert, but I understand that much. What greenlets do is > >force the programmer to think about concurrent programming. It doesn't > >force them to think about real threads, which is good, because a > >computer should take care of that for you.Greenlets are nice because > >they can run concurrently, but they don't have to. This means you can > >safely divide them up among many threads. You could not safely do this > >with just any old python program. > > There may be something to this. On the other hand, there's no _guarantee_ > that code written with greenlets will work with pre-emptive threading instead > of cooperative threading. There might be a tendency on the part of developers > to try to write code which will work with pre-emptive threading, but it's just > that - a mild pressure towards a particular behavior. That's not sufficient > to successfully write correct software (where "correct" in this context means > "works when used with pre-emptive threads", of course). Agreed. Stackless does include a preemptive mode, but if you don't use it, then you don't need to worry about locking at all. It would be quite tricky to get around this, but I don't think it's impossible. For instance, you could just automatically lock anything that was not a local variable. Or, if you required all tasklets in one object to run in one thread, then you would only have to auto-lock globals. > > One also needs to consider the tasks necessary to really get this integration > done. It won't change very much if you just add greenlets to the standard > library. For there to be real consequences for real programmers, you'd > probably want to replace all of the modules which do I/O (and maybe some > that do computationally intensive things) with versions implemented using > greenlets. Otherwise you end up with a pretty hard barrier between greenlets > and all existing software that will probably prevent most people from changing > how they program. If the framework exists to efficiently multi-thread python, I assume that the module maintainers will slowly migrate over if there is a performance benefit there. > > Then you have to worry about the other issues greenlets introduce, like > invisible context switches, which can make your code which _doesn't_ use > pre-emptive threading broken. Not breaking standard python code would definitely be priority #1 in an experiment like this. I think that by making the changes at the core we could achieve it. A standard program, after all, is just 1 giant tasklet. > > All in all, it seems like a wash to me. There probably isn't sufficient > evidence to answer the question definitively either way, though. And trying > to make it work is certainly one way to come up with such evidence. :) ::Sigh:: I honestly don't see myself having time to really do anything more than experiment with this. Perhaps I will try to do that though. Sometimes I do grow bored of my other projects. :) Justin From david at nospam.spam Tue Aug 21 04:10:37 2007 From: david at nospam.spam (david) Date: Tue, 21 Aug 2007 18:10:37 +1000 Subject: wxPython before MainLoop In-Reply-To: <6a6dnfbbFJNzcCbbnZ2dnUVZ_oudnZ2d@comcast.com> References: <13bl9a75laqcm70@corp.supernews.com> <6a6dnfbbFJNzcCbbnZ2dnUVZ_oudnZ2d@comcast.com> Message-ID: <13cl7ftdvac9ab2@corp.supernews.com> Thanks for that suggestion, and sorry I took so long to get back to you. That worked. Because I don't want the splash screen, just self.Update regards, [david] Heikki Toivonen wrote: > [david] wrote: >> I'd like to refresh the display before I start the main loop. > > We have this kind of situation in Chandler, where we display and update > the splash screen before we enter MainLoop. > > 1. Create app object > http://lxr.osafoundation.org/source/chandler/Chandler.py#080 > > 2. During app object creation, in OnInit, put up splash screen and update it > > http://lxr.osafoundation.org/source/chandler/application/Application.py#433 > > 3. The splash screen refresh is basically: draw new stuff, > self.Layout(), self.Update(), wx.Yield() > http://lxr.osafoundation.org/source/chandler/application/Application.py#1421 > > 3. Start MainLoop > http://lxr.osafoundation.org/source/chandler/Chandler.py#086 > From igorr at ifi.uio.no Wed Aug 22 04:12:32 2007 From: igorr at ifi.uio.no (Igor V. Rafienko) Date: 22 Aug 2007 10:12:32 +0200 Subject: non-blocking communication with imaplib Message-ID: <xjv8x84dm33.fsf@oinn.ifi.uio.no> Hi, I was wondering if anyone had a suggestion for the following issue. I would like to talk to an IMAP-server, imaplib being the tool of choice, of course. Unfortunately it may happen that the IMAP-server fails to respond to certain commands, and I would like to be able to detect that within a given time period (on the scale of 5-10 seconds). Initially, I thought about playing with setsockblocking() for the communication socket in the imaplib.IMAP4 object. However, the IMAP4 object uses a file object ("created from" the said socket), and the underlying socket must be blocking according to [1]. Is there another option for detecting when the server fails to reply within a given time slot? Could I perhaps temporarily set the socket to non-blocking mode? Or maybe I am attacking this problem the wrong way altogether? Any hints would be greatly appreciated. TIA, ivr [1] <http://docs.python.org/lib/socket-objects.html#l2h-3693> -- <+Kaptein-Dah> igorr: for f? parenteser <+Kaptein-Dah> igorr: parenteser virker som lubrication under iterasjon <+Kaptein-Dah> igorr: velkjent From larry.bates at websafe.com Wed Aug 15 16:02:13 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 15 Aug 2007 15:02:13 -0500 Subject: Who told str() to round my int()'s!!! In-Reply-To: <mailman.1857.1186861157.22759.python-list@python.org> References: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> <9qmvi.47364$s5.1537219@phobos.telenet-ops.be> <mailman.1857.1186861157.22759.python-list@python.org> Message-ID: <3ZudnUuJ68lcxl7bnZ2dnUVZ_t_inZ2d@comcast.com> Steve Holden wrote: > Roel Schroeven wrote: >> Adam W. schreef: >>> After a fair amount of troubleshooting of why my lists were coming >>> back a handful of digits short, and the last digit rounded off, I >>> determined the str() function was to blame: >>> >>>>>> foonum >>> 0.0071299720384678782 >>>>>> str(foonum) >>> '0.00712997203847' >>> >>> Why in the world does str() have any business rounding my numbers, and >>> how do I get around this? >> >> You could use repr() instead of str() (AFAIK that's what the >> interactive interpreter used to print your foonum), but in any case >> you should be aware of the limits inherent in floating point >> arithmetic and in conversions between decimal and binary fractions. >> See e.g. http://docs.python.org/tut/node16.html >> >> > I should also point out that the subject line for this thread is > inaccurate, as it wasn't rounding ints at all. > > regards > Steve What are they teaching in schools these days? I see questions like this and the equally perplexing "why don't floats represent numbers exactly?" or the mildy amusing "how do I write bytes not characters to a file" questions at least once a week on this forum. -Larry From arkanes at gmail.com Wed Aug 1 12:59:35 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 1 Aug 2007 11:59:35 -0500 Subject: Awkward format string In-Reply-To: <1185986578.527619.314310@e9g2000prf.googlegroups.com> References: <1185984697.605529.157110@g12g2000prg.googlegroups.com> <mailman.1440.1185985928.22759.python-list@python.org> <1185986578.527619.314310@e9g2000prf.googlegroups.com> Message-ID: <4866bea60708010959j789902anf27b33f46fcf8236@mail.gmail.com> On 8/1/07, beginner <zyzhu2000 at gmail.com> wrote: > On Aug 1, 11:31 am, "Chris Mellon" <arka... at gmail.com> wrote: > > On 8/1/07, beginner <zyzhu2... at gmail.com> wrote: > > > > > Hi, > > > > > In order to print out the contents of a list, sometimes I have to use > > > very awkward constructions. For example, I have to convert the > > > datetime.datetime type to string first, construct a new list, and then > > > send it to print. The following is an example. > > > > > x=(e[0].strftime("%Y-%m-%d"), e[1].strftime("%Y-%m-%d"))+e[2:] > > > print >>f, "%s\t%s\t%d\t%f\t%f\t%f\t%d" % x > > > > > e is a tuple. x is my new tuple. > > > > > Does anyone know better ways of handling this? > > > > You seem to be doing quite complicated things with your magical e > > tuple. Do you have some specific aversion to classes? > > e is not complicated. It is a record that have 7 fields. In my program > a function outputs a list of tuples, each is of type e, and now I just > need to send them to a text file. > > I have no problem using classes and I do use them everywhere. But > using classes does not solve my problem here. I will probably find > myself doing: > > print >>f, "%s\t%s\t%d\t%f\t%f\t%f\t%d" % (x.field1..strftime("%Y-%m- > %d"), x.field2..strftime("%Y-%m-%d"), x.field3, x.field4, x.field5, > x.field.6, x.field7) > > This is also tedious and error-prone. > If you ever need to write this more than once you're doing it wrong. I'm not sure what's "tedious and error prone" about specifying the format of your data file. From rcdailey at gmail.com Wed Aug 22 14:17:44 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 22 Aug 2007 13:17:44 -0500 Subject: Class destruction Message-ID: <496954360708221117pd7465fr838a24b167a1dcdd@mail.gmail.com> Hi, I'm wondering where the most appropriate location is to cleanup class objects. For example, i have a file handle as an instance attribute in one of my classes and I need to call f.close() on it when the class object falls out of scope. Any ideas? I've tried __del__() but I don't remember this working for some reason. I might try it again later just to be positive. Below is the source code to the class I'm attempting to add a destructor to: import struct ######################################################### class fout: def __init__( self, filename ): self._file = open( filename, "wb" ) def write32( self, data ): # write out a 32-bit integer value self._file.write( struct.pack( "I", data ) ) def write16( self, data ): # write out a 16-bit integer value self._file.write( struct.pack( "H", data ) ) def write8( self, data ): # write out an 8-bit integer value self._file.write( struct.pack( "B", data ) ) def write( self, data ): # write out a string literal self.write32( len( data ) ) self._file.write( data ) self._file.flush() -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070822/8f4fb741/attachment.html> From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Aug 19 08:37:23 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 19 Aug 2007 14:37:23 +0200 Subject: Development for dual core machine References: <1187515287.226791.186700@j4g2000prf.googlegroups.com> Message-ID: <5iqrs3F3qanv6U2@mid.individual.net> Andy wrote: > I'm going to develop a software package that includes a web server > (and PHP code) , a database, and some Python code of course. I am > being strongly suggested to make it to work on a dual- or > multi-core computer, No problem. CPython will work on any dual core CPU. > but I'm confused on how to take advantage of the multiple CPUs. First: Use a web server that can make use of multiple cores. Second: Use a data base that can make use of multiple cores. Third, for using multiple cores from CPython: this is an FAQ, please look at the mailing list archives. Whether you should optimize your python application to use all cores strongly depends on what your Python application actually does. > From what I read, I think that simply by making the package run in > several separate processes (web server, database server, Python > interpreter, etc.), and/or using multiple threads (which I will > anyway) the package should be able to use multiple CPUs. CPython has the GIL (global interpreter lock). Please search for it in the archives, it's been discussed exhaustingly. > And how is it decided which process and which threads go to CPU 1, > CPU 2, etc.? Perhaps the BIOS? No, the kernel (i. e., Linux). The BIOS is completely out of this. Regards, Bj?rn -- BOFH excuse #388: Bad user karma. From fuzzyman at gmail.com Wed Aug 1 21:09:41 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: Thu, 02 Aug 2007 01:09:41 -0000 Subject: Wing IDE for Python v. 3.0 beta1 released In-Reply-To: <mailman.1475.1186015988.22759.python-list@python.org> References: <46AF8ED7.2070206@wingware.com> <20070801212840.GA25065@spookie1.spookiegate> <mailman.1475.1186015988.22759.python-list@python.org> Message-ID: <1186016981.502313.268700@r34g2000hsd.googlegroups.com> On Aug 2, 1:46 am, "Greg Donald" <gdon... at gmail.com> wrote: > On 8/1/07, John K Masters <johnmast... at oxtedonline.net> wrote: > > > If their support for paid customers is anything like their support for > > prospective customers then I would leave well alone. > > I had no problems with their support whatsoever, really good in my > opinion. They were very responsive and addressed all my questions > over about a 3 or 4 day email conversation. > > -- > Greg Donaldhttp://destiney.com/ I'll third that. I have had excellent and extended support from the Wing guys. Definitely recommended. Fuzzyman http://www.voidspace.org.uk/python/articles.shtml From wolf_tracks at invalid.com Wed Aug 22 20:36:00 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 23 Aug 2007 00:36:00 GMT Subject: What Are These Import/From Statements about? In-Reply-To: <mailman.137.1187815545.32294.python-list@python.org> References: <un_yi.34471$2v1.24183@newssvr14.news.prodigy.net> <mailman.123.1187804723.32294.python-list@python.org> <qb0zi.47332$Um6.34487@newssvr12.news.prodigy.net> <mailman.137.1187815545.32294.python-list@python.org> Message-ID: <QD4zi.47346$Um6.28801@newssvr12.news.prodigy.net> Thanks very much. Where's the global index? Matt McCredie wrote: >> While that's an interesting link, I was thinking of the named items like: >> Numeric, (this one I know about.) >> Image >> ImageChops >> ImageTk >> time >> binascii >> tkMessageBox >> tkSimpleDialog > > The `image' ones are all part of PIL (Python Imaging Library) which is > a third party module (http://www.pythonware.com/products/pil/). The > others: time, binascii, os.path, tkMessageBox and tkSimpleDialog are > all part of the standard library > (http://docs.python.org/modindex.html). I don't see the documentation > for the tk* ones in the global module index, but you can always look > at the source. I'm not sure what MakeQTE is. If this is a program you > are able to run, you should be able to do something like this: > >>>> import MakeQTE >>>> print MakeQTE.__file__ > > That will show you where it lives, and you can then look at the source > for more clues. > > Also, you should be able to do this: > >>>> import MakeQTE >>>> help(MakeQTE) > > Which will also likely give you some good clues. > > -Matt -- Wayne Watson (Nevada City, CA) Web Page: <speckledwithStars.net> From steve at holdenweb.com Thu Aug 16 23:23:13 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 16 Aug 2007 23:23:13 -0400 Subject: why psyco using more memery in liunx? In-Reply-To: <005d01c7e078$c13d0ed0$811ba8c0@kyom> References: <005d01c7e078$c13d0ed0$811ba8c0@kyom> Message-ID: <46C514A1.9060503@holdenweb.com> kyo guan wrote: > Hi all: > > When you import psyco in python2.5, you can see the memery grow up near 40MB in linux. but the same version python and > psyco, is only grow up 1MB under windows. > Please don't repeat the question again. It *has* reached the list. Patience is a virtue ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From fabioztessitore at libero.it Fri Aug 3 16:59:52 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 03 Aug 2007 20:59:52 GMT Subject: Global package variable, is it possible? References: <1186160415.065108.139160@e9g2000prf.googlegroups.com> <46b36b31$0$10622$4fafbaef@reader2.news.tin.it> <mailman.1581.1186165038.22759.python-list@python.org> Message-ID: <46b39748$0$17945$4fafbaef@reader1.news.tin.it> Il Fri, 03 Aug 2007 14:16:59 -0400, Carsten Haese ha scritto: > Right idea, wrong execution. Note that the OP said "I'd like to be able > to reload the config file dynamically and have all my modules > automatically receive the new config." You are obviously right ... I haven't read all the post, sorry! Only for knowing more about modules: is there a way to dinamically reload an already imported module? bye Fabio From gherzig at fmed.uba.ar Tue Aug 28 18:51:50 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Tue, 28 Aug 2007 19:51:50 -0300 Subject: Is it reasonably easy easy to something like this with python? In-Reply-To: <1188335743.394160.254680@x35g2000prf.googlegroups.com> References: <1188326947.527698.245770@r23g2000prd.googlegroups.com> <mailman.78.1188327771.28954.python-list@python.org> <1188335743.394160.254680@x35g2000prf.googlegroups.com> Message-ID: <46D4A706.3090804@fmed.uba.ar> walterbyrd wrote: >On Aug 28, 1:31 pm, Gerardo Herzig <gher... at fmed.uba.ar> wrote: > > >>walterbyrd wrote: >> >> > > > >>The one who make that table sorteable is AJAX. Not php. The php part is >>kind of trivial (so it would be `trivial' in python too). It just reads >>some data and format it in an html table. >> >> > > >Thank you, that is great to know. What if there were 1000 records, and >the table was paginated? I suppose, ajax would sort the front end, and >backend language, and database, would soft behind the scene, or >something? > > > Im not an AJAX expert (not even close actually. In fact i just used it once), but seems like you will have to reload all the page (all the table at least). Because now is a different scenario. If the table is paginated, it looks like you will send, say 50 results at one time, then (when pressing 'next 50'), anhoter 50, and so on. So AJAX only will have THOSE 50 for ordering. Another approach would be returning de entire recordset, and implement all the 'next' and 'previous' links via AJAX. And i dont think you will like to send the entire result. I dont. What will i do (at least from WIK for now), is having a set of `hrefs' (maybe with some nice arrows) in all of the table headers, to indicate the desired order you want to get. And, if you have a column table named 'age', you will make those href like '<a href=showmethetable.py?columnorder=age&ordertype=asc><nice_arrow_graphic>' then your cgi python script will take that mess after the ? sign, parse it (via cgi module perhaps), and make a new query, with the 'order by age asc' clause, wich are the 'arguments' in the url. There is allways a lot of ways to do some stuff. I will check into de AJAX list too! Cheers. Gerardo From QJing.Li at gmail.com Mon Aug 20 01:53:18 2007 From: QJing.Li at gmail.com (math2life) Date: Mon, 20 Aug 2007 05:53:18 -0000 Subject: Call for advice on how to start PyOpenGL! Message-ID: <1187589198.616866.280500@j4g2000prf.googlegroups.com> I work with python for two years, are familiar with image processing, but beginner on PyOpenGL and OpenGL. Any advice appreciated! From steve at holdenweb.com Thu Aug 30 20:19:13 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Aug 2007 20:19:13 -0400 Subject: wx.DirDialog defaultPath In-Reply-To: <4BFBA39857A02A4D9C92496D7E14001901D2E5CE@blackhole.voicesignal.com> References: <4BFBA39857A02A4D9C92496D7E14001901D2E5CE@blackhole.voicesignal.com> Message-ID: <fb7mq6$t93$1@sea.gmane.org> Woo, Daniel wrote: > Is there some kind of parsing/checking that is done on the defaultPath? > The path I would like to set as default is something like this: > > ?c:\Somedirectory\engineering\somedirectory?. When providing this as > the default, the control seems to think it is an invalid path, although > it IS a valid path under Windows. I?m pretty sure this is because two > directories in the hierarchy have the same name. Since it believes this > is an invalid path, the dialog opens up browsing in the root directory. > I can successfully set the default to other directories, nested as deep > as I want and it works as expected. > > Anyway around this? > I think you need to revise your hypothesis about what's wrong with your program. There's no reason why it shouldn't be able to cope with a path that has a duplicate directory name at different levels. It's *much* more likely that you aren't correctly escaping the back-quotes in your path. See http://www.ferg.org/projects/python_gotchas.html#contents_item_2 for an explanation. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From tjreedy at udel.edu Wed Aug 8 17:07:30 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 8 Aug 2007 17:07:30 -0400 Subject: Seek the one billionth line in a file containing 3 billion lines. References: <1186554220.272488.134780@d55g2000hsg.googlegroups.com><46b977e9$0$27390$ba4acef3@news.orange.fr> <5htl5qF3md0abU1@mid.uni-berlin.de> Message-ID: <f9dbah$tfn$1@sea.gmane.org> "Marc 'BlackJack' Rintsch" <bj_666 at gmx.net> wrote in message news:5htl5qF3md0abU1 at mid.uni-berlin.de... | On Wed, 08 Aug 2007 09:54:26 +0200, M?ta-MCI \(MVP\) wrote: | | > Create a "index" (a file with 3,453,299,000 tuples : | > line_number + start_byte) ; this file has fix-length lines. | > slow, OK, but once. | | Why storing the line number? The first start offset is for the first | line, the second start offset for the second line and so on. Somewhat ironically, given that the OP's problem stems from variable line lengths, this requires that the offsets by fixed length. On a true 64-bit OS (not Win64, apparently) with 64-bit ints that would work great. From gherzig at fmed.uba.ar Fri Aug 17 12:15:42 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Fri, 17 Aug 2007 13:15:42 -0300 Subject: advice about `correct' use of decorator In-Reply-To: <740c3aec0708170529s6f7e7fe2l8c92771c2d0a51d4@mail.gmail.com> References: <46C4B097.4080309@fmed.uba.ar> <740c3aec0708170529s6f7e7fe2l8c92771c2d0a51d4@mail.gmail.com> Message-ID: <46C5C9AE.5020508@fmed.uba.ar> BJ?rn Lindqvist wrote: >On 8/16/07, Gerardo Herzig <gherzig at fmed.uba.ar> wrote: > > >>@is_logued_in >>def change_pass(): >> bla >> bla >> >>And so on for all the other functions who needs that the user is still >>loged in. >> >>where obviosly the is_logued_in() function will determine if the dude is >>still loged in, and THEN execute change_pass(). If the dude is not loged >>in, change_pass() is NOT executed at all. Instead, it will be redirected >>to the `login' screen. >> >> > >I think this is redundant use of a decorator. You can achieve the >exact same effect by writing: > >def is_logued_in(): > if not user.is_logged_in(): > raise NotLoggedInError > >It costs you one more line, but reduces complexity. And if you are >worried about that extra line you can put it in a function. > > > As far as i know (by the way, AFAK is the shortcut?, and BTW means `by the way'? ), decorators are not indispensable. I mean, all that you can do with python, you can doit without decorators. And from my point of view, this hides the complexity for the other developers of my group, since all they have to do is add the @is_logged_in line at the top of the cgi script, and not to worrie about exceptions, not even how the decorator is implemented (i may log the error in some file). All they have to know is that any abnormal situation will redirect to the `login' screen. Thank you for your comments! Gerardo From joetech at aapt.net.au Mon Aug 27 05:53:28 2007 From: joetech at aapt.net.au (Raptor) Date: Mon, 27 Aug 2007 19:53:28 +1000 Subject: Let's Unite Against Jews and Mongrels! References: <1188198797.772672.60840@r29g2000hsg.googlegroups.com> Message-ID: <fau6t4$e10$1@news-01.bur.connect.com.au> ra ra ra ra ra rara ra ra ra you're so irrelevant man!!!!!!! "Nenad Milicevic - The Aryan Serb" <i_hate_jews at shiftmail.com> wrote in message news:1188198797.772672.60840 at r29g2000hsg.googlegroups.com... > Rise up and shine, white sons and daughters > Rise up and shine, you gotta fight to part those waters > When we swim in the light, all will be okay > The black, yellow and brown man will wash away. > ------------------------------ > Let's break the chains of Jewish and black domination! Unite, white > brothers and sisters, and let's defeat those who oppress our white > heritage! > > Our skin is our uniform! > > > Serbian Committee for Aryan Defence > Nenad Milicevic, executive > Usenet name: Raoul Endymion or Raul Endymion > ICQ 208030128 > endymion at deadspam.com > endimion at myrealbox.com > Belgrade, Serbia > From arkanes at gmail.com Thu Aug 2 12:34:27 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 2 Aug 2007 11:34:27 -0500 Subject: wxpython with python 2.5 In-Reply-To: <4a7f84ac0708020924v73dee05eq76d10507e3c2cad5@mail.gmail.com> References: <4a7f84ac0708020924v73dee05eq76d10507e3c2cad5@mail.gmail.com> Message-ID: <4866bea60708020934r2b5a7be6l2ddc931342728e62@mail.gmail.com> On 8/2/07, G <gggg.iiiii at gmail.com> wrote: > Hello, > > > I am trying to get wxpython to run with python 2.5 without any success. > wx works prefectly in python 2.4. below is the error code i get when i try > to run the code. > File "demo.py", line 3, in <module> > import Main > File "/tmp/wxPython/Main.py", line 32, in <module> > import wx # This module uses the new wx namespace > ImportError: No module named wx > > Any help in getting wxpython to run in 2.5 would be greatly appreciated. > Download the python 2.5 package. From ldo at geek-central.gen.new_zealand Tue Aug 28 01:11:32 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 28 Aug 2007 17:11:32 +1200 Subject: Chaining programs with pipe References: <1187734166.384152.178040@o80g2000hse.googlegroups.com> <13cnbi87neru8c3@corp.supernews.com> <mailman.97.1187757319.32294.python-list@python.org> <13cogr3n6no937b@corp.supernews.com> <1187795716.083417.299540@q4g2000prc.googlegroups.com> <fau28j$gle$3@lust.ihug.co.nz> <mailman.51.1188274035.28954.python-list@python.org> Message-ID: <fb0alf$hgr$3@lust.ihug.co.nz> In message <mailman.51.1188274035.28954.python-list at python.org>, Gabriel Genellina wrote: > En Mon, 27 Aug 2007 05:35:51 -0300, Lawrence D'Oliveiro > <ldo at geek-central.gen.new_zealand> escribi?: > >> In message <1187795716.083417.299540 at q4g2000prc.googlegroups.com>, >> Gabriel Genellina wrote: >> >>> On 22 ago, 11:08, Grant Edwards <gra... at visi.com> wrote: >>> >>>> but I'm a Unix guy who occasionally tries >>>> to ship a Windows version of a Python app: the concept of a >>>> process defaulting to having a stderr or stdout that wasn't >>>> writable was utterly foreign to me. >>> >>> Ah, that explains your previous post telling that things on Windows >>> don't work as they "should". They work, but not necesarily as a >>> "foreigner" would expect. >> >> So what's the good reason for Windows having unusable defaults for stderr >> and stdout, then? > > You should ask the wxPython/wxWidgets guys why they choose to do things > that way. But I assumed you knew, since you were the one who used to term "foreigner" to describe Grant Edwards' mystification at why things worked this way. So in fact you are equally a "foreigner" to the way Windows works? > Tk programs don't have that problem, by example: you have a GUI > *and* a console, if you want. A simple print statement with no console > just goes into void space - no error, no crash, no GPF... > You get what you ask for: if you pass /SUBSYSTEM:WINDOWS as an option to > the linker (or put equivalent flags in the executable) you don't get a > console by default. That's fine for most GUI programs that don't use > stdout/stderr. If you want a console, create one using AllocConsole. But why should I need to do that? On Unix/Linux systems, there is no distinction between "GUI" and "non-GUI" programs--_all_ processes can (and usually do) have stdin, stdout and stderr. stderr is particularly important for GUI programs, so the desktop environment typically captures this to a file, commonly called ".xsession-errors". This is very useful when things go wrong (programs crash etc), to see what error messages were reported. Copying text messages from a file is somewhat easier than trying to capture them from a screenshot. From bgoldenberg at gmail.com Mon Aug 13 01:17:40 2007 From: bgoldenberg at gmail.com (Benjamin Goldenberg) Date: Mon, 13 Aug 2007 05:17:40 -0000 Subject: Querying Graphics Card Name In-Reply-To: <slrnfbuqq7.52s.grahn+nntp@frailea.sa.invalid> References: <1186686984.160312.175270@i13g2000prf.googlegroups.com> <5i1f4cF3mbqqdU1@mid.individual.net> <1186696734.059152.131080@d30g2000prg.googlegroups.com> <slrnfbuqq7.52s.grahn+nntp@frailea.sa.invalid> Message-ID: <1186982260.661135.293580@x40g2000prg.googlegroups.com> On Aug 12, 2:18 pm, Jorgen Grahn <grahn+n... at snipabacken.dyndns.org> wrote: > On Thu, 09 Aug 2007 21:58:54 -0000, Benjamin Goldenberg <bgoldenb... at gmail.com> wrote: > > On Aug 9, 3:26 pm, Bjoern Schliessmann <usenet- > > mail-0306.20.chr0n... at spamgourmet.com> wrote: > >> Benjamin Goldenberg wrote: > >> > I would like to find out the name of the graphics card of the > >> > machine my program is running on. I have looked into the pyopengl > >> > module, and using them to query the card, but it seems like there > >> > ought to be a simpler way to find this out without setting up a > >> > glcontext. Does anyone have any ideas? > > >> You could execute glxinfo and look for the renderer string. If > >> that's sharp enough for your purpose. Another option is lspci. > > > I should have clarified. I would like a cross platform implementation, > > Windows and *nix. It doesn't seem as if glxinfo is available under > > Windows, at least not without installing X11 under cygwin. If > > necessary, I can write the *nix and Windows queries separately. > > Yeah, but ... > - what if there isn't one? > - what if there are several? > - what if there *is* one, but your user is sitting by a remote machine, > not using the card at all? > > Your method will, no matter how you choose, fail sooner or later, > so you'd better plan for that. > > What is your reason to do this, by the way? Remember what Homer > Simpson said: if something appears to be hard, it is simply not worth > doing. And I mean that semi-seriously. These are for some internal automation scripts for the company I work for. We do development for specific graphics cards, all of which are OpenGL 2.0 compatible. In order to automate aspects of our building and testing systems, we need to know which graphics card the software is being built on. Hopefully, that makes some sense. -Benjamin From claird at lairds.us Mon Aug 13 07:04:17 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 13 Aug 2007 11:04:17 +0000 Subject: Process Control Help References: <1185808072.695752.20720@z28g2000prd.googlegroups.com> <mailman.1393.1185913913.22759.python-list@python.org> <1185923367.122846.117750@x40g2000prg.googlegroups.com> Message-ID: <heq5p4-29v.ln1@lairds.us> In article <1185923367.122846.117750 at x40g2000prg.googlegroups.com>, Azazello <tylerca at jeld-wen.com> wrote: >On Jul 31, 12:45 pm, Walt Leipold <leip... at ace-net.com> wrote: . . . >> It has nothing to do with 'proprietary issues'. A lot of it has to do >> with the perception of support -- who will support Python and custom >> Python code if my plant shuts down? Who will train my developers and >> operators? Who can I sue? The rest of it is because of the way the . . . >> You *might* save on development time (although I wouldn't bet on it), >> but you'll lose on testing time. Heck, you'll even lose because you >> have to document your stuff and train people to use it -- what happens >> to your custom system if you get hit by a bus? . . . >> Yes, it's a shame that you have to buy three packages to perform three >> functions, and then buy other 3rd-party packages to tie them together. >> Yes, it's a shame that industrial software is expensive, and >> proprietary, and Windows-only, and generally has a brain-dead scripting >> language (when it has any scriptability at all). Still, as much as it >> galls me to say it, if your company's primary business isn't writing >> industrial automation software, don't write industrial automation >> software. . . . >> * Unless you're a hobbyist, if you want to do data acquisition or i/o, >> purchase an i/o server for your particular bus/instrumentation from a >> major manufacturer. You *can* write your own i/o server, especially for >> simple protocols like Modbus, but the commercial versions have been >> tested more exhaustively than you can manage. Also, the most common >> protocol these days is OPC, which isn't a protocol at all in the >> conventional sense -- it's a set of APIs to a Windows DLL, with the >> wire-level details completely opaque -- so you'd have to buy a library >> for that anyway. >> >> * Unless you're a hobbyist, if you want an HMI, purchase LabView or >> InTouch or RSView or whatever, and use their tools to draw and >> 'configure' your screens. (Where 'configure' generally means 'program >> in Visual Basic or some other brain-dead language', but we try not to >> say "program" -- customers and underwriters *hate* "custom" software.) >> >> I personally think it's a tragedy that every manufacturer bases its HMI >> on Visual Basic for Applications rather than a better (and free and Open >> Source!) language like Python. It's also a tragedy that the dominant >> i/o 'protocol' for industrial automation isn't really a protocol, and is >> Windows-only to boot. It's horrifying that the primary means of >> communication between process control and data acquisition applications >> is via DDE or ActiveX. And I find it incredible that people and >> companies will pay large sums of money for some of the industrial >> automation products on the market. But that's the way the industry >> works, and, as frustrating as the commercial offerings are, using them >> will probably be better for you and your company in the long run. . . . >I really appreciate your post Walt. I started this thread last week >and I have to admit that in the subsequent days the 'option' of using >Python for our control solutions is simply not feasible. Although the >project I wanted to implement was fairly small scale, no 20 ton pieces >or x-ray machinery, the principle of the matter remains the same, >especially as a large corporation. As an intern returning to school >in the fall, the underlying responsibility for a Python system was my >original concern and discouragement to my employer for persuing this >path. It became readily apparent that using the crumby software >packaged with our control devices is surely faster in the long run, as >we are not involved in software development. (The majority of my >coworkers' formal programming experience is in FORTRAN) It has been a >very discouraging few days. There's so much room for improvement and >yet... My 4-day conclusion is unless you're already involved in >controls software you must be crazy to join. Are many young engineers >entering this field? > At an anecdotal level, I'd guess that, no, there are few young engineers entering this field. Mr. Leipold's descriptions of the difficulties involved in use of Python are accurate, and I particularly support his advice to use whatever commercial I/O you can find. I've had success, though, introducing high-level language programming, and even Linux, as an alternative to vendors' APIs, Labview, and so on. I'm not sure how to summarize what went into this; perhaps the best is to emphasize how flawed is the software that's typical with vendor APIs. While there's more to tell about the errors in commercial networking implementations, the horror of ActiveX, and so on, right now isn't the time for me to detail it all. From rcdailey at gmail.com Mon Aug 13 19:10:53 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 13 Aug 2007 18:10:53 -0500 Subject: Problem with Thread.join() Message-ID: <496954360708131610i62c0a63aneb7c39d23a052ac0@mail.gmail.com> Hi, I have a class that derives from threading.Thread. To signal the thread to exit its infinite loop, I set an Event. Once the thread checks Event.isSet() and it is true, it proceeds to break out of the loop and exit the function. In the main thread, right after calling Event.set(), I call Thread.join() to wait on the thread to exit. However, if I call Thread.join() the application locks up because for some reason calling Thread.join() prevents the thread from exiting. I don't know why. Any help? Thanks... -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070813/e8ea1686/attachment.html> From kyosohma at gmail.com Fri Aug 10 09:10:39 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 10 Aug 2007 06:10:39 -0700 Subject: wxPython before MainLoop In-Reply-To: <13bnh5bs4b9h427@corp.supernews.com> References: <13bl9a75laqcm70@corp.supernews.com> <13bnh5bs4b9h427@corp.supernews.com> Message-ID: <1186751439.697068.306770@q3g2000prf.googlegroups.com> On Aug 9, 8:51 pm, "[david]" <da... at nospam.spam> wrote: > I'm disappointed that I didn't get a wxPython solution. > > If the only way to get wxPython to correctly handle > this simple task is to code around it, I don't think > wxPython is really ready for Windows. > > Is there a better place to ask? > > Regarding the suggestions: > > Bjoern, you're wrong. The GUI needs to be displayed > for the user to analyse. A delay between display and > readiness is much better than a delay before display > or a delay with the GUI half-drawn. > > Mike, the screen does display correctly, it's just > that in Windows, screen updates are not processed > while the application is busy. > > 7Stud, that's a solution. Unless anyone comes up > with a direct solution, I guess I'll have to do that. > > [david] > > [david] wrote: > > I'd like to refresh the display before I start the main loop. > > > I have code like this: > > > app = App() > > app.Show() > > app.long_slow_init() > > app.MainLoop() > > > The main frame partly loads at Show, but because the mainloop has not > > started yet, the display does not update until long_slow_init() finishes. > > > Alternatively, I could code > > > app = App() > > app.long_slow_init() > > app.Show() > > app.MainLoop() > > > Which would give me a crisp Show, but there would be a long slow wait > > before the app showed any activity at all. I would need a splash screen. > > > I'd rather not have a splash screen (and I don't know how anyway). I'd > > like to just make app.Show() finish correctly before running > > long_slow_init. > > > Is there a wx internal method that I can use to give Windows the > > opportunity to finish painting the frame before I run long_slow_init()? > > > Or is there a better idea? > > > (david) Chris is right. The only way to interact with a gui is with a separate thread, otherwise you're blocking the gui's mainloop thread. That's why I gave that link. That's how to do it in every GUI I'm aware of. Mike From pavlovevidence at gmail.com Thu Aug 2 22:28:31 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 03 Aug 2007 02:28:31 -0000 Subject: __call__ considered harmful or indispensable? In-Reply-To: <mailman.1527.1186079415.22759.python-list@python.org> References: <mailman.1527.1186079415.22759.python-list@python.org> Message-ID: <1186108111.619578.41550@e9g2000prf.googlegroups.com> On Aug 2, 2:30 pm, s... at pobox.com wrote: > I'm wondering, are there some general cases where __call__ methods of > a user-defined class are simply indispensable? Indispensable's a strong word, but one thing that entails calling syntax, and can't (reasonably) be done with closures is to override a base class's __call__ method. There is one notable type in Python that defines __call__ and that you might want to subclass, namely type itself. So using __call__ is indispensible for some metaclasses. Here's my little example. I'm sure people could work out ways to do it without __call__ or even a metaclass, but I doubt it'd be so concise and out of the way as this: class CachedResourceMetaclass(type): def __init__(self,name,bases,clsdict): super(CachedResourceMetaclass,self).__init__(name,bases,clsdict) self._cache = {} self._releasefunc = self.release def decref(obj): obj._refcount -= 1 if obj._refcount <= 0: del self._cache[obj._key] obj._releasefunc() self.release = decref def __call__(self,*args): obj = self._cache.get(args) if obj is not None: obj._refcount += 1 else: obj = super(CachedResourceMetaclass,self).__call__(*args) obj._key = args obj._refcount = 1 self._cache[args] = obj return obj Carl Banks From bjourne at gmail.com Fri Aug 17 08:29:46 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Fri, 17 Aug 2007 14:29:46 +0200 Subject: advice about `correct' use of decorator In-Reply-To: <46C4B097.4080309@fmed.uba.ar> References: <46C4B097.4080309@fmed.uba.ar> Message-ID: <740c3aec0708170529s6f7e7fe2l8c92771c2d0a51d4@mail.gmail.com> On 8/16/07, Gerardo Herzig <gherzig at fmed.uba.ar> wrote: > @is_logued_in > def change_pass(): > bla > bla > > And so on for all the other functions who needs that the user is still > loged in. > > where obviosly the is_logued_in() function will determine if the dude is > still loged in, and THEN execute change_pass(). If the dude is not loged > in, change_pass() is NOT executed at all. Instead, it will be redirected > to the `login' screen. I think this is redundant use of a decorator. You can achieve the exact same effect by writing: def is_logued_in(): if not user.is_logged_in(): raise NotLoggedInError It costs you one more line, but reduces complexity. And if you are worried about that extra line you can put it in a function. -- mvh Bj?rn From eggie5 at gmail.com Fri Aug 10 14:46:03 2007 From: eggie5 at gmail.com (eggie5) Date: Fri, 10 Aug 2007 18:46:03 -0000 Subject: beginner whitespace question In-Reply-To: <HQSui.32716$2v1.16515@newssvr14.news.prodigy.net> References: <1186703261.136506.208660@x35g2000prf.googlegroups.com> <1186703525.591462.122140@m37g2000prh.googlegroups.com> <1186704161.334597.218750@z24g2000prh.googlegroups.com> <1186707164.095766.243480@q3g2000prf.googlegroups.com> <1186708404.901323.204730@g12g2000prg.googlegroups.com> <f9gf03$3al$1@daisy.noc.ucla.edu> <1186716319.025828.93780@g12g2000prg.googlegroups.com> <HQSui.32716$2v1.16515@newssvr14.news.prodigy.net> Message-ID: <1186771563.549959.324470@q4g2000prc.googlegroups.com> On Aug 9, 10:37 pm, James Stroud <jstr... at mbi.ucla.edu> wrote: > Dan Bishop wrote: > >> Tabs are for tables, hence the name. "Use spaces for space and use tabs > >> for tables" can be a little mnemonic to help you remember the rules. We > >> can make a little song together if you can think of some things that > >> rhyme with "don't" and "use" and "tabs". > > > "won't" > > > "blues", "booze", "bruise", "choose", "cruise", "fuse", "hues", > > "Jews", "lose", "muse", "news", "snooze", "views", etc. > > > "abs", "cabs", "crabs", "dabs", "grabs", "labs", "scabs", "slabs", > > "stabs", etc. > > When you want to screw your whitespace--don't! > Take this little pledge and I know you won't: > > When I was in school I would take of booze > While my typing teacher said I'm free to use > Space or formfeed or even tabs > And I punched so hard with my pinkie that scabs > Covered my Jake and Elwood tatoos. > (You didn't see that one coming did yous?) I'm so confused, I have no idea what's going on... From mhearne808 at gmail.com Thu Aug 30 19:18:09 2007 From: mhearne808 at gmail.com (mhearne808[insert-at-sign-here]gmail[insert-dot-here]com) Date: Thu, 30 Aug 2007 16:18:09 -0700 Subject: fcntl problems In-Reply-To: <1188512377.441241.107900@q4g2000prc.googlegroups.com> References: <1188512377.441241.107900@q4g2000prc.googlegroups.com> Message-ID: <1188515889.352267.220790@q5g2000prf.googlegroups.com> On Aug 30, 4:19 pm, "mhearne808[insert-at-sign-here]gmail[insert-dot- here]com" <mhearne... at gmail.com> wrote: > I'm having a number of problems with the fcntl module. First off, my > system info: > > Mac OS X > Darwin igskcicglthearn.cr.usgs.gov 8.10.1 Darwin Kernel Version > 8.10.1: Wed May 23 16:33:00 PDT 2007; root:xnu-792.22.5~1/RELEASE_I386 > i386 i386 > Python 2.5.1 (built from source) > > OK, the weirdness: > > First of all, if I try this: > file = open("counter.txt","w+") > fcntl.flock(file.fileno(), fcntl.LOCK_NB) > > I get this: > --------------------------------------------------------------------------- > <type 'exceptions.IOError'> Traceback (most recent call > last) > /Users/mhearne/src/python/<ipython console> in <module>() > <type 'exceptions.IOError'>: [Errno 9] Bad file descriptor > > However, if I try this: > fcntl.flock(file.fileno(), fcntl.LOCK_EX) > > I get no errors. > > Proceeding forward with the locked file, let's say I do the above in > Python interactive Process A. Then in python interactive Process B, I > repeat the "open" function on the same file with the same > permissions. Then, in each process, I write some text to the file > using the write() method. After closing the file in both processes, > the only text I see in the file is from Process B! > > According to my Python Cookbook: > "Exclusive lock: This denies all _other_ processes both read and write > access to the file." > > I seem to be experiencing the reverse of that description. Is this my > lack of understanding, or have I discovered a bug? > > Thanks, > > Mike I've been doing some experiments, and here are some specific examples to try. I'll designate the two interactive python processes as PA and PB. Both processes were started in the same directory. Here goes: PA: import fcntl PA: f = open("foo.txt","w+") PA: fcntl.flock(f.fileno(),fcntl.LOCK_EX) PA: f.write("text1\n") PB: f = open("foo.txt","w+") PB: f.write("text2\n") PA: f.close() PB: f.close() contents of foo.txt are: text2 Second experiment: PA: f = open("foo.txt","w+") PA: fcntl.flock(f.fileno(),fcntl.LOCK_EX) PB: f = open("foo.txt","w+") PA: f.write("text1\n") PB: f.write("text2\n") PA: f.write("text3\n") PB: f.close() PA: f.write("text4\n") PA: f.close() contents of foo.txt are: text1 text3 text4 Third experiment: PA: f = open("foo.txt","w+") PA: fcntl.flock(f.fileno(),fcntl.LOCK_EX) PA: f.write("text1\n") PB: f = open("foo.txt","w+") PB: f.write("text2\n") PB: f.close() PA: f.close() contents of foo.txt are: text1 Fourth experiment: PA: f = open("foo.txt","w+") PA: f.write("text1\n") PB: f = open("foo.txt","w+") PB: f.write("text2\n") PB: f.close() PA: f.close() contents of foo.txt are: text1 >From these last two experiments I can only conclude that file locking isn't doing a durned thing. What's going on? --Mike From david at asdf.asdf Fri Aug 24 04:31:43 2007 From: david at asdf.asdf (bambam) Date: Fri, 24 Aug 2007 18:31:43 +1000 Subject: beginner, idomatic python 2 References: <13csjmeaoqh9le3@corp.supernews.com> <46ce8d0c$0$410$426a74cc@news.free.fr> Message-ID: <13ct5rfc3n5ug48@corp.supernews.com> > trying to be "idiomatic" ...I hope that if a python programmer looks at my code it won't be an excuse to discard it. Less of an issue with Python than with C/C++, but since I'm just starting... def device(DeviceType): if DeviceType=='PSP': return Psp() elif DeviceType=="Power Supply" return Pwr() What about the parameter "DeviceType"? Also, I see what you mean now, DEVICE_DICT is upper case because it is a 'constant' -- I'd missed that point. Steve. "Bruno Desthuilliers" <bruno.42.desthuilliers at wtf.websiteburo.oops.com> wrote in message news:46ce8d0c$0$410$426a74cc at news.free.fr... > bambam a ?crit : >> Would someone like to suggest a replacement for this? This is a >> function that returns different kinds of similar objects, depending >> on what is asked for. PSP and PWR are classes. I don't really >> want to re-write the calling code very much: I'm just wondering >> if the function can be replaced with some kind of OOP pattern. > > Dan already answered to this. Just as a side note, and since you're trying > to be "idiomatic", Python's naming convention is to use all_lower for > functions, MixedCaps for classes (except - mostly for historical reasons - > the builtin types...), and ALL_LOWER for symbolic (pseudo) constants. > > >> def Device(DeviceType): >> if DeviceType=='PSP': >> return PSP() >> elif DeviceType=="Power Supply" >> return PWR() >> etc... >> >> >> Thanks! From ldo at geek-central.gen.new_zealand Thu Aug 30 20:54:57 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 31 Aug 2007 12:54:57 +1200 Subject: Python doesn't see the directories I create References: <ldvBi.293202$LE1.92748@newsfe13.lga> <46d6856b$0$17674$426a74cc@news.free.fr> <mailman.133.1188471584.28954.python-list@python.org> <46d6a72c$0$20532$426a74cc@news.free.fr> <mailman.134.1188473377.28954.python-list@python.org> <5jns3vFdmbcU6@mid.uni-berlin.de> Message-ID: <fb7ood$jb7$1@lust.ihug.co.nz> In message <5jns3vFdmbcU6 at mid.uni-berlin.de>, Marc 'BlackJack' Rintsch wrote: > Even on Unix it shouldn't be a problem on most file systems to create a > directory named 'C:' Except that some commands (e.g. scp, rsync) will interpret the colon as delimiting a host name. Also remember that, unless you write it "/C:", it's only going to be interpreted relative to your current working directory. From skawaii at gmail.com Mon Aug 27 14:54:30 2007 From: skawaii at gmail.com (skawaii at gmail.com) Date: Mon, 27 Aug 2007 18:54:30 -0000 Subject: [PyQt] Help on resizing a custom widget Message-ID: <1188240870.457859.207670@57g2000hsv.googlegroups.com> Ok, here's what's going on. I've just created a custom widget. it works great. I'm having some trouble, however, figuring out how to allow the said widget to resize. For example, when I throw the widget into a new dialog (using Qt Designer), I want to be able to drag it larger/smaller and have widget expand/shrink to that size. Right now, I can drag the widget bigger/smaller all I want, but it doesn't actually change size. I'm pretty new to PyQt (and therefore, Qt), so I'm pretty sure that the answer is a property that needs to be set somewhere. I'm just not sure which one. So you know, I'm using Python 2.4.3 and PyQt 3.1.6. Any help and suggestions would be appreciated. Thanks. From rcdailey at gmail.com Fri Aug 17 15:11:54 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 17 Aug 2007 14:11:54 -0500 Subject: Problem with directory recursion! In-Reply-To: <496954360708171119g66564ecas3134aed0b3916f8@mail.gmail.com> References: <496954360708171116t4370c2ddra3d7905bc956c7eb@mail.gmail.com> <496954360708171119g66564ecas3134aed0b3916f8@mail.gmail.com> Message-ID: <496954360708171211t74a19a8j636ffb7a0f272d77@mail.gmail.com> I figured it out. I was doing a recursive function call when I didn't have to. The walk() method already walks into every possible sub-directory for you! On 8/17/07, Robert Dailey <rcdailey at gmail.com> wrote: > > Here's part of the output that's incorrect: > > models\W_BoomerEdge > BYOS_C.entity.xml > BYOS_C_Collision.entity.xml > > Notice that the file BYOS_C.entity.xml is showing up as a file in the > directory W_BoomerEdge. This file does not exist in this folder, but yet in > a different folder. The output is consistent with the 'print' statements you > will see in the function I posted earlier. > > On 8/17/07, Robert Dailey <rcdailey at gmail.com> wrote: > > > > Hi, > > > > I've created a function that is used to recurse a directory tree in > > Windows XP using os.walk(). For the most part it works, however in some > > instances the data is incorrect and I'm getting invalid sub-directory paths. > > Here's the function: > > > > > > def __doSearch( root_dir, sub_path, restype, ext ): > > print sub_path > > # Searches the specified directory and generates a > > # list of files to preload. > > complete_path = osp.normpath( osp.join( root_dir, sub_path ) ) > > for root, dirs, files in os.walk( complete_path ): > > > > # Record the list of file hash ID's > > for file in files: > > split = __resType( file ) > > if split[1] == restype: > > # print sub_path > > print "\t", file > > __appendResource( ext, sub_path, split[0] ) > > > > # Remove .svn subdirectories; we don't walk these. > > if ".svn" in dirs: > > dirs.remove( ".svn" ) > > > > # Recurse child directories > > for dir in dirs: > > __doSearch( root_dir, osp.join( sub_path, dir ), restype, > > ext ) > > > > Does anyone see anything immediately suspicious about the code? I'm > > assuming that in Python, every time a function is called recursively it gets > > its own copy of local variables. For some reason the sub_path variable isn't > > consistent depending on where I use it. For example, if you notice the print > > call at the very start of the function, it will output something like > > "models/ships". However, after passing it into __appendResource(), it > > appears to be just "models". > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070817/5795ae66/attachment.html> From michele.simionato at gmail.com Tue Aug 21 09:35:58 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 21 Aug 2007 13:35:58 -0000 Subject: restoring the default completer in IPython Message-ID: <1187703358.454773.72960@50g2000hsm.googlegroups.com> This should probably go to the IPython list, but since I am not subscribed I will try my luck here. Basically, I want to embed IPython inside a command line interpreter based on cmd.Cmd, in this way: import cmd, IPython class Cmd(cmd.Cmd): def do_ipython(self, arg): ipython = IPython.Shell.IPShellEmbed() ipython(global_ns=globals()) def do_EOF(self, arg): return 1 Cmd().cmdloop() It works, however when I exit from the IPython shell (after giving the ipython command) the Cmd class is still using the IPython readline completer, not the original one. By looking at the source code of IPShellEmbed I see that there is a method .restore_system_completer() which is called, but it seems to be not working. I am probably doing something wrong, can somebody knowledgeable on IPython internals share some light on that? TIA, Michele Simionato From hniksic at xemacs.org Tue Aug 21 10:28:19 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 21 Aug 2007 16:28:19 +0200 Subject: python 2.5.1 segfault, multithreading & dual core issue? References: <46caf049$0$239$e4fe514c@news.xs4all.nl> Message-ID: <87r6lxx8qk.fsf@mulj.homelinux.net> Paul Sijben <paul.sijben at xs4all.nl> writes: > I am running a multi-threaded python application in a dual core > intel running Ubuntu. [...] Judging from the stack trace, this patch has a good chance of fixing your problem: http://mail.python.org/pipermail/python-dev/2007-August/074232.html From paddy3118 at googlemail.com Mon Aug 20 12:52:34 2007 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 20 Aug 2007 16:52:34 -0000 Subject: yet another indentation proposal In-Reply-To: <1i335jn.g5ymo519vckxfN%aleax@mac.com> References: <fEZxi.8855$9W6.6492@fe103.usenetserver.com> <1187538922.849174.94870@19g2000hsx.googlegroups.com> <1i335jn.g5ymo519vckxfN%aleax@mac.com> Message-ID: <1187628754.033003.113900@22g2000hsm.googlegroups.com> On Aug 19, 5:22 pm, al... at mac.com (Alex Martelli) wrote: > Paddy <paddy3... at googlemail.com> wrote: > > ... > > > Can screen reaaderss be customized? > > Open-source ones surely can (e.g., NVDA is an open-source reader for > Windows written in Python, <http://www.nvda-project.org/> -- alas, if > you search for NVDA Google appears to be totally convinced you mean > NVidia instead, making searches pretty useless, sigh). > > > Maybe their is a way to get the screen reader to say indent and dedent > > at thee appropriate places? > > There definitely should be. > > > Or maybe a filter to put those wordds into the source? > > .../Tools/scripts/pindent.py (comes with the Python source distribution, > and I hope that, like the whole Tools directory, it would also come with > any sensible packaged Python distribution) should already be sufficient > for this particular task. The "indent" always happens (in correct > Python sources) on the next line after one ending with a colon; > pindent.py can add or remove "block-closing comments" at each dedent > (e.g., "# end for" if the dedent is terminating a for-statement), and > can adjust the indentation to make it correct if given a Python source > with such block-closing comments but messed-up indentation. > > Alex Aaron, here's the comment at the beginning of the script. Would it work for you? # This file contains a class and a main program that perform three # related (though complimentary) formatting operations on Python # programs. When called as "pindent -c", it takes a valid Python # program as input and outputs a version augmented with block-closing # comments. When called as "pindent -d", it assumes its input is a # Python program with block-closing comments and outputs a commentless # version. When called as "pindent -r" it assumes its input is a # Python program with block-closing comments but with its indentation # messed up, and outputs a properly indented version. # A "block-closing comment" is a comment of the form '# end <keyword>' # where <keyword> is the keyword that opened the block. If the # opening keyword is 'def' or 'class', the function or class name may # be repeated in the block-closing comment as well. Here is an # example of a program fully augmented with block-closing comments: # def foobar(a, b): # if a == b: # a = a+1 # elif a < b: # b = b-1 # if b > a: a = a-1 # # end if # else: # print 'oops!' # # end if # # end def foobar # Note that only the last part of an if...elif...else... block needs a # block-closing comment; the same is true for other compound # statements (e.g. try...except). Also note that "short-form" blocks # like the second 'if' in the example must be closed as well; # otherwise the 'else' in the example would be ambiguous (remember # that indentation is not significant when interpreting block-closing # comments). # The operations are idempotent (i.e. applied to their own output # they yield an identical result). Running first "pindent -c" and # then "pindent -r" on a valid Python program produces a program that # is semantically identical to the input (though its indentation may # be different). Running "pindent -e" on that output produces a # program that only differs from the original in indentation. # Other options: # -s stepsize: set the indentation step size (default 8) # -t tabsize : set the number of spaces a tab character is worth (default 8) # -e : expand TABs into spaces # file ... : input file(s) (default standard input) # The results always go to standard output # Caveats: # - comments ending in a backslash will be mistaken for continued lines # - continuations using backslash are always left unchanged # - continuations inside parentheses are not extra indented by -r # but must be indented for -c to work correctly (this breaks # idempotency!) # - continued lines inside triple-quoted strings are totally garbled # Secret feature: # - On input, a block may also be closed with an "end statement" -- # this is a block-closing comment without the '#' sign. # Possible improvements: # - check syntax based on transitions in 'next' table # - better error reporting # - better error recovery # - check identifier after class/def # The following wishes need a more complete tokenization of the source: # - Don't get fooled by comments ending in backslash # - reindent continuation lines indicated by backslash # - handle continuation lines inside parentheses/braces/brackets # - handle triple quoted strings spanning lines # - realign comments # - optionally do much more thorough reformatting, a la C indent -Paddy From jcd at sdf.lonestar.org Fri Aug 24 09:31:39 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 24 Aug 2007 09:31:39 -0400 Subject: creating a tar file with python In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> Message-ID: <46CEDDBB.7000806@sdf.lonestar.org> Brian McCann wrote: > Hi, > > I'm trying to create a tar file of the contents of the current directory > > right now there is only one file "text.xml" in the current dir, I'm > using"." current dir as source > but that gives syntax error > > any help would be greatly appreciated > --Brian > > > #!/usr/bin/python > import string > import os > import sys > import time > import errno > import shutil > import tarfile > > > tar = tarfile.open(.,"test.tar.gz", "w:gz) > Over the course of this thread, I found the following variations on one line of code. Original problem code: tar = tarfile.open(.,"test.tar.gz", "w:gz) (missing quotes around arg[0], and at the end of arg[2]) SH's First solution: tar = tarfile(".", "test.tar.gz", "w:gz") (quotes around everything, and tarfile.open() becomes tarfile()) OP's attempt at implementing 1st solution: tar = tarfile.open(".","test.tar.gz",w:gz) (now the quotes are entirely missing around arg[2]) SH's concatenation into file what\ I\ wrote: tar = tarfile(".", "test.tar.gz", w:gz") (suddenly the quotes are missing from the beginning of arg[2]) Result from SH's diff: > tar = tarfile(".", "test.tar.gz", "w:gz") (the quotes have magically returned). Then the conversation devolves into grouchiness on both sides, until JM steps in with an entirely new solution. Sheesh. Both of y'all needed to pay more attention to detail. This is *one* line of code folks. Better yet, get a decent editor that will do syntax highlighting, so you don't need to pay attention. If quotes don't close, you need to know that. Train yourself so that looking for unclosed quotes, parens, brackets, etc. becomes second nature. And make sure you quote ALL strings. Some languages are forgiving on this count. Python is not. Blessings to all, and may all find their good cheer restored by some rest. I offer you both a virtual pint. You seem like you could use it. Cheers, Cliff -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070824/847d9836/attachment.html> From kar1107 at gmail.com Wed Aug 1 19:10:05 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Wed, 01 Aug 2007 16:10:05 -0700 Subject: split a string of space separated substrings - elegant solution? In-Reply-To: <46B03940.8020105@igpm.rwth-aachen.de> References: <46af9beb$0$14242$ba620e4c@news.skynet.be> <1185941803.577841.178550@l70g2000hse.googlegroups.com> <46B03940.8020105@igpm.rwth-aachen.de> Message-ID: <1186009805.678439.298450@i13g2000prf.googlegroups.com> On Aug 1, 12:41 am, Helmut Jarausch <jarau... at igpm.rwth-aachen.de> wrote: > Many thanks to all of you! > It's amazing how many elegant solutions there are in Python. Here is yet another solution. pexpect.split_command_line() >From the documentation: split_command_line(command_line) This splits a command line into a list of arguments. It splits arguments on spaces, but handles embedded quotes, doublequotes, and escaped characters. It's impossible to do this with a regular expression, so I wrote a little state machine to parse the command line. http://pexpect.sourceforge.net/pexpect.html But I am surprised to see there is a standard module already doing this (shlex) Karthik > > -- > Helmut Jarausch > > Lehrstuhl fuer Numerische Mathematik > RWTH - Aachen University > D 52056 Aachen, Germany From edreamleo at charter.net Fri Aug 10 12:04:47 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 10 Aug 2007 11:04:47 -0500 Subject: Leo 4.4.4 beta 1 released Message-ID: <Q00vi.5$Kb1.3@newsfe06.lga> Leo 4.4.4 beta is available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.4: ---------------------------- - A threading_colorizer plugin replaces the __jEdit_colorizer__ plugin. This plugin features much better performance. - Support for @auto nodes. Such nodes allow people to collaborate using Leo without inserting Leo sentinels in the files Leo generates. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at yahoo.com Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Aug 9 10:00:24 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 09 Aug 2007 16:00:24 +0200 Subject: Stackless Integration In-Reply-To: <mailman.1786.1186660119.22759.python-list@python.org> References: <mailman.1786.1186660119.22759.python-list@python.org> Message-ID: <46bb1df0$0$403$426a74cc@news.free.fr> Jean-Paul Calderone a ?crit : > On Thu, 09 Aug 2007 09:00:27 -0000, "Justin T." <jmtulloss at gmail.com> > wrote: >> Hi, >> >> I've been looking at stackless python a little bit, and it's awesome. >> My question is, why hasn't it been integrated into the upstream python >> tree? Does it cause problems with the current C-extensions? It seems >> like if something is fully compatible and better, then it would be >> adopted. However, it hasn't been in what appears to be 7 years of >> existence, so I assume there's a reason. > > It's not Pythonic. Hum... Yes ? Really ? Care to argument ? From grante at visi.com Thu Aug 23 13:53:07 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 23 Aug 2007 17:53:07 -0000 Subject: Socket recv(1) seems to block instead of returning end of file. References: <mailman.164.1187862959.32294.python-list@python.org> <pan.2007.08.23.16.48.52.958428@datallegro.com> Message-ID: <13cric35jcjp336@corp.supernews.com> On 2007-08-23, Dan Stromberg - Datallegro <dstromberg at datallegro.com> wrote: > Are you using sock.settimeout()? Hey, somebody snuck timeouts into the socket module when I wasn't looking... > I agree with Grant though - posting a minimal snippet of code that > replicates the problem would help us help you. In fact, it might help you > help yourself :) Yup, in my experience attempting to produce a minimally failing example will usually reveal what's wrong. -- Grant Edwards grante Yow! I have seen these EGG at EXTENDERS in my Supermarket visi.com ... I have read the INSTRUCTIONS ... From wescpy at gmail.com Thu Aug 23 11:27:24 2007 From: wescpy at gmail.com (wesley chun) Date: Thu, 23 Aug 2007 08:27:24 -0700 Subject: [ANN] Python courses this Fall In-Reply-To: <20070823.011932.12838.0@webmail31.lax.untd.com> References: <20070823.011932.12838.0@webmail31.lax.untd.com> Message-ID: <78b3a9580708230827sb171216l3a0eb8c96ff1f2ad@mail.gmail.com> $1295/pp for the intro course and $495/ for the 1-day course (but $395 if you take the intro course too). http://cyberwebconsulting.com (click "Python Training") for more details -wesley On 8/23/07, Jeff Pang <pangj at juno.com> wrote: > Sounds good.How about the costs for those lessons?thanks. > >> WEB: http://cyberwebconsulting.com (click "Python Training") >> See website for costs, venue info, and registration. Discounts are > available for multiple registrations as well as for teachers/students. From gherzig at fmed.uba.ar Thu Aug 16 15:58:55 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Thu, 16 Aug 2007 16:58:55 -0300 Subject: Help me!! In-Reply-To: <1187291279.545324.205610@i38g2000prf.googlegroups.com> References: <1187291279.545324.205610@i38g2000prf.googlegroups.com> Message-ID: <46C4AC7F.6000201@fmed.uba.ar> Anhoter HURRA for list comprehensions: >>> a = ['a', 'b', 'c', 'd'] >>> b = ['a','c'] >>> [x in b and x.upper() or x for x in a] ['A', 'b', 'C', 'd'] Is what you want? Cheers Gerardo >I'm trying to compare the list with another list and if it is there in >both I'm changing it to upper case and adding to another list and if >its not there in both I just want to add it to the global list (ie >files). >I'm able to do the first part but when I'm doing the second part the >files which are not there in both are getting repeatedly into the >global file. Some one help me so that >If ab = [a,b,c,d] >and cd = [a,c] >my global list file should be [A,b,C,d] > > > From wpdster at gmail.com Mon Aug 6 10:06:51 2007 From: wpdster at gmail.com (Patrick Doyle) Date: Mon, 6 Aug 2007 10:06:51 -0400 Subject: Importing * From a Package Message-ID: <e2a1d0aa0708060706p1f50d5c1j93b6cc3679522597@mail.gmail.com> Reading through the Python tutorial, I got to section 6.4.1, "Importing * From a Package", which states: "If __all__ is not defined, the statement from Sound.Effects import * does not import all submodules from the package Sound.Effects into the current namespace; ..." It then goes on to state: "[It] imports whatever names are defined in the package [including] any submodules of the package that were explicitly loaded by previous import statements." I am curious to learn the rationale for this behavior, since it just caught me by surprise (hence the reason I was pouring over the tutorial document in such detail :-)) Thus far, everything in Python has seemed very intuitive to me, however the behavior of "from package import *" baffles me. So I figured I'd ask -- why does Python behave this way. (And now, I'm going to do some code cleanup :-)) --wpd From kyosohma at gmail.com Thu Aug 30 15:07:02 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 30 Aug 2007 12:07:02 -0700 Subject: create Powerpoint via com In-Reply-To: <j7EBi.13372$Yg.7724@trnddc02> References: <j7EBi.13372$Yg.7724@trnddc02> Message-ID: <1188500822.869925.194430@e9g2000prf.googlegroups.com> Alan, On Aug 30, 1:37 pm, Alan Isaac <ais... at american.edu> wrote: > Can someone point me to a simple example > or better yet tutorial for creating > a Powerpoint using Python. > > Thanks, > Alan Isaac You should check our the following for information on using COM itself: http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html Core Python Programming by Chun has an example in it using Tkinter. I did it a while back, so here's the source: <code> # Core Python Chp 23, pg 994 # ppoint.pyw from Tkinter import Tk from time import sleep from tkMessageBox import showwarning import win32com.client as win32 warn = lambda app: showwarning(app, 'Exit?') RANGE = range(3, 8) def ppoint(): app = 'PowerPoint' ppoint = win32.gencache.EnsureDispatch('%s.Application' % app) pres = ppoint.Presentations.Add() ppoint.Visible = True s1 = pres.Slides.Add(1, win32.constants.ppLayoutText) sleep(1) sla = s1.Shapes[0].TextFrame.TextRange sla.Text = 'Python-to-%s Demo' % app sleep(1) slb = s1.Shapes[1].TextFrame.TextRange for i in RANGE: slb.InsertAfter("Line %d\r\n" % i) sleep(1) slb.InsertAfter("\r\nTh-th-th-that's all folks!\r\n") warn(app) pres.Close() ppoint.Quit() if __name__ == '__main__': Tk().withdraw() ppoint() </code> I recommend getting ActiveState's Python distro as it comes with an IDE that can browse COM objects fairly easily. Hope that helps! Mike From BjornSteinarFjeldPettersen at gmail.com Sun Aug 19 19:06:39 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sun, 19 Aug 2007 23:06:39 -0000 Subject: Latest models of Gibson guitars In-Reply-To: <1187548916.909340.37420@k79g2000hse.googlegroups.com> References: <1187544898.289948.322160@22g2000hsm.googlegroups.com> <1187548916.909340.37420@k79g2000hse.googlegroups.com> Message-ID: <1187564799.265981.75740@o80g2000hse.googlegroups.com> On Aug 19, 8:41 pm, vedrandeko... at v-programs.com wrote: > On 19 kol, 19:34, mobile... at gmail.com wrote: > [spam] > > Hello, > > This is a newsgroup of programming language Python, stop with this! > > Regards, > Vedran As someone else pointed out, this is more widely disseminated than just c.l.py. If you feel the need to do something about the post, and you're using Google groups, there's a "More options" link in the top right corner of every post where you can report it as spam. That might be marginally more effective than trying to chastise a spammer for being off-topic (it's what they do) -- at least it won't degrade the signal/noise ratio further. -- bjorn From seem at gazeta.pl Fri Aug 3 16:49:16 2007 From: seem at gazeta.pl (Lukasz) Date: Fri, 03 Aug 2007 22:49:16 +0200 Subject: Eclipse and Python In-Reply-To: <59f9c5160708030922m2f4f5179nf384135214246d14@mail.gmail.com> References: <59f9c5160708030922m2f4f5179nf384135214246d14@mail.gmail.com> Message-ID: <46B394CC.6080904@gazeta.pl> U?ytkownik Danyelle Gragsone napisa?: > Does anyone have any suggested websites for learning Eclipse the python way? > > thanks, > Danyelle http://www.showmedo.com/videos/series?name=PyDevEclipseList -- Opole - Miasto Bez Granic. http://www.opole.pl - tu znajdziesz nowe miejsca, nowe mozliwosci, nowe inspiracje... From rcdailey at gmail.com Tue Aug 21 12:27:21 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 21 Aug 2007 11:27:21 -0500 Subject: Python is removing my quotes! In-Reply-To: <46CB0E29.2010306@islandtraining.com> References: <496954360708210900p6da42670o3a28d6b0dbd4c524@mail.gmail.com> <46CB0E29.2010306@islandtraining.com> Message-ID: <496954360708210927w10655bbdtc977aace232bf05d@mail.gmail.com> Thank you for your response. The back slashes work! It's a bit annoying; but I have Microsoft to thank for that. On 8/21/07, Gary Herron <gherron at islandtraining.com> wrote: > > Robert Dailey wrote: > > Hi, > > > > Note: I'm using Python on Windows > > > > I have an application that allows a user to submit a password as a > > command line parameter. The password of choice may contain any > > characters the user wishes, including quotes. If I do the following: > > > > python password.py "9999"MyPassword > > > > The resulting output when I print this inside the script is: > > > > 9999MyPassword > > > > Notice how the quotations have been stripped. Is it DOS doing this, or > > Python? Is there a way I can fix it? > > > > Thanks. > > Not Python. It never even sees those quotes. Whatever system you are > using for entering the text is stripping them. Is it the command prompt > (cmd.exe)? If so then you can escape the quote by preceding it with a > backslash. (This is true of the DOS prompt and all the unix shells, and > their windows ports, that I know about.) > > Gary Herron > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070821/347e464e/attachment.html> From steveo at syslang.net Thu Aug 23 16:55:21 2007 From: steveo at syslang.net (Steven W. Orr) Date: Thu, 23 Aug 2007 16:55:21 -0400 (EDT) Subject: Redo: Problem with dynamic creation of classes. Message-ID: <alpine.LFD.0.999.0708231654210.1598@saturn.syslang.net> Sorry, I had a small description problem. It's corrected below. I have a base class B and a derived class D which inherits from B. I also have a D2 class which inherits from D. D is used as a base class for most of my generated classes. I have a "special" class which inherits from D2 because I need to override a couple of its methods. Anything based on D will inherit Encode and Decode from B. class D(b.B): def __init__(self, data, timestamp = None): b.B.__init__(self, data) self.timestamp = timestamp class D2( D ): def __init__(self, data, timestamp = None): DS.__init__(self, data, timestamp) def Decode(self): pass def Encode(self): pass The generated classes come from this loop: for m in mdefs: mdef = mdefs[m] name = mdef['name'] + fbase if mdef.has_key('baseclass'): base_class_seq = mdef['baseclass'] else: base_class_seq = DEFAULT_BASE_CLASS nclass = new.classobj( name, base_class_seq, globals() ) base_class_seq is either going to be (D,) or (D2,) After I get through the class generation, I want to say globals()['IFRAMED2'].Decode = dynDecode globals()['IFRAMED2'].Encode = dynEncode for the one class that inherited from D2. If I do that, I find that *all* classes that call Encode or Decode are all calling dyn{En,De}code (which is exactly what I *don't* want). So I looked at the id values after class generation. print 'IFRAMED2.Encode = ', IFRAMED2.Encode, id(IFRAMED2.Encode) print 'SNRMD.Encode = ', SNRMD.Encode, id(SNRMD.Encode) print 'IFRAMED2 = ', IFRAMED2, id(IFRAMED2) print 'SNRMD = ', SNRMD, id(SNRMD) IFRAMED2.Decode = dynDecode IFRAMED2.Encode = dynEncode print 'IFRAMED2.Encode = ', IFRAMED2.Encode, id(IFRAMED2.Encode) print 'SNRMD.Encode = ', SNRMD.Encode, id(SNRMD.Encode) Here's the output: IFRAMED2.Encode = <unbound method IFRAMED2.Encode> 1100623660 SNRMD.Encode = <unbound method SNRMD.Encode> 1100623660 IFRAMED2 = d.IFRAMED2 1076299644 SNRMD = d.SNRMD 1103202364 IFRAMED2.Encode = <unbound method IFRAMED2.dynEncode> 1100623660 SNRMD.Encode = <unbound method SNRMD.dynEncode> 1100623660 So it looks like the IFRAMED2 class which inherits from D2 is starting out with the same id value for Encode as SNRMD which inherits from D, even though D2 defines its own Encode method. Is it me of is it the interpreter doing something wrong? -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net -- http://mail.python.org/mailman/listinfo/python-list From steve at holdenweb.com Sun Aug 19 20:37:29 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 19 Aug 2007 20:37:29 -0400 Subject: "Variable variable name" or "variable lvalue" In-Reply-To: <46C8796F.8090505@islandtraining.com> References: <1187199722.618893.281170@r29g2000hsg.googlegroups.com> <1187541583.607550.107230@57g2000hsv.googlegroups.com> <46C8796F.8090505@islandtraining.com> Message-ID: <faannv$o18$1@sea.gmane.org> Gary Herron wrote: > inmmike at gmail.com wrote: >> On Aug 15, 1:42 pm, mfglinux <mfgli... at gmail.com> wrote: >> >>> Hello to everybody >>> >>> I would like to know how to declare in python a "variable name" that >>> it is in turn a variable >>> In bash shell I would wrote sthg like: >>> >>> for x in `seq 1 3` >>> do >>> M$i=Material(x) #Material is a python class >>> done >>> >>> Why I need this? Cause I have a python module that obliges me to build >>> a variable called Period, which should have a variable name of >>> summands (depends on the value of x) >>> >>> #Let's say x=3, then Period definition is >>> Period=Slab(Material1(12.5)+Material2(25)+Material3(12.5)) #Slab is a >>> python class >>> >>> I dont know how to automatize last piece of code for any x >>> >>> thank you >>> >>> Marcos >>> >> Regardless of whether or not this is a "best practice" sometimes it is >> necessary. For example, I am looping through a dictionary to set some >> class properties. Anyway, here is what I finally came up with: >> >> exec "self.%s = '%s'" % (item, plist[item]) >> > Yuck! Not at all necessary. Use setattr instead: > > setattr(self, item, plist[item]) > > That's much cleaner then an exec or eval. You may also find getattr and > hasattr useful. > Or even, in some cases, self.__dict__.update(otherdict) if you have a dictionary of stuff to put into an object. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From kyosohma at gmail.com Mon Aug 6 14:34:01 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 06 Aug 2007 18:34:01 -0000 Subject: Tkinter or wxpython? In-Reply-To: <46B75F31.9070208@codebykevin.com> References: <op.tv98rva4wepdt4@ericb.pragmadev> <mailman.1550.1186099225.22759.python-list@python.org> <1186410331.905174.21370@q3g2000prf.googlegroups.com> <7xps204tin.fsf@ruckus.brouhaha.com> <46B73DE4.6040405@codebykevin.com> <1186421115.402000.88080@x35g2000prf.googlegroups.com> <46B75F31.9070208@codebykevin.com> Message-ID: <1186425241.246492.144340@d30g2000prg.googlegroups.com> On Aug 6, 12:49 pm, Kevin Walzer <k... at codebykevin.com> wrote: > kyoso... at gmail.com wrote: > > > I tried the PMW widget toolkit. It was ok, but it seemed kind of > > buggy. I found out about Tix on a forum of some sort. When I tried to > > find out how to get it and use it, all I found was conflicting > > information. I finally got it downloaded only to find I had to compile > > it and I didn't have the right version of TCL. So I switched to > > wxPython then. Months later I found out that Tix is now included with > > Python. > > > I still don't know how to use it though. As with most external Tkinter > > widget sets, Tix doesn't have examples. The docs look less inviting > > than man pages...but I realize that's probably just me. I just don't > > like man pages much. > > Tkinter comes more naturally to me than other toolkits because I'm also > a Tcl developer. I just haven't felt the need to learn wxPython because > I can get what I need from Tkinter, even the more complicated GUI layouts. > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com Yeah...I would assume I would enjoy Tkinter more if I knew more tcl. Until that day arrives though, it will probably still be fairly confusing for me to figure out. I do like it's "pythonic" style though. Mike From sdeibel at gmail.com Thu Aug 2 10:50:31 2007 From: sdeibel at gmail.com (sdeibel at gmail.com) Date: Thu, 02 Aug 2007 07:50:31 -0700 Subject: Wing IDE for Python v. 3.0 beta1 released In-Reply-To: <mailman.1453.1186004775.22759.python-list@python.org> References: <46AF8ED7.2070206@wingware.com> <20070801212840.GA25065@spookie1.spookiegate> <mailman.1453.1186004775.22759.python-list@python.org> Message-ID: <1186066231.229502.133040@57g2000hsv.googlegroups.com> On Aug 1, 5:45 pm, "Joshua J. Kugler" <jos... at eeinternet.com> wrote: > I tend to let questions slide when they are answered in the documentation or > on the web site. Maybe theWingdevelopers/support personnel are the same > way. Just to clarify: We never do that. If you don't hear from us in response to a question, something has gone wrong (either we didn't get your email or ours got filtered). In this case, there was a typo in the reply-to email message and I didn't manage to figure out the correct email address to reply to until now. Stephan Deibel Wingware From sentientholon at gmail.com Wed Aug 22 12:09:39 2007 From: sentientholon at gmail.com (Frederick Polgardy) Date: Wed, 22 Aug 2007 16:09:39 -0000 Subject: Eval and raw string ?? In-Reply-To: <1187798806.029598.264740@q3g2000prf.googlegroups.com> References: <1187798806.029598.264740@q3g2000prf.googlegroups.com> Message-ID: <1187798979.244766.257370@e9g2000prf.googlegroups.com> On Aug 22, 11:06 am, Mark <cree... at gmail.com> wrote: > Eval() doesn't seem to recognize the r'string' format. Is there a way > around this. > Example: > If I input: ---------> eval("r'C:\tklll\ndfd\bll'") > I get the output: > > Traceback (most recent call last): > File "<pyshell#3>", line 1, in <module> > eval("r'C:\tklll\ndfd\bll'") > File "<string>", line 1 > r'C: klll > ^ > SyntaxError: EOL while scanning single-quoted string > > The same principle applies for exec. > > Thanks in advance, > Mark The r'' format is purely for the interpreter; eval wouldn't know the difference. Your problem is that eval and exec evaluate source. You're trying to do execfile(). Fred From steve at holdenweb.com Thu Aug 30 07:28:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Aug 2007 07:28:52 -0400 Subject: Python doesn't see the directories I create In-Reply-To: <46d6a72c$0$20532$426a74cc@news.free.fr> References: <ldvBi.293202$LE1.92748@newsfe13.lga> <46d6856b$0$17674$426a74cc@news.free.fr> <mailman.133.1188471584.28954.python-list@python.org> <46d6a72c$0$20532$426a74cc@news.free.fr> Message-ID: <fb69lm$gr$1@sea.gmane.org> Bruno Desthuilliers wrote: > Steve Holden a ?crit : >> Bruno Desthuilliers wrote: [...] >> That does indeed work in most situations, but ideally (i.e. for maximum >> code portability) paths should be constructed using os.path.join(), or >> collected from the environment somehow. > > Indeed. But I doubt a path starting with 'C:' will work fine on a > unix-like environment anyway !-) Just to be contrarian: sholden at bigboy ~/Projects/python.org/build $ ls C:/Steve/ Apache SANSsecurityOverview.pdf Apache2 SQLServer.txt ... Resume.odt todo.txt Resume.pdf untitled-1.py sholden at bigboy ~/Projects/python.org/build That's Cygwin, of course. Is that sufficiently "unix-like"? Though I have to admit that the different utilities all take different approaches to the use of Windows paths, and some just won't take them at all. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From eric at abrahamsen.com Wed Aug 22 03:45:05 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Wed, 22 Aug 2007 15:45:05 +0800 Subject: for statement on empty iterable In-Reply-To: <1187761957.636211.107060@x40g2000prg.googlegroups.com> References: <1187760507.951994.50310@q4g2000prc.googlegroups.com> <7xabsk3zgm.fsf@ruckus.brouhaha.com> <1187761270.713307.224570@i38g2000prf.googlegroups.com> <7xejhw15r9.fsf@ruckus.brouhaha.com> <1187761957.636211.107060@x40g2000prg.googlegroups.com> Message-ID: <57EFA4FF-D7AC-4FAA-A455-AAAEF73BC4D5@abrahamsen.com> Here's another simple method: l = ['j', 'a', 'm', 'e', 's'] counter = 0 for i in l: # Do your code counter += 1 print counter Yrs, Eric > l = ['j', 'a', 'm', 'e', 's'] > > for i in l > # i want to know the nth number of times it has loop thru or > something like counter? > > Thanks > james > > -- > http://mail.python.org/mailman/listinfo/python-list > From afriere at yahoo.co.uk Tue Aug 21 03:51:45 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 21 Aug 2007 00:51:45 -0700 Subject: Newbee Question In-Reply-To: <1187682119.353756.278840@i13g2000prf.googlegroups.com> References: <mailman.15.1187620149.26576.python-list@python.org> <1187682119.353756.278840@i13g2000prf.googlegroups.com> Message-ID: <1187682705.769160.68850@q3g2000prf.googlegroups.com> On Aug 21, 5:41 pm, Asun Friere <afri... at yahoo.co.uk> wrote: > over = Decimal('1.40) oops, that should of course be: over = Decimal('1.40') From edgrsprj at ix.netcom.com Thu Aug 30 21:55:43 2007 From: edgrsprj at ix.netcom.com (E.D.G.) Date: Thu, 30 Aug 2007 19:55:43 -0600 Subject: Important Research Project References: <13ddcvm1bsu3s94@corp.supernews.com> <1188482087.098419.56490@k79g2000hse.googlegroups.com> <1188500139.411988.127100@q5g2000prf.googlegroups.com> Message-ID: <13deppf942e6u45@corp.supernews.com> "dave_w" <dave.willmer at gmail.com> wrote in message news:1188500139.411988.127100 at q5g2000prf.googlegroups.com... My main Perl program is presently about 3500 lines of code long and 160 KB in size. So I am not too anxious to translate it into another language. The problem I am having is largely with the mechanics of linking modules to the Perl compiler etc. So I am looking for experts who can help with cookbook instructions, start with step 1, step 2, step 3 etc. With trying to find a chart program to use for example, there appear to be a number of them. But from examining their instructions it looks like most of them must also be linked to a third program called Gnuplot. And that increases the complexity of getting something running. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Aug 19 17:33:15 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 19 Aug 2007 23:33:15 +0200 Subject: Development for dual core machine References: <1187515287.226791.186700@j4g2000prf.googlegroups.com> <08Xxi.28398$RX.5261@newssvr11.news.prodigy.net> Message-ID: <5irr8rF3r2m8aU2@mid.individual.net> samwyse wrote: > The Python interpreter is not multi-cpu aware, so using Python > threads won't work on multiple CPUs. Are you sure about this? Regards, Bj?rn -- BOFH excuse #12: dry joints on cable plug From damondolby at googlemail.com Wed Aug 15 04:25:22 2007 From: damondolby at googlemail.com (towers) Date: Wed, 15 Aug 2007 01:25:22 -0700 Subject: module: zipfile.writestr - line endings issue In-Reply-To: <1%xwi.1232$4w7.433@newssvr22.news.prodigy.net> References: <1187107452.905165.45700@l70g2000hse.googlegroups.com> <1187110504.154878.317460@19g2000hsx.googlegroups.com> <1187112768.095414.223640@w3g2000hsg.googlegroups.com> <1187120956.574400.99170@g4g2000hsf.googlegroups.com> <1%xwi.1232$4w7.433@newssvr22.news.prodigy.net> Message-ID: <1187166322.391371.258800@a39g2000hsc.googlegroups.com> > > Please don't top post. > > > The problem is with how you are opening the file. You need to open in > > binary mode if you wish to read your file unaltered. Also, file() is > > preferred over open() these days I think. Use: > > > dfile = file('test.csv', 'rb') > > From Python 2.5 library documentation. > > <quote> > When opening a file, it's preferable to use `open()' instead of > invoking this constructor directly. `file' is more suited to type > testing (for example, writing `isinstance(f, file)'). > </quote> > > Python documentation seem to recommend using open(). I personally prefer > to use open, just because python open has same signature as POSIX open, > even beginner programmers can understand the intent of the code clearly. > > Kolla Opening in binary mode solves the issue. Thanks very much for the help. From rainwatching at gmail.com Fri Aug 31 08:53:36 2007 From: rainwatching at gmail.com (=?iso-8859-1?q?S=F6nmez_Kartal?=) Date: Fri, 31 Aug 2007 12:53:36 -0000 Subject: reload(sys) In-Reply-To: <JK2dnSgydPkg8ErbnZ2dnUVZ_u3inZ2d@comcast.com> References: <1188521143.421431.119100@l22g2000prc.googlegroups.com> <JK2dnSgydPkg8ErbnZ2dnUVZ_u3inZ2d@comcast.com> Message-ID: <1188564816.430863.219560@w3g2000hsg.googlegroups.com> On 31 A ustos, 04:24, Steven Bethard <steven.beth... at gmail.com> wrote: > S?nmez Kartal wrote: > > I've had an encoding issue and solved it by > > "sys.setdefaultencoding('utf-8')"... > > > My first try wasn't successful since setdefaultencoding is not named > > when I imported sys module. After, I import sys module, I needed to > > write "reload(sys)" also. > > > I wonder why we need to call "reload(sys)" to get setdefaultencoding > > named? > > sys.setdefaultencoding is purposely deleted from the sys module after > it's loaded because you really shouldn't be using it. The reload() call > restores the deleted attribute. > > If you'd like a less brittle solution to your encoding issue, explain > what the issue was, and people here can probably help you find a better > solution. > > STeVe I was using the XMLBuilder(xmlbuilder.py). I'm writing XML files as "f.write(str(xml))". At execution of that line, it gives error with description, configure your default encoding... My operating system's default is utf-8, and Emacs' is utf-8 too. Default of XMLBuilder is utf-8 too. There were some characters interpreter may couldn't print in ascii. I have tried to replace those characters like (TM) (R)... I cannot remember them right now, but if necessary I can find them easily... This is the part of xmlbuilder.py which raises the error. try: if self.pretty: # tabs are evil, so we will use two spaces outstr = self._dom.toprettyxml(" ",encoding=self.encoding) else: outstr = self._dom.toxml(encoding=self.encoding) except UnicodeDecodeError: sys.stderr.write('Decoding Error: You must configure default encoding\n') sys.exit() What I can do instead of "import sys; reload(sys); sys.setdefaultencoding('utf-8')"? Happy coding From larry.bates at websafe.com Wed Aug 15 15:11:56 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 15 Aug 2007 14:11:56 -0500 Subject: "Variable variable name" or "variable lvalue" In-Reply-To: <1187199722.618893.281170@r29g2000hsg.googlegroups.com> References: <1187199722.618893.281170@r29g2000hsg.googlegroups.com> Message-ID: <8PSdnfQVbqhk0l7bnZ2dnUVZ_h2pnZ2d@comcast.com> mfglinux wrote: > Hello to everybody > > I would like to know how to declare in python a "variable name" that > it is in turn a variable > In bash shell I would wrote sthg like: > > for x in `seq 1 3` > do > M$i=Material(x) #Material is a python class > done > > Why I need this? Cause I have a python module that obliges me to build > a variable called Period, which should have a variable name of > summands (depends on the value of x) > > #Let's say x=3, then Period definition is > Period=Slab(Material1(12.5)+Material2(25)+Material3(12.5)) #Slab is a > python class > > I dont know how to automatize last piece of code for any x > > thank you > > Marcos > I think the answer is to use a dictionary of lists , but it is a little hard to tell from your description: mdict={1:[Material1, 12.5], 2:[Material2, 25.0], 3:[Material3, 12.5] } x=3 slab_arg=0 for i in range(1,x): func, farg=mdict[i] slab_arg+=func(farg) Period=Slab(slab_arg) Obviously not tested! I sense that the Material functions should be consolidated into something more general here. -Larry Bates From hamstu at gmail.com Wed Aug 22 23:59:34 2007 From: hamstu at gmail.com (Hamish Macpherson) Date: Thu, 23 Aug 2007 03:59:34 -0000 Subject: libgmail failure In-Reply-To: <1187730447.621592.93740@q4g2000prc.googlegroups.com> References: <1187730447.621592.93740@q4g2000prc.googlegroups.com> Message-ID: <1187841574.800105.219970@z24g2000prh.googlegroups.com> On Aug 21, 5:07 pm, "james.p.n... at gmail.com" <james.p.n... at gmail.com> wrote: > Hey all, > > I've been usinglibgmailto send out automated notification emails for > my company's nightly regression testing. Last night these emails > started failing, though the python code has not changed. I updated to > the latestlibgmail, but that isn't helping. I've logged in to the > email account directly, and the account is still working fine. > > The error I get is "HTTP Error 400: Bad Request" when using > gmailAccount.login(). This doesn't throw an exception, just prints > the error. The code crashes outright when it tries to send mail. > > This code has been up and running for several months and just started > failing last night. Does anyone have an idea what's going on? > > The code and error follow (fairly short :-) > > Thanks much, > James > > Code: > ------------------------------------------------------------------------------------------------------- > def send(TO_LIST,SUBJECT,MESSAGE): > GA =libgmail.GmailAccount("xxx... at gmail.com","xxxxxxx") > try: > print "Logging in" > GA.login() > exceptlibgmail.GmailLoginFailure: > print "\nLogin failed. (Wrong username/password?)" > else: > print "Log in successful.\n" > for RX in TO_LIST: > MSG =libgmail.GmailComposedMessage(RX,SUBJECT,MESSAGE) > if GA.sendMessage(MSG): > print "Message successfully sent to `%s` ." % RX > else: > print "Could not send message." > ------------------------------------------------------------------------------------------------------- > > Output: > ------------------------------------------------------------------------------------------------------- > Logging in > HTTP Error 400: Bad Request > Log in successful. > > No messages found > Traceback (most recent call last): > File "C:\projects\physware\testCases\PythonTestScripts > \SendEmail.py", line 58, in <module> > main() > File "C:\projects\physware\testCases\PythonTestScripts > \SendEmail.py", line 55, in main > send(TO_LIST,SUB,MSG) > File "C:\projects\physware\testCases\PythonTestScripts > \SendEmail.py", line 39, in send > if GA.sendMessage(MSG): > File "C:\projects\physware\testCases\PythonTestScripts\libgmail.py", > line 588, in sendMessage > U_ACTION_TOKEN: self._getActionToken(), > File "C:\projects\physware\testCases\PythonTestScripts\libgmail.py", > line 563, in _getActionToken > at = self._cookieJar._cookies[ACTION_TOKEN_COOKIE] > KeyError: 'GMAIL_AT' > ------------------------------------------------------------------------------------------------------- I believe I've found a (temporary) fix in this forum thread: http://www.castlecops.com/p984588-HTTP_Error_400_when_using_gknujon.html Pasted here for posterity; --- Edit the libgmail.py file. In the function def login(self) change the following text: Code: try: link = re.search(RE_PAGE_REDIRECT, pageData).group(1) redirectURL = urllib.unquote(link) to add the extra line: Code: try: link = re.search(RE_PAGE_REDIRECT, pageData).group(1) redirectURL = urllib.unquote(link) redirectURL = redirectURL.replace('\\x26','&') --- Must have been some small change in gmail's redirect that put it off. From steve at holdenweb.com Fri Aug 31 21:37:09 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 31 Aug 2007 21:37:09 -0400 Subject: How can I wait for all the threads I spawn for 5 minutes In-Reply-To: <1188603646.671414.272760@w3g2000hsg.googlegroups.com> References: <1188603646.671414.272760@w3g2000hsg.googlegroups.com> Message-ID: <fbafo8$ugc$1@sea.gmane.org> herman wrote: > Hi, > > In my python program, I would to like to spwan 5 threads, for the them > for 5 minutes maximum and the continue. Here is my script: > > threads = [] > > for j in range(5): > t = MyThread() > threads.append(t) > > for t in threads: > t.join(60*5) > print "thread join\n" > > # wait for 5 minutes for all the threads to complete , > and > # then continue > > But this code ends up waiting 5 minutes for **each** thread. that is > not what I want. I just want to wait for 5 minutes for all threads. > how can I do that? > > And after 5 minutes, i want to kill off all the threads I spawn > earlier, how can I do that in python. > > Thank you for any help. > Well, to answer your second question, there is no reliable way to kill a thread without having the thread periodically examine some aspect of its environment that the main thread can change to indicate the requirement that the sub-thread terminate. The easiest way to check the number of outstanding threads is to use threading.activeCount(), which tells you how many outstanding threads remain. Here's some code I used in a test program recently: # As long as we have more than just the 'main' thread running, # print out a status message while threading.activeCount() > 1 : print "-- after", iterCount, "sleeps", \ str(threading.activeCount()), "threads running in total" iterCount += 1 time.sleep(1) print "Only main thread remains" Clearly you will need to set some termination flag (a global variable would do) after time is up, and as long as your threads examine this flag you'll be good to go. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bbxx789_05ss at yahoo.com Mon Aug 6 18:46:55 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 06 Aug 2007 15:46:55 -0700 Subject: udp, datagram sockets In-Reply-To: <1186431279.714122.316530@j4g2000prf.googlegroups.com> References: <1186416225.769753.307110@o61g2000hsh.googlegroups.com> <mailman.1691.1186428498.22759.python-list@python.org> <1186431279.714122.316530@j4g2000prf.googlegroups.com> Message-ID: <1186440415.340206.147800@d55g2000hsg.googlegroups.com> On Aug 6, 1:27 pm, Carsten Haese <cars... at uniqsys.com> wrote: > I don't think that sending the datagram to port 7777 on localhost sends > the message back to the client. I'm guessing the server is sending the > message back to itself, which throws it into the infinite feedback loop > you're experiencing. > Thanks. On Aug 6, 2:14 pm, anethema <jefish... at gmail.com> wrote: > Yes, you want to use the socket.recvfrom() method, store the address, > and send the response to that address. Your code is indeed repeatedly > sending itself the received message. > > You want to change > >> data = s.recv(1024) > > to > > data, recv_addr = s.recvfrom(1024) > > and > >> size_sent = s.sendto(message[total_sent:], ("localhost", >> 7777) ) > > to > > size_sent = s.sendto(message[total_sent:], recv_addr) > Thanks for the details. > However, your client closes immediately after sending all its data, so > it will never receive that message. > Yes, I commented out the recv() part of the client to debug the infinite loop I was experiencing. When I add that back to the client everything works as it should. Thanks to both of you again. From zowtar at gmail.com Fri Aug 31 11:42:42 2007 From: zowtar at gmail.com (zowtar) Date: Fri, 31 Aug 2007 08:42:42 -0700 Subject: JavaScript Message-ID: <1188574962.185775.274420@d55g2000hsg.googlegroups.com> Guys, anybody know if is possible "to press" a button linked a javascript function using python? My Firefox send something like that: POST /msgs.aspx TOKEN=B8B83BGDBC191B9FE0A0BE1393294FAB&sig=gpaiOqbp0Nr %2BoecRLF4FGGDOAao %3D&toUserId=1331299&rawAddedDate=1188546666&fromUserId=23029&Action.delete=Send +data python has modules for forms and other things... and for it? Thank you for help... zowtar From steve at holdenweb.com Mon Aug 13 09:49:28 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 13 Aug 2007 09:49:28 -0400 Subject: negative polar axis In-Reply-To: <1186999666.642856.16820@19g2000hsx.googlegroups.com> References: <1186999666.642856.16820@19g2000hsx.googlegroups.com> Message-ID: <f9pnh3$ce4$1@sea.gmane.org> yadin wrote: > hi! > how can i do polar plot in python with negative axes > that is the value of the magnitude is negative > Surely a negative magnitude doesn't make sense in polar coordinates, since the magnitude is supposed to represent the distance from the center. About the best interpretation I can think of is to add 180 degrees to the angle and reverse the sign of the magnitude, but this would be a hack. Where are those coordinates coming from? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From steve at holdenweb.com Fri Aug 31 21:41:22 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 31 Aug 2007 21:41:22 -0400 Subject: Parameter Passing - String Variable Truncated ? In-Reply-To: <1188604442.700651.94530@19g2000hsx.googlegroups.com> References: <1188604442.700651.94530@19g2000hsx.googlegroups.com> Message-ID: <fbag04$ugc$2@sea.gmane.org> goldtech wrote: > Hi, > > I'm passing what I think is a string parameter to another Python > program (spawn.py) - see the code snip below. But only the counter > part gets printed to a log file via spawn.py. Yet the echo print to > the output window shows the whole string with the fc part. Better > explained below I hope, there's the calling .py and the spawn > script .py: > ...snip... > while fc: > counter = counter + 1 > fc_cntr = str(counter) + ' : ' + fc > print fc_cntr + '\n' # Print to Pythonwin interactive window - > eg. "1 : New York" - all is printed OK > > arglist = [] > arglist.append(pythonPath) > arglist.append(spawn_script) > arglist.append(fc_cntr) # This gets sent to the spawn_script but > only "1" gets printed > > os.spawnv(os.P_WAIT, pythonPath, arglist) > fc = fcs.next() > ... > -------------------------- > ## the spawn_script > import win32com.client, sys, os, time, re > > in_featclass = sys.argv[1] Try in_featclass = sys.argv[1:] to collect all the arguments. At the moment I suspect some shell argument processing is intervening, splitting your "N : something" into multiple arguments. > handle = open('C:\\log_file.txt', 'a') > handle.write(in_featclass + "\n") # ONLY the counter part gets printed > to the log file! Why? > -------------------------- > > Thanks, for help. > regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From nick at craig-wood.com Fri Aug 10 11:30:06 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 10 Aug 2007 10:30:06 -0500 Subject: The Future of Python Threading References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <5i329uF3muir4U1@mid.individual.net> Message-ID: <slrnfbou9k.vkb.nick@irishsea.home.craig-wood.com> Bjoern Schliessmann <usenet-mail-0306.20.chr0n0ss at spamgourmet.com> wrote: > Justin T. wrote: > > > The detrimental effects of the GIL have been discussed several > > times and nobody has ever done anything about it. > > Also it has been discussed that dropping the GIL concept requires > very fine locking mechanisms inside the interpreter to keep data > serialised. The overhead managing those fine ones properly is not > at all negligible, and I think it's more than managing GIL. That is certainly true. However the point being is that running on 2 CPUs at once at 95% efficiency is much better than running on only 1 at 99%... > > The truth is that the future (and present reality) of almost every > > form of computing is multi-core, > > Is it? 8) Intel, AMD and Sun would have you believe that yes! > The question is: If it really was, how much of useful performance > gain would you get? The linux kernel has been through these growing pains already... SMP support was initially done with the Big Kernel Lock (BKL) which is exactly equivalent to the GIL. The linux kernel has moved onwards to finer and finer grained locking. I think one important point to learn from the linux experience is to make the locking a compile time choice. You can build a uniprocessor linux kernel with all the locking taken out or you can build a multi-processor kernel with fine grained locking. I'd like to see a python build as it is at the moment and a python-mt build which has the GIL broken down into a lock on each object. python-mt would certainly be slower for non threaded tasks, but it would certainly be quicker for threaded tasks on multiple CPU computers. The user could then choose which python to run. This would of course make C extensions more complicated... -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From Brian.McCann at viziant.net Thu Aug 23 20:53:03 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Thu, 23 Aug 2007 20:53:03 -0400 Subject: creating a tar file with python References: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> <faktv8$8fs$1@sea.gmane.org> Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE2ED@efmailx> Hi, I'm now getting this error any ideas? Thanks, Brian Traceback (most recent call last): File "./tarup.py", line 25, in ? tar = tarfile.open("test.xml","sample.tar.gz", 'w:gz') File "/usr/lib64/python2.4/tarfile.py", line 929, in open raise ValueError, "undiscernible mode" ValueError: undiscernible mode ############################################################ #!/usr/bin/python import string import os import sys import time import errno import shutil import tarfile tar = tarfile.open(test.xml","sample.tar.gz", 'w:gz') <mailto:brian.mccann at viziant.net> ________________________________ From: python-list-bounces+brian.mccann=viziant.net at python.org on behalf of Steve Holden Sent: Thu 8/23/2007 5:24 PM To: python-list at python.org Subject: Re: creating a tar file with python Brian McCann wrote: > Hi, > > I'm trying to create a tar file of the contents of the current directory > > right now there is only one file "text.xml" in the current dir, I'm > using"." current dir as source > but that gives syntax error > > any help would be greatly appreciated > --Brian > > > #!/usr/bin/python > import string > import os > import sys > import time > import errno > import shutil > import tarfile > > > tar = tarfile.open(.,"test.tar.gz", "w:gz) > <mailto:brian.mccann at viziant.net> > > well, /probably/ (meaning I haven't done any testing) you need quotes around the name of the current directory just like you do around the name of the file. Try tar = tarfile(".", "test.tar.gz", "w:gz") regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070823/18a157cf/attachment.html> From tooru_honda at fast-mail.org Fri Aug 24 22:43:42 2007 From: tooru_honda at fast-mail.org (tooru honda) Date: Sat, 25 Aug 2007 10:43:42 +0800 Subject: Does shuffle() produce uniform result ? References: <tooru_honda-1F800B.15385124082007@wvnews01.netvigator.com> <mailman.243.1187955760.32294.python-list@python.org> Message-ID: <tooru_honda-7C82D1.10432725082007@wvnews01.netvigator.com> Hi, First of all, my thanks to all of you who replied. I am writing a gamble simulation to convince my friend that his "winning strategy" doesn't work. I use shuffle method from a random.SystemRandom instance to shuffle 8 decks of cards. As the number of cards is quite small (number of cards is 416), the nonuniformity doesn't matter as most of you have already said. Just to avoid argument from my friend, I am considering writing my own randint and shuffle methods based on os.urandom() though. -tooru honda From rcdailey at gmail.com Tue Aug 21 17:05:50 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 21 Aug 2007 16:05:50 -0500 Subject: Tokenizer for python? Message-ID: <496954360708211405j4ddbf4bfxd0710efbc58682b0@mail.gmail.com> Hi, I am looking for a sort of "tokenizer" for python. I've taken a look at the tokenize module, but that seems to parse python code from what I read. I want a tokenizer that works a little like boost::tokenizer, however for python. Basically I want to be able to pass in an arbitrary string (or line from readline()) and specify tokens that cause the string to be separated into parts, much like the regular expression split() method (I think that's the name of it). Is there anything that already exists that does this, or do I need to implement it myself with regular expressions? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070821/849ceb2a/attachment.html> From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Aug 2 03:56:55 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 02 Aug 2007 09:56:55 +0200 Subject: Emacs + python In-Reply-To: <mailman.1476.1186017909.22759.python-list@python.org> References: <ak8x8v2udo.fsf@googlemail.com> <mailman.1476.1186017909.22759.python-list@python.org> Message-ID: <46b18e47$0$25330$426a34cc@news.free.fr> Edward O'Connor a ?crit : >> Could anyone put me on the right track to developing Python with emacs >> please : modes to consider, debugging etc hopefully all within emacs. > > Personally, I prefer the python.el that ships with Emacs 22 to the > python-mode.el from python.org. It seems more like other Emacs major > modes. Would you mind giving us a quick summary of the differences between these 2 modes ? As far as I'm concerned, I've been mostly happy with python-mode so far... > > Ted > From kyosohma at gmail.com Thu Aug 2 15:23:39 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 02 Aug 2007 19:23:39 -0000 Subject: XML Processing In-Reply-To: <mailman.1532.1186081833.22759.python-list@python.org> References: <1186080339.344993.167670@z24g2000prh.googlegroups.com> <1186081434.012668.206770@z24g2000prh.googlegroups.com> <mailman.1532.1186081833.22759.python-list@python.org> Message-ID: <1186082619.193097.207650@x40g2000prg.googlegroups.com> On Aug 2, 2:09 pm, Jay Loden <pyt... at jayloden.com> wrote: > kyoso... at gmail.com wrote: > > On Aug 2, 1:45 pm, Roman <rgelfa... at hotmail.com> wrote: > >> Is there a package that converts a string that contains special > >> characters in xml to to literal value. For instance, converts stringhttp://myhome/¶mtohttp://myhome/¶m. > > >> Thanks in advance > > > I've seen examples using the HTMLgen module. But here's another script > > I just found: > > >http://mail.python.org/pipermail/python-list/1999-November/016814.html > > > I would think that you could use regular expressions too. > > > Mike > > I would reccommend against using the example above or using regular expressions, since both are likely to miss corner cases, and the stdlib has an encode function that's already designed for this task > > http://docs.python.org/lib/module-xml.sax.saxutils.html > > The encode() function in xml.sax.saxutils also is extensible, should you run into any entities that it fails to escape in the current implementation. > > -Jay Yes, I am an idiot. From http Sat Aug 4 01:06:25 2007 From: http (Paul Rubin) Date: 03 Aug 2007 22:06:25 -0700 Subject: How to pass a reference to the current module References: <f90gsg$ek4$1@zinnia.noc.ucla.edu> <pan.2007.08.04.01.46.50.985228@REMOVE.THIS.cybersource.com.au> <7xy7gs9ioe.fsf@ruckus.brouhaha.com> <pan.2007.08.04.04.37.38.567054@REMOVE.THIS.cybersource.com.au> Message-ID: <7xy7gr51ny.fsf@ruckus.brouhaha.com> Steven D'Aprano <steve at REMOVE.THIS.cybersource.com.au> writes: > I'll point at the difficulty in using getattr for extracting a function > from the current module: > >>> func = getattr(???, 'f') # what should go there? Hmm, it's a pain that there's no clean way to get at the current module. PEP 3130 shows some icky and unreliable ways, e.g. func = getattr(sys.modules[__name__], 'f') PEP 3130's goal was to add a clean way to do this. Unfortunately it was rejected. From simonwittber at gmail.com Fri Aug 17 01:06:19 2007 From: simonwittber at gmail.com (Simon Wittber) Date: Fri, 17 Aug 2007 05:06:19 -0000 Subject: One Python in a Pub, with 100 Rails Developers... Message-ID: <1187327179.563426.299340@i38g2000prf.googlegroups.com> Python helped deliver the goods last Wednesday evening in front of a one hundred strong crowd of Rails hecklers... Video footage here: http://blog.scouta.com/2007/08/16/iccarus/ ...just kidding, they were all great chaps, and only a few were Rails devs, and only a few of them were hecklers :-) I was amazed at how many developers in the audience use Rails for day to day development. As far as I could see, I was the only person developing web apps using a Python framework. For the interested, a more thorough screencast of the ICCARUS visualisation system is over here: http://scouta.com/faves/8raO17jT8Y3/ We used Python, Pyrex and Pygame to build ICCARUS over about 3 days. ICCARUS retrieved its data via a web service provided by TurboGears. It ran on OSX, Vista and Linux with minimal porting. Python through the entire system. Quite a 'Python Success Story', IMHO. -Sw. From aclarke11 at yahoo.co.uk Wed Aug 8 19:41:46 2007 From: aclarke11 at yahoo.co.uk (Tony) Date: Wed, 08 Aug 2007 16:41:46 -0700 Subject: How can I programmatically find the name of a method from within that method? In-Reply-To: <f9d92f$8qe$02$1@news.t-online.com> References: <1186548312.672360.259100@q3g2000prf.googlegroups.com> <mailman.1727.1186549847.22759.python-list@python.org> <1186557384.845276.151630@i13g2000prf.googlegroups.com> <f9br51$e9a$01$1@news.t-online.com> <1186603550.882122.223340@d55g2000hsg.googlegroups.com> <f9d92f$8qe$02$1@news.t-online.com> Message-ID: <1186616506.072708.3310@g4g2000hsf.googlegroups.com> On Aug 8, 9:28 pm, Peter Otten <__pete... at web.de> wrote: > No, just wrong. > > >> class A: > > ... def alpha(self): return dir(self)[-2] > ... def gamma(self): return dir(self)[-1] > ...>>> a = A() > >>> a.alpha(), a.gamma() > ('alpha', 'gamma') > >>> a.beta = 42 > >>> a.alpha(), a.gamma() > > ('beta', 'gamma') > > Peter Only wrong if the function is only to write its own name. if it does something else as well, seems to work: class a: def square(self, x): print 'executing:', dir(self)[-1] print x*x def cube(self, x): print 'executing:', dir(self)[-2] print x*x*x b=a() b.cube(4),b.square(2) b.c =4 b.cube(3), b.cube(2) executing: cube 64 executing: square 4 executing: cube 27 executing: cube 8 cheers From fartknuckle at fartknuckle.com Fri Aug 10 19:08:57 2007 From: fartknuckle at fartknuckle.com (fartknuckle) Date: Fri, 10 Aug 2007 18:08:57 -0500 Subject: Python Dies on "make install" References: <pan.2007.08.10.21.01.56.706157@fartknuckle.com> <f9im89$3tf$1@nemesis.news.tpi.pl> Message-ID: <pan.2007.08.10.23.08.54.304894@fartknuckle.com> On Fri, 10 Aug 2007 23:39:39 +0200, Jarek Zgoda wrote: > fartknuckle : > >> When I try to build and install python from source It configures and >> makes fine but upon 'make install' I always get to this >> point: >> >> >> >> Listing /usr/local/lib/python2.5/xml/sax ... >> Compiling /usr/local/lib/python2.5/xml/sax/__init__.py ... >> Compiling /usr/local/lib/python2.5/xml/sax/_exceptions.py ... >> Compiling /usr/local/lib/python2.5/xml/sax/expatreader.py ... >> Compiling /usr/local/lib/python2.5/xml/sax/handler.py ... >> Compiling /usr/local/lib/python2.5/xml/sax/saxutils.py ... >> Compiling /usr/local/lib/python2.5/xml/sax/xmlreader.py ... >> Compiling /usr/local/lib/python2.5/xmllib.py ... >> Compiling /usr/local/lib/python2.5/xmlrpclib.py ... >> Compiling /usr/local/lib/python2.5/zipfile.py ... >> make: *** [libinstall] Error 1 >> >> >> >> I am currently trying to install 2.5.1. I get the error no matter what the >> version is. Does anyone have an idea what may be causing this? >> >> I have gone through the config.log and found no errors concerning >> zipfile.py or zipfile or zip. I am thinking the error is the next command >> after the zipfile.py installation because I can go into >> /usr/local/lib/python2.5 and zipfile.py is installed. >> >> Any help much appreciated. > > I saw this (and reported this issue in SF's tracker) at some time around > 2.2/2.3 (just cann't recall). I don't know what causes this problem > exactly, but in my case the installation succeeded if I removed prevoius > python's library directory (/usr/lib/python2.x or > /usr/local/lib/python2.x). The module that stopped installation was > exactly the same. That did the trick, thanks a million. :) -- Take summa dis punk! From DustanGroups at gmail.com Fri Aug 10 08:36:23 2007 From: DustanGroups at gmail.com (Dustan) Date: Fri, 10 Aug 2007 12:36:23 -0000 Subject: Question about properties. In-Reply-To: <1186741865.755891.207090@i13g2000prf.googlegroups.com> References: <1186741289.074717.174370@e16g2000pri.googlegroups.com> <1186741865.755891.207090@i13g2000prf.googlegroups.com> Message-ID: <1186749383.720833.240060@x40g2000prg.googlegroups.com> On Aug 10, 5:31 am, dijkstra.ar... at gmail.com wrote: > On Aug 10, 12:21 pm, king kikapu <aboudou... at panafonet.gr> wrote: > > > > > Hi, > > > i read in a book the following code snippet that is dealing with > > properties: > > > class ProtectAndHideX(object): > > def __init__(self, x): > > assert isinstance(x, int), '"x" must be an integer!"' > > self.__x = ~x > > > def get_x(self): > > return ~self.__x > > > x = property(get_x) > > > Can anyone please help me understand what the symbol "~" does here ?? > > > Thanks for any help! > >>> help(2) > > .... > | __invert__(...) > | x.__invert__() <==> ~x > > hth. > Duikboot http://docs.python.org/ref/unary.html The unary ~ (invert) operator yields the bit-wise inversion of its plain or long integer argument. The bit-wise inversion of x is defined as -(x+1). It only applies to integral numbers. From zyzhu2000 at gmail.com Mon Aug 20 16:22:15 2007 From: zyzhu2000 at gmail.com (beginner) Date: Mon, 20 Aug 2007 20:22:15 -0000 Subject: 'REPL' style IDE In-Reply-To: <mailman.20.1187639538.32294.python-list@python.org> References: <1187632249.748945.158910@i13g2000prf.googlegroups.com> <mailman.20.1187639538.32294.python-list@python.org> Message-ID: <1187641335.794138.27150@q3g2000prf.googlegroups.com> On Aug 20, 2:51 pm, JoeSox <joe... at gmail.com> wrote: > On 8/20/07, beginner <zyzhu2... at gmail.com> wrote: > > > Hi Everyone, > > > I am using the Wing IDE. It works great when developing applications, > > but the workflow is like Visual Studio -- after you execute it or > > debug it, the python script ends. > > > What I want is an interactive interpreting environment. I want the IDE > > to execute a boot script to initialize my environment and create some > > basic data objects. And then I want to be able to type in command on > > the command line using these objects. The IDLE that comes with Python > > does this, but compared with Wing, it does not have a lot of the > > convenient features. > > > I am wondering if there is anything more powerful than IDLE that can > > do this. > > I use Wing IDE. > Place something like this on the bottom of your module you are debuging. > Place a stop point on the line you want then start your debug! Hope that helps. > > def test(): > c=MyClass > c.do_foobar() > > if __name__ == '__main__': > test() > -- > Later, Joe Thanks for your help. Yes, this is what I always do. However, I want more than debugging interactively. I am trying to use the python interperter as a programmable application. Once I run my boot script, the python interpreter should have all the right objects and libraries, and the end user (who obviously knows python) can simply type in a few commands, calling my functions, to achieve his purposes interactively. What I am doing right now is almost exactly what you prescribed. I put a 'pass' statement at the end of my boot script and set a breakpoint on it, so that once the debugger stops on the breakpoint, the user can start typing in commands in the Debug Probe window. But this is by no means a nice set up. Thanks, Geoffrey From pyscottishguy at hotmail.com Mon Aug 13 14:02:23 2007 From: pyscottishguy at hotmail.com (pyscottishguy at hotmail.com) Date: Mon, 13 Aug 2007 18:02:23 -0000 Subject: Colored text In-Reply-To: <slrnfc0kqf.1us.horpner@FIAD06.norwich.edu> References: <1186970751.435970.189900@q3g2000prf.googlegroups.com> <mailman.1904.1186984795.22759.python-list@python.org> <slrnfc0kqf.1us.horpner@FIAD06.norwich.edu> Message-ID: <1187028143.736566.175220@d55g2000hsg.googlegroups.com> On Aug 13, 10:37 am, Neil Cerutti <horp... at yahoo.com> wrote: > On 2007-08-13, Michael Bentley <mich... at jedimindworks.com> wrote: > > > > > On Aug 12, 2007, at 7:05 PM, Rohan wrote: > >> Can some one tell me how do I get colored text. Say when I want to > >> write something in a text file , how do I get it colored. > > > You can use ANSI escape codes --http://en.wikipedia.org/wiki/ > > ANSI_escape_code: > > Unfortunately, most versions of Windows of the last 7 years > (2000, XP, probably Vista) don't support ANSI escape codes well > enough to work with Python. > > -- > Neil Cerutti > We have to play hard for the full 40 minutes. 48? Oh, that's right. --Mikki > Moore Check out these recipes: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496901 From FJIFALSDGVAF at spammotel.com Mon Aug 20 07:37:02 2007 From: FJIFALSDGVAF at spammotel.com (Thomas Kellerer) Date: Mon, 20 Aug 2007 13:37:02 +0200 Subject: best GUI library for vector drawing program In-Reply-To: <sptic31137mal5t4cajdo6lvddo8spjkbp@4ax.com> References: <1187357244.883516.79840@j4g2000prf.googlegroups.com> <sptic31137mal5t4cajdo6lvddo8spjkbp@4ax.com> Message-ID: <5itcmuF3s08srU1@mid.individual.net> Roedy Green wrote: >> What would be the best cross-platform GUI library to use for a vector >> based CAD program ( something like Visio on Windows ) > I don't know about he best, but I have collected a list of them at > http://mindprod.com/jgloss/graph.html Roedy, you might want to add NetBeans' Graph library to the list. It is very similar to Eclipse's GEF http://graph.netbeans.org/ Thomas From kyosohma at gmail.com Wed Aug 8 13:36:51 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 08 Aug 2007 17:36:51 -0000 Subject: Launch file from Python In-Reply-To: <1186594137.971393.128780@57g2000hsv.googlegroups.com> References: <1186594137.971393.128780@57g2000hsv.googlegroups.com> Message-ID: <1186594611.490723.251870@m37g2000prh.googlegroups.com> On Aug 8, 12:28 pm, joc... at gmail.com wrote: > Good afternoon from someone who is trying to learn Python. > > I would like to launch an app from within a Python script. From the > examples I have found, I should be able to do this with os.system. > > I use this: > os.system("xplanet-1.2.0/xplanet.exe -fontsize 24 -label -target earth > -lat 33.65 -lon -84.42 -radius 40 -num_times 1 -tmpdir .") > This is copied directly from the .bat file that launches the xplanet > app. It works there. > > and get this: > 1 > > Can someone fill me in? Thanks. That's just the exit status or run status, if I recall correctly. I think 0 (i.e. False) means it didn't run properly and anything else is True, or ok. Something like that. Technically speaking, you should probably switch to using the subprocess module as it is replacing that os module's functionality: http://www.python.org/doc/2.4/lib/module-subprocess.html This thread also discusses it somewhat: http://www.velocityreviews.com/forums/t348777-python-doc-problem-example-ossystem.html Mike From ldo at geek-central.gen.new_zealand Thu Aug 23 04:19:00 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 23 Aug 2007 20:19:00 +1200 Subject: What Are These Import/From Statements about? References: <un_yi.34471$2v1.24183@newssvr14.news.prodigy.net> <mailman.123.1187804723.32294.python-list@python.org> <qb0zi.47332$Um6.34487@newssvr12.news.prodigy.net> <mailman.139.1187815633.32294.python-list@python.org> Message-ID: <fajfp0$ke0$1@lust.ihug.co.nz> In message <mailman.139.1187815633.32294.python-list at python.org>, Robert Kern wrote: > os.path. It's a sub-module of the standard os module. Actually, there are no such things as sub-modules (as you'll find out if you try to define one). What it really is is a variable in that module, which points to another module (e.g. posixpath). From Shawn at Milochik.com Mon Aug 20 11:01:37 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Mon, 20 Aug 2007 11:01:37 -0400 Subject: I Need help from all the group participants In-Reply-To: <fac7nj$ci9$1@localhost.localdomain> References: <fac7nj$ci9$1@localhost.localdomain> Message-ID: <2dc0c81b0708200801k63352a4gcea50e418bf465a@mail.gmail.com> "Please enter John's heart rate." "Please notify me immediately if John's heart rate drops below 60 or exceeds 100." From apt.shansen at gmail.com Fri Aug 17 19:26:19 2007 From: apt.shansen at gmail.com (Stephen Hansen) Date: Fri, 17 Aug 2007 16:26:19 -0700 Subject: wxPython in C++ app using wxWidgets In-Reply-To: <rIidnU2tiqY8vVvbnZ2dnUVZ8ternZ2d@eclipse.net.uk> References: <rIidnU2tiqY8vVvbnZ2dnUVZ8ternZ2d@eclipse.net.uk> Message-ID: <7a9c25c20708171626t3e6717afh3564564fbfab57d5@mail.gmail.com> On 8/17/07, Marcin Kalicinski <kalita at poczta.onet.pl> wrote: > > I have an application written in C++ that uses wxWidgets for GUI. I use > embedded Python for scripting inside of this application. I want to use > wxPython to add GUI to my scripts - because my C++ App uses wxWidgets I > thought it to be easy. The problem is that wxPython knows nothing about > wxApp/wxFrame objects created in my C++ application, and insists (by > giving > me asserts) that I create another wxApp object for wxPython inside my > scripts. Obviously, this is not what I want. I want the scripts to use the > same wxApp/wxFrame object that my C++ application already created. More > specifically, I want to create dialogs in wxPython that will have my > application wxFrame as parent. > I have nooo idea how to do it with pure wx, buut, you could try passing the handle for the parent via wx.Window.GetHandle() to Python, then create a reference to it in python via wx.Window_FromHWND(handle). Maybe! Its just a guess :) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070817/45b12e34/attachment.html> From max at alcyone.com Wed Aug 29 17:57:34 2007 From: max at alcyone.com (Erik Max Francis) Date: Wed, 29 Aug 2007 14:57:34 -0700 Subject: Haskell like (c:cs) syntax In-Reply-To: <rAbBi.13285$fb.8669@tornado.fastwebnet.it> References: <fb25uh$gl9$1@online.de> <mailman.85.1188339894.28954.python-list@python.org> <rAbBi.13285$fb.8669@tornado.fastwebnet.it> Message-ID: <yPidnai--qNTdkjbnZ2dnUVZ_hzinZ2d@speakeasy.net> Marco Mariani wrote: > Ricardo Ar?oz ha scritto: > >> L = ['one', 'two', 'three', 'four', 'five'] >> >> print L[0] # This would be 'head' >> print L[1:] # This would be 'tail' >> >> Caution : L[0] and L[1:] are COPIES of the head and tail of the list. > > This might surprise people who see L[1:] = [], since changing a copy is > not supposed to change the original. That's because slicing and assigning is not the same thing as slicing alone. Slicing and assigning mutates the sequence. Slicing alone returns a copy. >>> L = ['one', 'two', 'three', 'four', 'five'] >>> x = L[1:] # grab a slice >>> x[:] = [] # mutate it >>> x [] >>> L # original list is unchanged ['one', 'two', 'three', 'four', 'five'] -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis Eternity is very long, especially near the end. -- Woody Allen From martin at v.loewis.de Thu Aug 30 05:50:52 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 30 Aug 2007 11:50:52 +0200 Subject: gc.garbage In-Reply-To: <1188467173.708043.44800@w3g2000hsg.googlegroups.com> References: <1188467173.708043.44800@w3g2000hsg.googlegroups.com> Message-ID: <46D692FC.4030805@v.loewis.de> > gc.set_debug(gc.DEBUG_LEAK) > print gc.garbage > > --output:-- > [] > gc: uncollectable <Dog 0x56e10> > gc: uncollectable <Cat 0x56e30> > gc: uncollectable <dict 0x58270> > gc: uncollectable <dict 0x43e40> gc.garbage is filled only after these messages are printed, not before. You need to add an explicit call to gc.collect() if you want to see what uncollectable garbage you have. Regards, Martin From lionchao at gmail.com Wed Aug 22 16:13:30 2007 From: lionchao at gmail.com (Eric CHAO) Date: Wed, 22 Aug 2007 21:13:30 +0100 Subject: way to define static method In-Reply-To: <de6dc4a00708221234q63752cc2xc7ac1b64495ae95e@mail.gmail.com> References: <de6dc4a00708221234q63752cc2xc7ac1b64495ae95e@mail.gmail.com> Message-ID: <de6dc4a00708221313h36b328a5obd5d30f20ec081a7@mail.gmail.com> Thanks a lot. Because I found a solution about static method from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52304 And that's a little bit difficult to understand. # direct, naive approach -- doesn't work...: class Class1: def static1(name): print "Hello",name # ...but now, a call such as: Class1.static1("John") # will fail with a TypeError, as 'static1' has become # an unbound-method object, not a plain function. # This is easy to solve with a simple tiny wrapper: class Callable: def __init__(self, anycallable): self.__call__ = anycallable # toy-example usage: class Class2: def static2(name): print "Hi there",name static2 = Callable(static2) # now, a call such as: Class2.static2("Peter") # works just fine, and as-expected From bignose+hates-spam at benfinney.id.au Thu Aug 30 19:31:17 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 31 Aug 2007 09:31:17 +1000 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <mailman.135.1188474634.28954.python-list@python.org> <1188495863.242815.236900@o80g2000hse.googlegroups.com> Message-ID: <87bqcod2gq.fsf@benfinney.id.au> zzbbaadd at aol.com writes: > In my case of have done os.listdir() on two directories. I want to see > what files are in directory A that are not in directory B. You get that information unambiguously. It's an exceptional case, since there's no index to return, so it throws an exception. > I have used exceptions in other languages and only do so on logic > that should never happen. You're confusing "assert" ("this should always be true") with "exception" ("this is an exception to the the normal flow of this process"). An exception isn't "something that should never happen", it's something that is entirely possible and needs to be handled somehow. -- \ "Always do right. This will gratify some people, and astonish | `\ the rest." -- Mark Twain | _o__) | Ben Finney From __peter__ at web.de Tue Aug 21 10:17:44 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 21 Aug 2007 16:17:44 +0200 Subject: python 2.5.1 segfault, multithreading & dual core issue? References: <46caf049$0$239$e4fe514c@news.xs4all.nl> Message-ID: <faes69$vp1$03$1@news.t-online.com> Paul Sijben wrote: > I am running a multi-threaded python application in a dual core intel > running Ubuntu. > > I am using python 2.5.1 that I compiled myself. At random points I am > getting segmentation faults (sometimes indicating a duplicate free). > Below is the backtrace of the latest segfault. > > I am thinking this might be an issue related to the dual core CPU so I > am now running the app with affinity to one CPU to test this hypothesis. > > Where can I put such a bugreport? http://sourceforge.net/bugs/?group_id=5470 if you do it before August 23, when the bugtracker will be moved to bugs.python.org. Note that a thread-related bug causing a segfault has been reported today at http://sourceforge.net/tracker/index.php?func=detail&aid=1778376&group_id=5470&atid=105470 I could reproduce this one on my machine, though, so I'm sure that it has nothing to do with a dual core CPU. Peter From jjl at pobox.com Sun Aug 12 08:50:49 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 12 Aug 2007 12:50:49 GMT Subject: Seek the one billionth line in a file containing 3 billion lines. References: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> <7xzm12o7o7.fsf@ruckus.brouhaha.com> <1186555297.877273.40540@o61g2000hsh.googlegroups.com> <874pja70p5.fsf@benfinney.id.au> <mailman.1740.1186581536.22759.python-list@python.org> Message-ID: <87eji829xy.fsf@pobox.com> "Chris Mellon" <arkanes at gmail.com> writes: [...] > The minimum bounds for a line is at least one byte (the newline) and > maybe more, depending on your data. You can seek() forward the minimum > amount of bytes that (1 billion -1) lines will consume and save > yourself some wasted IO. But how do you know which line number you're on, then? John From wolf_tracks at invalid.com Sat Aug 18 11:40:43 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sat, 18 Aug 2007 15:40:43 GMT Subject: Python and Tkinter Programming--Expensive! In-Reply-To: <fa554f$vt$1@zinnia.noc.ucla.edu> References: <Xllxi.9066$3x.1781@newssvr25.news.prodigy.net> <fa554f$vt$1@zinnia.noc.ucla.edu> Message-ID: <%pExi.33896$2v1.26943@newssvr14.news.prodigy.net> Thanks. I'm borrowing it from a library and see the URL on the back of the book. <www.manning.com/grayson> James Stroud wrote: > W. Watson wrote: >> Why is the book in Subject (author is Grayson) so expensive? $100 on >> Amazon and $195 on ABE. Aren't there alternatives? > > > Read the fine print. Its available as an ebook for about $25.00 at > Manning. You can print out just the parts you need--or read it from your > iphone. > > James > -- Wayne Watson (Nevada City, CA) Web Page: <speckledwithStars.net> From nospam at invalid.com Sun Aug 19 14:21:28 2007 From: nospam at invalid.com (Jack) Date: Sun, 19 Aug 2007 11:21:28 -0700 Subject: Parser Generator? References: <abKdnVoQMu2o7FrbnZ2dnUVZ_gqdnZ2d@comcast.com> <_6mdnZxbdNKTVFrbnZ2dnUVZ_tqtnZ2d@comcast.com> <xHWxi.1073$vU4.633@nlpi068.nbdc.sbc.com> Message-ID: <fbadnTQA4qe6F1XbnZ2dnUVZ_s-pnZ2d@comcast.com> Thanks for the suggestion. I understand that more work is needed for natural language understanding. What I want to do is actually very simple - I pre-screen the user typed text. If it's a simple syntax my code understands, like, Weather in London, I'll redirect it to a weather site. Or, if it's "What is ... " I'll probably redirect it to wikipedia. Otherwise, I'll throw it to a search engine. So, extremelyl simple stuff ... "samwyse" <dejanews at email.com> wrote in message news:xHWxi.1073$vU4.633 at nlpi068.nbdc.sbc.com... > Jack wrote: >> Thanks for all the replies! >> >> SPARK looks promising. Its doc doesn't say if it handles unicode >> (CJK in particular) encoding though. >> >> Yapps also looks powerful: http://theory.stanford.edu/~amitp/yapps/ >> >> There's also PyGgy http://lava.net/~newsham/pyggy/ >> >> I may also give Antlr a try. >> >> If anyone has experiences using any of the parser generators with CJK >> languages, I'd be very interested in hearing that. > > I'm going to echo Tommy's reply. If you want to parse natural language, > conventional parsers are going to be worse than useless (because you'll > keep thinking, "Just one more tweak and this time it'll work for sure!"). > Instead, go look at what the interactive fiction community uses. They > analyse the statement in multiple passes, first picking out the verbs, > then the noun phrases. Some of their parsers can do on-the-fly > domain-specific spelling correction, etc, and all of them can ask the user > for clarification. (I'm currently cobbling together something similar for > pre-teen users.) From __peter__ at web.de Thu Aug 9 02:50:42 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 09 Aug 2007 08:50:42 +0200 Subject: How can I programmatically find the name of a method from within that method? References: <1186548312.672360.259100@q3g2000prf.googlegroups.com> <mailman.1727.1186549847.22759.python-list@python.org> <1186557384.845276.151630@i13g2000prf.googlegroups.com> <f9br51$e9a$01$1@news.t-online.com> <1186603550.882122.223340@d55g2000hsg.googlegroups.com> <f9d92f$8qe$02$1@news.t-online.com> <1186616506.072708.3310@g4g2000hsf.googlegroups.com> Message-ID: <f9edg2$ceu$02$1@news.t-online.com> Tony wrote: > On Aug 8, 9:28 pm, Peter Otten <__pete... at web.de> wrote: > >> No, just wrong. >> >> >> class A: >> >> ... def alpha(self): return dir(self)[-2] >> ... def gamma(self): return dir(self)[-1] >> ...>>> a = A() >> >>> a.alpha(), a.gamma() >> ('alpha', 'gamma') >> >>> a.beta = 42 >> >>> a.alpha(), a.gamma() >> >> ('beta', 'gamma') >> >> Peter > Only wrong if the function is only to write its own name. if it does > something else as well, seems to work: > > class a: > > ????????def square(self, x): > ????????????????print 'executing:', dir(self)[-1] > ????????????????print x*x > ????????def cube(self, x): > ????????????????print 'executing:',?????dir(self)[-2] > ????????????????print x*x*x > > b=a() > > b.cube(4),b.square(2) > b.c =4 > b.cube(3), b.cube(2) You mean b.cube(3), b.square(2) > executing: cube > 64 > executing: square > 4 > executing: cube > 27 > executing: cube > 8 Yeah, cargo cult programming, I love it. dir() sorts attribute names alphabetically. Therefore the tail of the list you are accessing will only be altered if you choose a name > min(other_names), i. e. a name that comes after "cube" in the alphabet. Try setting b.root = 42 if you don't believe me. Peter From ddyche at bigbluenetworks.com Wed Aug 29 00:23:53 2007 From: ddyche at bigbluenetworks.com (ddyche) Date: Wed, 29 Aug 2007 00:23:53 -0400 Subject: test Message-ID: <46D4F4D9.5030208@bigbluenetworks.com> From jstroud at mbi.ucla.edu Sat Aug 4 00:06:23 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 03 Aug 2007 21:06:23 -0700 Subject: How to pass a reference to the current module In-Reply-To: <7xtzrg3vof.fsf@ruckus.brouhaha.com> References: <f90gsg$ek4$1@zinnia.noc.ucla.edu> <pan.2007.08.04.01.46.50.985228@REMOVE.THIS.cybersource.com.au> <f90lon$av5$1@daisy.noc.ucla.edu> <7xtzrg3vof.fsf@ruckus.brouhaha.com> Message-ID: <f90tvv$nt7$2@zinnia.noc.ucla.edu> Paul Rubin wrote: > James Stroud <jstroud at mbi.ucla.edu> writes: > >> Module Behavior >> ============== ==================================================== >> UserDefined1 Imports FunctionUser >> ThirdParty Contains User Functions (May be ==UserDefined1) >> FunctionUser do_something_with() and/or get_function_from_name() >> >>So the name-to-function mapping is done in FunctionUser but the >>function is actually defined in UserDefined1 (or ThirdParty if >>ThirdParty is different than UserDefined1). > > > I'm still completely confused. Does FunctionUser know what module the > user functions are supposed to come from? Could you give an example > of what you want the actual contents of those 3 modules to look like? > E.g.: > > UserDefined1.py: > import FunctionUser > > def foo(x): > print x+3 > > FunctionUser.py: > def do_something_with (module, funcname, *args, **kw): > func = getattr(module, funcname) > func (*args, **kw) > > main.py: > import UserDefined1, FunctionUser > > # the following should print 10 > FunctionUser.do_something_with(UserDefined1, 'foo', 7) > > I don't think the above is quite what you want, but is it somewhere > close? Its very close. However, there is the possibiltiy that main.py and UserDefined1.py are the same module. In such a case I'm guessing that I need to resort to the gymnastics of frame inspection I mentioned earlier. The problem is when this combination of possibilities exists: 1. main.py is named without the .py (e.g. `main`) as would be the convention for "programs"), and is not a true python module as a result--perhaps python has a mechanism for importing such files? 2. foo is defined in `main` Possibility two (even when it is a properly named module) sets the stage for a circular import, but I believe in python this is not entirely worrisome. However, the combination above makes it difficult to pass a reference to the `main` namespace without some sort of introspection. Ideally, I would prefer to not require the user to provide some mapping as it detracts from the convenience of the API. For example: from UserDefined1 import some_function def foo(): [etc.] def doit(): [etc.] mapping = { 'foo' : foo, 'doit' : doit, 'some_function' : some_function } The idea would be that the above mapping would be specified in the configuration file: [foo] param1 = float param2 = 4 [option1] __module__ = 'UserDefined1' __function__ = 'doit' param1 = str param2 = 30.0 [doit] param1 = float param2 = float [etc.] James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From luismgz at gmail.com Sun Aug 12 20:54:11 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 13 Aug 2007 00:54:11 -0000 Subject: python + XUL In-Reply-To: <46BEA6FC.9050907@web.de> References: <1186894004.913359.132000@b79g2000hse.googlegroups.com> <46BEA6FC.9050907@web.de> Message-ID: <1186966451.081184.63490@r34g2000hsd.googlegroups.com> On Aug 12, 3:21 am, Stefan Behnel <stefan.behnel-n05... at web.de> wrote: > Madhu Alagu wrote: > > Hi > > > Python + XUL Success Stories > > > Thanks > > > Madhu Alagu > > Any chance you forgot to ask a question? > > Stefan My telepatic powers tell me that this means: "I don't really feel like googling, so just give me the info, ok?" From steve at holdenweb.com Fri Aug 31 14:26:53 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 31 Aug 2007 14:26:53 -0400 Subject: list index() In-Reply-To: <1i3pcju.j2fvej1056nqpN%aleax@mac.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <mailman.135.1188474634.28954.python-list@python.org> <1188495863.242815.236900@o80g2000hse.googlegroups.com> <1i3ob5k.dm3jmoqx1z68N%aleax@mac.com> <1188530557.550119.27260@q3g2000prf.googlegroups.com> <1i3pcju.j2fvej1056nqpN%aleax@mac.com> Message-ID: <fb9mhg$mf3$2@sea.gmane.org> Alex Martelli wrote: > mensanator at aol.com <mensanator at aol.com> wrote: > ... >> Why wouldn't "the one obvious way" be: >> >> def inAnotB(A, B): >> inA = set(os.listdir(A)) >> inBs = set(os.listdir(B)) >> return inA.difference(inBs) > > If you want a set as the result, that's one possibility (although > possibly a bit wasteful as you're building one more set than necessary); > I read the original request as implying a sorted list result is wanted, > just like os.listdir returns (possibly sorted in case-independent order > depending on the underlying filesystem). There's no real added value in > destroying inA's ordering by making it a set, when the list > comprehension just "naturally keeps" its ordering. > As I had reason to point out in another thread only recently, os.listdir() makes no promises about the filename ordering. Nevertheless I agree with you that the list comprehension method is the obvious way to solve the problem, and the set optimization is just that. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From steve at shrogers.com Thu Aug 9 08:25:52 2007 From: steve at shrogers.com (Steve) Date: Thu, 09 Aug 2007 05:25:52 -0700 Subject: (Re)announcing APL 2007 In-Reply-To: <1186406430.744134.298400@x35g2000prf.googlegroups.com> References: <5hnkb3F3hus4jU1@mid.individual.net> <1186406430.744134.298400@x35g2000prf.googlegroups.com> Message-ID: <1186662352.731056.47190@q3g2000prf.googlegroups.com> On Aug 6, 7:20 am, Paul Mansour <p... at carlislegroup.com> wrote: > On Aug 5, 11:54 pm, Mike Kent <mk... at acm.org> wrote: > > > APL 2007 conference on Array Programming > > > co-located with OOPSLA 2007 > > > Sponsor: ACM SIGAPL > > > Where: Montreal > > > When: October 21 (tutorials) > > October 22/23 (main conference program) > > APL2007 Roll Call: Is anyone going to this? > > I'm thinking about going, but I don't want to the only one to show up, > as in San Diego. I'm going. From grante at visi.com Tue Aug 28 22:03:25 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 29 Aug 2007 02:03:25 -0000 Subject: Gmane's been quiet ... References: <mailman.88.1188343014.28954.python-list@python.org> Message-ID: <13d9kvdm9tcqtae@corp.supernews.com> On 2007-08-28, Steve Holden <steve at holdenweb.com> wrote: > ... so I was wondering if it's just me who hasn't seen any postings today? AFAICT, it's been dead for a day or so. I posted something to the py2exe list via the gmane NNTP server early this after noon and it never showed up. I don't think I've seen any other new articles today in any of the 20 or so lists I watch via gmane's NNTP server. The server appears to be fine (it's serving up headers and ariticles like always), but the "news feed" seems to be down. -- Grant Edwards grante Yow! Yow! I just went at below the poverty line! visi.com From nick at craig-wood.com Wed Aug 22 06:30:06 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 22 Aug 2007 05:30:06 -0500 Subject: File Read Cache - How to purge? References: <1187669203.698637.81990@i38g2000prf.googlegroups.com> <87veb9xb7y.fsf@mulj.homelinux.net> <slrnfcm1hv.4r1.nick@irishsea.home.craig-wood.com> <87ir781afk.fsf@mulj.homelinux.net> Message-ID: <slrnfco315.k3i.nick@irishsea.home.craig-wood.com> Hrvoje Niksic <hniksic at xemacs.org> wrote: > Nick Craig-Wood <nick at craig-wood.com> writes: > > > If you are running linux > 2.6.18 then you can use > > /proc/sys/vm/drop_caches for exactly that purpose. > > > > http://www.linuxinsight.com/proc_sys_vm_drop_caches.html > > That URL claims that you need to run "sync" before dropping the cache, > and so do other resources. I wonder if that means that dropping the > cache is unsafe on a running system. It isn't unsafe, the OS just can't drop pages which haven't been synced to disk so you won't get all the pages dropped unless you sync first. -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From kyosohma at gmail.com Thu Aug 2 15:50:40 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 02 Aug 2007 19:50:40 -0000 Subject: Error subclassing datetime.date and pickling In-Reply-To: <mailman.1514.1186071067.22759.python-list@python.org> References: <mailman.1514.1186071067.22759.python-list@python.org> Message-ID: <1186084240.922922.11870@i13g2000prf.googlegroups.com> On Aug 2, 11:02 am, Mike Rooney <m... at qvii.com> wrote: > Hi everyone, this is my first post to this list. I am trying to create a > subclass of datetime.date and pickle it, but I get errors on loading it > back. I have created a VERY simple demo of this: > > import datetime > > class MyDate(datetime.date): > """ > This should be pickleable. > > >>> md = MyDate(2007, 1, 6) > >>> import pickle > >>> pickle.dump(md, open("test.pickle", 'w')) > >>> mdp = pickle.load(open("test.pickle")) > >>> import os; os.remove("test.pickle") > """ > def __init__(self, y, m, d): > datetime.date.__init__(self, y, m, d) > > if __name__ == "__main__": > import doctest > doctest.testmod() > > The traceback that occurs is: > > Traceback (most recent call last): > File "C:\Python25\lib\doctest.py", line 1212, in __run > compileflags, 1) in test.globs > File "<doctest __main__.MyDate[3]>", line 1, in <module> > mdp = pickle.load(open("test.pickle")) > File "C:\Python25\lib\pickle.py", line 1370, in load > return Unpickler(file).load() > File "C:\Python25\lib\pickle.py", line 858, in load > dispatch[key](self) > File "C:\Python25\lib\pickle.py", line 1133, in load_red > value = func(*args) > TypeError: __init__() takes exactly 4 arguments (2 given) > > I have found a few relating issues: > -https://sourceforge.net/tracker/?func=detail&atid=105470&aid=952807&g... > -http://sourceforge.net/tracker/index.php?func=detail&aid=720908&group... > > But these are both rather old and are marked as fixed. I am running > Python 2.5.1 on Windows XP SP2. Any help here would be greatly appreciated! > > - Mike I've never used pickle or shelve in my applications...yet. I tried separating out the class into its own module and importing it, as pickling classes is supposed to be tricky. I looked through all my Python books and what few examples I found looked just like your code. I did find this article which might be helpful to you more than it was to me: http://www.ibm.com/developerworks/library/l-pypers.html >From what I can tell, when your object gets unpickled it only passes 2 arguments to the class instead of the 4 that were supposed to be pickled. If you change the number of arguments that the class accepts and re-pickle it, you'll see that the unpickle object traceback corresponds. It's very weird. Sorry I didn't have some slam-bang awesome idea. Mike From JYOUNG79 at kc.rr.com Fri Aug 24 14:20:24 2007 From: JYOUNG79 at kc.rr.com (JYOUNG79 at kc.rr.com) Date: Fri, 24 Aug 2007 13:20:24 -0500 Subject: question Message-ID: <c54792253f115.3f115c5479225@rdc-kc.rr.com> Still trying to learn Python and was hoping some of you might be able to give me some advice on my code below. It works but I'm wondering if there's more efficient ways of doing this than the way I've done it. The first step is I have to loop thru nested folders and find all files that start with "LOGO". So I use Unix's 'find' and write all the paths out to a text file like so: find ~/Desktop/logoFiles/ -type f -iname "LOGO*" > ~/Desktop/logo_stuff/paths.txt" Next, I use Python (code below) to look thru each paragraph of that file (paths.txt). While looping thru each paragraph, I want to first make sure that the folder name that the file is in is a number. For example, if it found file 'LOGO9012', then I'd want to make sure the folder name that this file was in was a number (~/Desktop/ logoFiles/12/LOGO9012). If that's ok then I grab the number off the file name. If there's not a number in the file name then I ignore it. I then create a dictionary that has a key which equals the number I grabbed from the file name and then the value contains the full file path (that I grabbed out of the text file) followed by a delimiter (<::>) followed by 'LOGO' and the number I got from the file name (making sure to keep any leading zeroes if they were there originally). Finally, I sort the keys in numerical order and save out a file with all the appropriate info from my dictionary (which will be a list of paths followed by a delimiter and file name). Here's an example of what this new file might contain: /Users/jyoung1/Desktop/logoFiles/02/Logo002<::>LOGO002 /Users/jyoung1/Desktop/logoFiles/02/LOGO102<::>LOGO102 /Users/jyoung1/Desktop/logoFiles/02/LOGO302<::>LOGO302 /Users/jyoung1/Desktop/logoFiles/9/LOGO462.2PMS<::>LOGO462 Anyway, if anyone has time to look at this I'd appreciate your thoughts. Thanks! Jay #!/usr/bin/python import re dList = {} sortedList = "" pathFile = open("~/Desktop/logo_stuff/paths.txt", "r") for x in pathFile: if len(re.findall(r"^\d+$", x.split("/")[-2])) > 0: #make sure folder name is a number n = re.findall(r"\d+", x.split("/")[-1]) #Grab number off file name if len(n) > 0: dList[int(n[0])] = x[:-1] + "<::>LOGO" + n[0] + "\n" pathFile.close() keyList = dList.keys() keyList.sort() for x in keyList: sortedList += dList[x] newFile = open("~/Desktop/logo_stuff/sortedPaths.txt", "w") newFile.write(sortedList) newFile.close() From tleeuwenburg at gmail.com Thu Aug 30 15:31:29 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: Thu, 30 Aug 2007 19:31:29 -0000 Subject: Trouble using sys.settrace Message-ID: <1188502289.484027.322520@z24g2000prh.googlegroups.com> The code below produces no output. I would expect to see: tracing... tracing... tracing... tracing... tracing... I was wondering if anyone had any experience with this. ================================= import sys def mytrace(frame, event, arg): print "tracing..." sys.settrace(mytrace) def foo(): for i in range(5): print i foo() From toby at tobiah.org Thu Aug 23 15:27:10 2007 From: toby at tobiah.org (Tobiah) Date: Thu, 23 Aug 2007 12:27:10 -0700 Subject: Using Regular Expresions to change .htm to .php in files In-Reply-To: <1187896823.843419.53220@q3g2000prf.googlegroups.com> References: <1187896823.843419.53220@q3g2000prf.googlegroups.com> Message-ID: <46cdd386$0$27392$88260bb3@free.teranews.com> sebzzz at gmail.com wrote: > Hi, > > I have a bunch of files that have changed from standard htm files to > php files but all the links inside the site are now broken because > they point to the .htm files while they are now .php files. > > Does anyone have an idea about how to do a simple script that changes > each .htm in a given file to a .php > > Thanks a lot in advance > #!/bin/bash for each in *.php; do sed "s/.htm/.php/g" < $each > /tmp/$$ mv /tmp/$$ $each done -- Posted via a free Usenet account from http://www.teranews.com From rvtol+news at isolution.nl Sat Aug 11 11:54:59 2007 From: rvtol+news at isolution.nl (Dr.Ruud) Date: Sat, 11 Aug 2007 17:54:59 +0200 Subject: I am giving up perl because of assholes on clpm -- switching to Python References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> <1186242055.553090.112680@m37g2000prh.googlegroups.com> Message-ID: <f9ktdc.1ho.1@news.isolution.nl> grocery_stocker schreef: > In the beginning there was Mathematics > And all was good > Then one day God said "Let there be the Lambda Calculus" > And hence the Lambda Calculus was born. > However, God felt the the Lambda Calculus needed a mate > So god said "Let there be Lisp" > And thus, Lisp was born. > > As the years went on, god became depressed by how impure the Lisp had > become. > For from the Lisp, came Emacs Lisp, Java, Perl, Ruby, and Python. http://xkcd.com/224/ -- Affijn, Ruud "Gewoon is een tijger." From bdesth.quelquechose at free.quelquepart.fr Tue Aug 7 14:04:46 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 07 Aug 2007 20:04:46 +0200 Subject: check if regeular expression has results In-Reply-To: <slrnfbm4vk.194.horpner@FIAD06.norwich.edu> References: <1186664302.050036.302670@g4g2000hsf.googlegroups.com> <slrnfbm4vk.194.horpner@FIAD06.norwich.edu> Message-ID: <46bb6ba1$0$424$426a74cc@news.free.fr> Neil Cerutti a ?crit : > On 2007-08-09, shahargs at gmail.com <shahargs at gmail.com> wrote: > >>Hi, >>I'm looking for the best way to check if regular expression return >>true (it's mean - there is a match). for example, i want "if" that >>check if this regular expression: .*born.*to.* has a match. >> >>What's the way to do that simply? > > > Newgroups are a poor substitute for the docs. For one thing, > newsgroups sometimes contain cranky people who say, "RTFM!" The > docs will never do that. > And for completness, here are the relevant parts of TheFineManual(tm): http://docs.python.org/lib/module-re.html http://www.amk.ca/python/howto/regex/ From johnmasters at oxtedonline.net Wed Aug 1 18:42:19 2007 From: johnmasters at oxtedonline.net (John K Masters) Date: Wed, 1 Aug 2007 23:42:19 +0100 Subject: Wing IDE for Python v. 3.0 beta1 released In-Reply-To: <f8r147$rvm$1@sea.gmane.org> References: <46AF8ED7.2070206@wingware.com> <20070801212840.GA25065@spookie1.spookiegate> <f8quug$m7j$1@sea.gmane.org> <496954360708011453h2a68dee4x48dcb15bb25ea717@mail.gmail.com> <f8r0du$qhn$1@sea.gmane.org> <f8r147$rvm$1@sea.gmane.org> Message-ID: <20070801224219.GD25065@spookie1.spookiegate> On 18:23 Wed 01 Aug , Steve Holden wrote: > Joshua J. Kugler wrote: > > On Wednesday 01 August 2007 13:53, Robert Dailey wrote: > >> He's secretly an employee of Wing IDE in disguise!!! > > > > Sorry to destroy your conspiracy theories, but no, I've never been employed > > by Wing IDE in any fashion, nor have I ever received any monetary > > compensation from them in any form. Just a satisfied user. That's all. > > > > j > > > Me too, and I have to say the response I have had to all my technical > support requests has been first-class. Maybe they are busy because > they're in beta? I know they aren't the largest company, but they can > stand comparison with most when it comes to support. > > I can't think of any other products I use where you can contact the > support team from right inside the software. And get answers without > paying per-incident support fees! > > regards > Steve > -- I am happy to hear that you have had a good experience with wingide and I wish I could say the same as I have found the product to be excellent as far as the concept goes but lacking in the implementation. To suggest that, because the autocompletion worked on one method of a module and not on another was because I had not configured the PYTHONPATH properly is at least insulting. Regards, John -- War is God's way of teaching Americans geography uggest that mbrose Bierce (1842 - 1914) From bignose+hates-spam at benfinney.id.au Tue Aug 7 20:13:42 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 08 Aug 2007 10:13:42 +1000 Subject: ensuring GNU readline isn't used References: <mailman.1711.1186491401.22759.python-list@python.org> Message-ID: <87k5s67uix.fsf@benfinney.id.au> Josh Paetzel <josh at tcbug.org> writes: > Is there a way to ensure that GNU readline isn't used (even though > support may have been compiled in?). I'm experiencing a licensing > problem Note that the GPL (the license terms of readline) is like any other valid copyright license in that it only restricts acts covered by copyright. You have no responsibility to prevent others from using a GPL-covered work. Anyone may use a GPL-covered work they receive for any purpose without further permission; nobody needs a copyright license for that (despite what some copyright holders might prefer). Copyright covers acts of copying and distribution, so you *do* need license to do those things with someone's work. > but my code is proprietary That's unfortunate. I hope you can fix that. > and hence, if cmd uses readline, I can't use cmd. Not true; you can derive from and redistribute cmd, so long as you comply with the license on cmd. -- \ "What I have to do is see, at any rate, that I do not lend | `\ myself to the wrong which I condemn." -- Henry Thoreau, _Civil | _o__) Disobedience_ | Ben Finney From kyoguan at gmail.com Thu Aug 16 22:46:01 2007 From: kyoguan at gmail.com (kyo guan) Date: Fri, 17 Aug 2007 10:46:01 +0800 Subject: why psyco using more memery in liunx? Message-ID: <005d01c7e078$c13d0ed0$811ba8c0@kyom> Hi all: When you import psyco in python2.5, you can see the memery grow up near 40MB in linux. but the same version python and psyco, is only grow up 1MB under windows. kyo From B.Ogryczak at gmail.com Fri Aug 10 07:08:31 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: Fri, 10 Aug 2007 11:08:31 -0000 Subject: programmatically define a new variable on the fly In-Reply-To: <1186697500.024593.303820@x35g2000prf.googlegroups.com> References: <1186697500.024593.303820@x35g2000prf.googlegroups.com> Message-ID: <1186744111.800625.232730@x40g2000prg.googlegroups.com> On 10 ago, 00:11, Lee Sander <lesa... at gmail.com> wrote: > Hi, > > I would like to define a new variable which is not predefined by me. > For example, > I want to create an array called "X%s" where "%s" is to be determined > based on the data I am processing. So, for example, if I the file > I'm reading has > g 99 > on the first line, I want to create a new variable called "Xg" whose > length > is 99. > I tried eval("Xg=[0]*99") but that did not work. >>> letter = 'g' >>> import __main__ >>> setattr(__main__,'X%s'%letter,[0]*99) >>> Xg [0, 0, 0 ... Anyway, I don?t see the point in this. Why don?t you just use something like X['g'] instead? From skip at pobox.com Thu Aug 2 22:39:23 2007 From: skip at pobox.com (Skip Montanaro) Date: Fri, 3 Aug 2007 02:39:23 +0000 (UTC) Subject: =?utf-8?b?X19jYWxsX18=?= considered harmful or indispensable? References: <mailman.1527.1186079415.22759.python-list@python.org> <46b24200$0$19638$426a74cc@news.free.fr> Message-ID: <loom.20070803T042845-57@post.gmane.org> > > In this case there was a bug. Depending on inputs, sometimes obj > > initialized to a class, sometimes an instance of that class. (I fixed > > that too while I was at it.) The problem was that the use of __call__ > > obscured the underlying bug by making the instance as well as the class > > callable. > I don't quite get the point here. A concrete example would be welcome. The bug went something like this: obj = some.default_class ... if some_other_rare_condition_met: ... several lines ... obj = some.other_class() ... Later, x = obj() x(...) The bug was that in the rare condition branch obj should have been assigned just the class. It shouldn't have been instantiated there. Having the instance be callable (for no obvious reason that I could tell) misdirected my attention because the x = obj() generally succeeded and I thought the problem was with the call to x(...). If the instance wasn't callable it would have been clear at "x = obj()" that I was trying to call an instance. Thanks for the various bits of feedback. From the responses I've seen, it seems that if one is tempted to use __call__ they should consider it before just sprinkling it in their code. The places where people seem to use it generally seem not to be in run-of-the-mill code. In the common case it seems to me there are generally better ways to do things. (I did like the StoredProcedure mirroring stuff someone posted. That does look kind of cool.) Skip From horpner at yahoo.com Wed Aug 1 11:11:18 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 01 Aug 2007 15:11:18 GMT Subject: Extending doctest Message-ID: <slrnfb18rk.lo.horpner@FIAD06.norwich.edu> One of my current tests looks like this (the program is an interpreter for a scheme-like language): >>> result = parse_op('(with (b (newbox 5))' ... ' (seqn (setbox b 1)' ... ' (setbox b 2)' ... ' (setbox b 3)' ... ' b))').interp(EmptyEnv(), EmptyStore()) >>> result #doctest: +ELLIPSIS (<Box ...>, ~...: <Num 3> ~) >>> result[0].location == result[1].location True The memrory location that the box refers to must match the actual location in storage. Currently, the doctest stinks because it depends on internal details of my implementation. Is there a doctest feature that will allow me to stipulate that one thing in a result is arbitrary, but identical to another thing in that result? -- Neil Cerutti Trespassers will be prosecuted to the full extent of the law --sign at Sisters of Mercy Nunnery From carl at 29degrees.co.uk Tue Aug 28 13:35:19 2007 From: carl at 29degrees.co.uk (Carl Drinkwater | 29degrees) Date: Tue, 28 Aug 2007 18:35:19 +0100 Subject: National grid to lat long conversion In-Reply-To: <1188295755.877801.217710@r29g2000hsg.googlegroups.com> References: <1188295755.877801.217710@r29g2000hsg.googlegroups.com> Message-ID: <E736173B-9678-44B3-86E5-0D71031445F9@29degrees.co.uk> > I have a load of British National Grid references that I want to > convert to decimal degrees so I can create a google KML file. Does > anyone know of a module to do this? I should probably have added that you can get a number of the variables you start off with from : http://www.ordnancesurvey.co.uk/oswebsite/gps/information/ coordinatesystemsinfo/guidecontents/guidea.html and http://www.ordnancesurvey.co.uk/oswebsite/gps/information/ coordinatesystemsinfo/guidecontents/index.html might be useful to read around the subject. It might look complex, but don't let it put you off. Also, you can get JavaScript code to do just this from the URL below, which would be a good starting point. http://www.movable-type.co.uk/scripts/latlong-gridref.html Regards, Carl. From Dominic at PLEASEASK.co.uk Thu Aug 9 09:59:07 2007 From: Dominic at PLEASEASK.co.uk (special_dragonfly) Date: Thu, 9 Aug 2007 14:59:07 +0100 Subject: Help with Dictionaries and Classes requested please. References: <46bacae3$0$89254$7b0f0fd3@mistral.news.newnet.co.uk> <46bacf1b$0$54289$7b0f0fd3@mistral.news.newnet.co.uk> <87ejic6dkw.fsf@benfinney.id.au> Message-ID: <46bb19e2$0$9835$7b0f0fd3@mistral.news.newnet.co.uk> "Ben Finney" <bignose+hates-spam at benfinney.id.au> wrote in message news:87ejic6dkw.fsf at benfinney.id.au... > "special_dragonfly" <Dominic at PLEASEASK.co.uk> writes: > >> I've managed to solve the problem, I really was just being a >> dunce. > > Doubtful; but at this stage we can't tell, because we still don't know > what it is you're actually trying to *do*. > >> Here's how incase anyone is wondering: >> >> class MyClass: >> def __init__(self): >> name="" >> dict={} >> dict[0]=[] >> dict[0].append(MyClass()) >> dict[0][0].name="Hello" >> print dict[0][0].name > > It's not clear why you are using the value 0 for a dictionary key > here; nor why you're assigning an attribute to an object after > creating the object. Neither of them are errors, but without context > it's hard to know what advice to give. > The 0 for a key is just an example. The code I actually have would be just as meaningful at the end of the day. I could have changed MyClass for class Animals(object): def __init__(self, name="", type="", age=""): self.name=name self.type=type self.age=age dict={'Mouse':[Animals('George','long eared',20)]} dict['Mouse'].append(Animals('Benny','hairy',30)) dict['Cat']=[Animals('Inigo Montoya','spanish',10)] and Neil, Bruno has the right idea of what I was trying to do. However, your code came in handy still as I used your code elsewhere.see below. def EnterDictionary(FieldsDictionary,key,data): for i in range(0,int(data[6:])): line=myfile.readline() line=line.strip() line=line[6:-1] if key in FieldsDictionary: FieldsDictionary[key].append(FieldClass(*line.split(","))) else: FieldsDictionary[key]=[FieldClass(*line.split(","))] I'd like to thank you all for your patience with me whilst I've asked some really beginner-like questions. I hope I haven't annoyed you all too much... In future I would ask however, if it's a really stupid question and you feel that the answer can be found either by searching google (because in some cases I don't know what to search for), or in one of the O'reilly books, just say. In either case, if you could refer me to the search term to use or the book to read I'd be grateful. Dominic From tazmaster at rocketmail.com Sat Aug 4 22:21:17 2007 From: tazmaster at rocketmail.com (Jim Langston) Date: Sat, 4 Aug 2007 19:21:17 -0700 Subject: Formatting Results so that They Can be Nicely Imported into a Spreadsheet. References: <1186270555.514649.311280@d30g2000prg.googlegroups.com> <1186278638.931477.39760@z24g2000prh.googlegroups.com> Message-ID: <Avati.40$Tu1.6@newsfe12.lga> <mensanator at aol.com> wrote in message news:1186278638.931477.39760 at z24g2000prh.googlegroups.com... > On Aug 4, 6:35?pm, SMERSH009 <SMERSH0... at gmail.com> wrote: >> Hi All. >> Let's say I have some badly formatted text called doc: >> >> doc= >> """ >> friendid >> Female >> >> 23 years old >> >> Los Gatos >> >> United States >> friendid >> Male >> >> 24 years old >> >> San Francisco, California >> >> United States >> """ >> >> How would I get these results to be displayed in a format similar to: >> friendid;Female;23 years old;Los Gatos;United States >> friendid;Male; 24 years old;San Francisco, California;United States >> >> The latter is a lot easier to organize and can be quickly imported >> into Excel's column format. >> >> Thanks Much, >> Sam > > d = doc.split('\n') > > f = [i.split() for i in d if i] > > g = [' '.join(i) for i in f] > > rec = [] > temprec = [] > for i in g: > if i: > if i == 'friendid': > rec.append(temprec) > temprec = [i] > else: > temprec.append(i) > rec.append(temprec) > > output = [';'.join(i) for i in rec if i] > > for i in output: print i > > ## friendid;Female;23 years old;Los Gatos;United States > ## friendid;Male;24 years old;San Francisco, California;United States also, I would suggest you use CSV format. CSV stands for "Comma Seperated Variable" and Excel can load such a sheet directly. Instead of seperating using ; seperate using , Of course, this provides a problem when there is a , in a string. Resolution is to quote the string. Being such, you can just go ahead and quote all strings. So you would want the output to be: "friendid","Female","23 years old","Los Gatos","United States" "friendid","Male","24 years old","San Francisco, California","United States" Numbers should not be quoted if you wish to treat them as numeric and not text. From hniksic at xemacs.org Wed Aug 22 07:58:08 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 22 Aug 2007 13:58:08 +0200 Subject: File Read Cache - How to purge? References: <1187669203.698637.81990@i38g2000prf.googlegroups.com> <87veb9xb7y.fsf@mulj.homelinux.net> <slrnfcm1hv.4r1.nick@irishsea.home.craig-wood.com> <87ir781afk.fsf@mulj.homelinux.net> <slrnfco315.k3i.nick@irishsea.home.craig-wood.com> Message-ID: <874pirpyr3.fsf@mulj.homelinux.net> Nick Craig-Wood <nick at craig-wood.com> writes: >> > http://www.linuxinsight.com/proc_sys_vm_drop_caches.html >> >> That URL claims that you need to run "sync" before dropping the cache, >> and so do other resources. I wonder if that means that dropping the >> cache is unsafe on a running system. > > It isn't unsafe, the OS just can't drop pages which haven't been > synced to disk so you won't get all the pages dropped unless you > sync first. Thanks for the clarification. From google at tyeon.com Thu Aug 30 13:29:24 2007 From: google at tyeon.com (T) Date: Thu, 30 Aug 2007 10:29:24 -0700 Subject: How to use os.putenv() ? In-Reply-To: <1188438641.676443.121510@x35g2000prf.googlegroups.com> References: <1188436871.549201.315170@g4g2000hsf.googlegroups.com> <1188438641.676443.121510@x35g2000prf.googlegroups.com> Message-ID: <1188494964.539169.104180@d55g2000hsg.googlegroups.com> On Aug 29, 9:50 pm, Graham Dumpleton <Graham.Dumple... at gmail.com> wrote: > On Aug 30, 11:21 am, goo... at tyeon.com wrote: > > > > > >>> import os > > > >>> os.environ['PATH'] > > > 'C:\\WINNT\\system32;C:\\WINNT;C:\\WINNT\\System32\\Wbem;%C:\\WINNT%\ > > \system32;%C:\\WINNT%;%C:\\WINNT%\\System32\\Wbem' > > > >>> os.putenv('PATH', 'C:\\WINNT\\system32') > > > >>> os.environ['PATH'] > > > 'C:\\WINNT\\system32;C:\\WINNT;C:\\WINNT\\System32\\Wbem;%C:\\WINNT%\ > > \system32;%C:\\WINNT%;%C:\\WINNT%\\System32\\Wbem' > > > What am I doing wrong? How do I change the value of an environment > > variable? > > What you are missing is that os.environ is only populated from the > global process environment at process startup. > > If you update os.environ the changes will be pushed into the global > process environment as well. But if you use os.putenv() instead, > bypassing os.environ, the changes will not show in os.environ. > > To confirm that the global process environment is being updated, use > os.getenv(). > > Graham Can you tell me what I am still missing please? >>> import os >>> >>> os.getenv('PATH') 'C:\\WINNT\\system32;C:\\WINNT;C:\\WINNT\\System32\\Wbem;%C:\\WINNT%\ \system32;%C:\\WINNT%;%C:\\WINNT%\\System32\\Wbem' >>> >>> os.putenv('PATH', 'C:\\WINNT\\system32') >>> >>> os.getenv('PATH') 'C:\\WINNT\\system32;C:\\WINNT;C:\\WINNT\\System32\\Wbem;%C:\\WINNT%\ \system32;%C:\\WINNT%;%C:\\WINNT%\\System32\\Wbem' >>> From prey at cesga.es Thu Aug 30 07:46:47 2007 From: prey at cesga.es (Pablo Rey) Date: Thu, 30 Aug 2007 13:46:47 +0200 Subject: SAXParseException: not well-formed (invalid token) Message-ID: <fb6alc$pfj$1@news.cesga.es> Dear Colleagues, I am getting the following error with a XML page: > File "/home/prey/RAL-CESGA/bin/voms2users/voms2users.py", line 69, in getItems > d = minidom.parseString(xml.read()) > File "/usr/lib/python2.2/site-packages/_xmlplus/dom/minidom.py", line 967, in parseString > return _doparse(pulldom.parseString, args, kwargs) > File "/usr/lib/python2.2/site-packages/_xmlplus/dom/minidom.py", line 954, in _doparse > toktype, rootNode = events.getEvent() > File "/usr/lib/python2.2/site-packages/_xmlplus/dom/pulldom.py", line 265, in getEvent > self.parser.feed(buf) > File "/usr/lib/python2.2/site-packages/_xmlplus/sax/expatreader.py", line 208, in feed > self._err_handler.fatalError(exc) > File "/usr/lib/python2.2/site-packages/_xmlplus/sax/handler.py", line 38, in fatalError > raise exception > xml.sax._exceptions.SAXParseException: <unknown>:553:48: not well-formed (invalid token) > def getItems(page): > opener =urllib.URLopener(key_file=HOSTKEY,cert_file=HOSTCERT) ; > try: > xml = opener.open(page) > except: > return [] > > d = minidom.parseString(xml.read()) > items = d.getElementsByTagName('item') > data = [] > for i in items: > data.append(getText(i.childNodes)) > > return data The page is https://lcg-voms.cern.ch:8443/voms/cms/services/VOMSCompatibility?method=getGridmapUsers and the line with the invalid character is (the invalid character is the final ? of Universit?): <item>/C=BE/O=BEGRID/OU=Physique/OU=Univesit? Catholique de Louvain/CN=Roberfroid</item> I have tried several options but I am not able to avoid this problem. Any idea?. I am starting to work with Python so I am sorry if this problem is trivial. Thanks for your time. Pablo Rey From stefan.behnel-n05pAM at web.de Fri Aug 31 04:31:23 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 31 Aug 2007 10:31:23 +0200 Subject: Simple elementtree question In-Reply-To: <1188512190.384302.125730@m37g2000prh.googlegroups.com> References: <1188495178.701968.246690@50g2000hsm.googlegroups.com> <46D71A5E.1000005@web.de> <1188512190.384302.125730@m37g2000prh.googlegroups.com> Message-ID: <46D7D1DB.6020605@web.de> IamIan wrote: > Thank you very much! That did it. > > In the source XML <item> tags have rdf:about attributes with the link > to the story, and it was here I planned on grabbing the link and > matching it up with the <title> child text. After seeing the output of > elmenttree's getiterator() though, it now looks like each item, title, > description, and link is a separate element... > > I could use a dictionary or lists to match the first title to the > first link, but is there a more elegant way in elementtree (or > otherwise) to do this? You can iterate over the channel Elements and then select the title child (el.find()) to see if it's interesting. You can also try lxml.etree, which supports XPath: >>> from lxml import etree >>> find_channel = etree.XPath("//channel[title = $title]") >>> tree = etree.parse("http://somewhere/the_document.xml") >>> channel = find_channel(tree, title="example title") >>> print channel.findtext("link") or lxml.objectify: >>> from lxml import etree, objectify >>> find_channel = etree.XPath("//channel[title = $title]") >>> tree = objectify.parse("http://somewhere/the_document.xml") >>> channel = find_channel(tree, title="example title") >>> print channel.title, channel.link http://codespeak.net/lxml Stefan From jstroud at mbi.ucla.edu Sun Aug 19 22:11:35 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 19 Aug 2007 19:11:35 -0700 Subject: Syntax Question - list multiplication In-Reply-To: <mn.9d997d78fb085e82.46195@XX.XmclaveauX.com> References: <1187560273.146491.90530@r29g2000hsg.googlegroups.com> <mn.9d997d78fb085e82.46195@XX.XmclaveauX.com> Message-ID: <46C8F857.1010603@mbi.ucla.edu> MC wrote: > Classic Thanks Michel, but maybe this bit of programming jargon needs some translation for the uninitiated: Classic \Clas"sic\ (kl[a^]s"s[i^]k), Classical \Clas"sic*al\, a. 0. Read the FAQ 1. First rate 2. Greek 3. Refined James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Aug 7 03:46:38 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 07 Aug 2007 09:46:38 +0200 Subject: boolean operations on sets In-Reply-To: <1186409631.147290.323400@22g2000hsm.googlegroups.com> References: <1186409631.147290.323400@22g2000hsm.googlegroups.com> Message-ID: <46b82347$0$6945$426a74cc@news.free.fr> Flavio a ?crit : > Hi, I have been playing with set operations lately and came across a > kind of surprising result given that it is not mentioned in the > standard Python tutorial: > > with python sets, intersections and unions are supposed to be done > like this: > In [7]:set('casa') & set('porca') > Out[7]:set(['a', 'c']) > > In [8]:set('casa') | set('porca') > Out[8]:set(['a', 'c', 'o', 'p', 's', 'r']) > > and they work correctly. Now what is confusing is that if you do: > > In [5]:set('casa') and set('porca') > Out[5]:set(['a', 'p', 'c', 'r', 'o']) > > In [6]:set('casa') or set('porca') > Out[6]:set(['a', 'c', 's']) > > The results are not what you would expect from an AND or OR > operation, from the mathematical point of view! aparently the "and" > operation is returning the the second set, and the "or" operation is > returning the first. the semantic of 'and' and 'or' operators in Python is well defined and works the same for all types AFAIK. > If python developers wanted these operations to reflect the > traditional (Python) truth value for data structures: False for empty > data structures and True otherwise, why not return simply True or > False? > > So My question is: Why has this been implemented in this way? Because Python long lived without the 'bool' type - considering None, numeric zero, empty string and empty containers as false (ie : 'nothing', and anything else as true (ie : 'something'). > I can > see this confusing many newbies... Yes, and this has been one of the arguments against the introduction of the bool type. Changing this behaviour would have break lot of existing code, and indeed, not changing it makes things confusing. OTHO - and while I agree that there may be cases of useless complexities in Python -, stripping a language from anything that might confuse a newbie doesn't make great languages. From dfabrizio51 at gmail.com Fri Aug 17 09:27:24 2007 From: dfabrizio51 at gmail.com (chewie54) Date: Fri, 17 Aug 2007 13:27:24 -0000 Subject: best GUI library for vector drawing program Message-ID: <1187357244.883516.79840@j4g2000prf.googlegroups.com> Hello, What would be the best cross-platform GUI library to use for a vector based CAD program ( something like Visio on Windows ) WxWidgets, Tk, PyQt, Java Swing, Java SWT,???? I need the capibility to draw and edit in a window that looks like a page of paper so WYSIWYG is very important, and I need to save the drawings in vector based file formats like PS, EPS, SVG, as well as image formats like jpg, png, and gif. Also, the images need to be high resolution so that they can be pasted into various other programs in Windows OS, and Linux OS, and the Mac OS. Thanks in advance, Dan From Eric_Dexter at msn.com Wed Aug 8 20:05:37 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Wed, 08 Aug 2007 17:05:37 -0700 Subject: Launch file from Python In-Reply-To: <1186601943.551097.82360@j4g2000prf.googlegroups.com> References: <1186594137.971393.128780@57g2000hsv.googlegroups.com> <1186594611.490723.251870@m37g2000prh.googlegroups.com> <mailman.1764.1186601788.22759.python-list@python.org> <1186601943.551097.82360@j4g2000prf.googlegroups.com> Message-ID: <1186617937.241625.121270@q75g2000hsh.googlegroups.com> On Aug 8, 2:39 pm, kyoso... at gmail.com wrote: > On Aug 8, 2:35 pm, Arnau Sanchez <ar... at ehas.org> wrote: > > > > > > > kyoso... at gmail.com escribi?: > > > > That's just the exit status or run status, if I recall correctly. I > > > think 0 (i.e. False) means it didn't run properly and anything else is > > > True, or ok. Something like that. > > > The other way: 0 means "ok" while everything else means error (at least in > > UNIX). The reason is clear: there is usually only one way to do things well, but > > many to fail :-) > > > > Technically speaking, you should > > > probably switch to using the subprocess module as it is replacing that > > > os module's functionality:http://www.python.org/doc/2.4/lib/module-subprocess.html > > > Correct, subprocess replaces low-level os.system, os.popen*, os.spawn*, popen* > > functions. > > Figures...I couldn't find the docs on it though...and I do know that > some Windows programs return goofy numbers in the 1000s that mean it > worked fine. So, in other words, the return value isn't very helpful. > > Mike- Hide quoted text - > > - Show quoted text - I had used popen on windows and had to seperate the arguments out.. (example is in my awk module in dex tracker on sourceforge).. What you did may not work on windows. From bj_666 at gmx.net Tue Aug 7 04:05:19 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Aug 2007 08:05:19 GMT Subject: Regular Expression Groups - loop References: <1186472689.488634.23360@b79g2000hse.googlegroups.com> Message-ID: <5hqndvF3ldifeU4@mid.uni-berlin.de> On Tue, 07 Aug 2007 00:44:49 -0700, shahargs wrote: > I'm trying to write application which parse one page to sentences and > then, check every group for few things. > > The code: > rawstr = r"""([^.?!]+[.?!])""" > regex=re.compile(rawstr) > matchs=regex.search(document) > document, is the text i parsing. I cheked it in Kodos, and everything > worked well. but, i'm trying to write for loop which check every > group. > > I tried: > for group in matchs.groups(): > but then, it's check only the first group. and i tried: There is only one group in your regular expression. I guess you are confusing groups within one match with multiples matches in the text. `re.search()` finds exactly one sentence. If you want all sentences use `re.find_all()` or `re.find_iter()`. Ciao, Marc 'BlackJack' Rintsch From raims at dot.com Mon Aug 13 05:21:05 2007 From: raims at dot.com (Lawrence Oluyede) Date: Mon, 13 Aug 2007 11:21:05 +0200 Subject: retrieving ATOM/FSS feeds References: <f9oecg$249v$1@sxnews1.qg.com> Message-ID: <1i2s7c9.13bkwbfsd3mbqN%raims@dot.com> _spitFIRE <timid.gentoo at gmail.com> wrote: > I'm using feedparser library to parser ATOM/RSS feeds. However, I don't > get the entire post! but only summaries! How do I retrieve the entire feed? > I believe that the parser library should have support for doing that or the > specification should detail how it can be done? Or should I simply get the > feed link and do HTML scraping? If the content producer doesn't provide the full article via RSS/ATOM there's no way you can get it from there. Search for full content feeds if any, otherwise get the article URL and feed it to BeautifulSoup to scrape the content. -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From DustanGroups at gmail.com Thu Aug 9 18:30:08 2007 From: DustanGroups at gmail.com (Dustan) Date: Thu, 09 Aug 2007 22:30:08 -0000 Subject: programmatically define a new variable on the fly In-Reply-To: <1186697500.024593.303820@x35g2000prf.googlegroups.com> References: <1186697500.024593.303820@x35g2000prf.googlegroups.com> Message-ID: <1186698608.818912.180370@e16g2000pri.googlegroups.com> On Aug 9, 5:11 pm, Lee Sander <lesa... at gmail.com> wrote: > Hi, > > I would like to define a new variable which is not predefined by me. > For example, > I want to create an array called "X%s" where "%s" is to be determined > based on the data I am processing. So, for example, if I the file > I'm reading has > g 99 > on the first line, I want to create a new variable called "Xg" whose > length > is 99. > I tried eval("Xg=[0]*99") but that did not work. eval only evaluates expressions. To go about the problem that way, you would use exec, not eval. Of course, use of exec generally means you're going about the problem the wrong way; it looks to me like a better way to do what you're doing is to create a dictionary to hold your values. So, given the variables data (the dictionary), name (in your example, 'g') and *size* (in your example, 99), you can add it data as shown: data[name] = [0] data[name] *= size Note that by splitting the '[0]*size' code into two lines as shown above, you don't create an intermediate list object that gets thrown away right after creation. From antroy at gmail.com Wed Aug 29 15:28:00 2007 From: antroy at gmail.com (Ant) Date: Wed, 29 Aug 2007 12:28:00 -0700 Subject: sys.argv is munging my command line options In-Reply-To: <1188414714.645724.63330@i38g2000prf.googlegroups.com> References: <1188414714.645724.63330@i38g2000prf.googlegroups.com> Message-ID: <1188415680.744407.21190@r34g2000hsd.googlegroups.com> On Aug 29, 8:11 pm, Chris Allen <ca.al... at gmail.com> wrote: ... > But I'm running into a problem with this which is that sys.argv splits > my key=value options. I need to know the option associations, and > there's no way to know this by inspecting sys.argv. Can I get access > to the command line string as python saw it before it split it into > sys.argv or is there another way? Thanks. Could you show us some example code that demonstrates this? The following works as expected for me on win32: # test.py import sys for arg in sys.argv[1:]: print arg >From the command prompt: C:\0>test.py action key=value key=value action key=value key=value -- Ant. From tunedstyle at gmail.com Thu Aug 16 11:18:29 2007 From: tunedstyle at gmail.com (tunedstyle at gmail.com) Date: Thu, 16 Aug 2007 08:18:29 -0700 Subject: Car Air Conditioners Message-ID: <1187277509.218923.177520@b79g2000hse.googlegroups.com> All the informations about car air conditioners, how to install, repair, service all can be found on this website... http://car-air-conditioning.blogspot.com/ From ptmcg at austin.rr.com Fri Aug 17 00:27:11 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 16 Aug 2007 21:27:11 -0700 Subject: defaultdict of arbitrary depth In-Reply-To: <mailman.2098.1187324422.22759.python-list@python.org> References: <1187321113.841198.195100@22g2000hsm.googlegroups.com> <mailman.2098.1187324422.22759.python-list@python.org> Message-ID: <1187324831.082493.190970@w3g2000hsg.googlegroups.com> On Aug 16, 11:19 pm, Carsten Haese <cars... at uniqsys.com> wrote: > On Thu, 2007-08-16 at 20:25 -0700, Paul McGuire wrote: > > [...] > > I've hacked out this recursivedefaultdict which is a > > defaultdict(defaultdict(defaultdict(...))), arbitrarily deep depending > > on the keys provided in the reference. > > > Please comment. > > [...] > > > class recursivedefaultdict(object): > > def __init__(self): > > self.__dd = defaultdict(recursivedefaultdict) > > def __getattr__(self,attr): > > return self.__dd.__getattribute__(attr) > > def __getitem__(self,*args): > > return self.__dd.__getitem__(*args) > > def __setitem__(self,*args): > > return self.__dd.__setitem__(*args) > > This is shorter: > > from collections import defaultdict > > class recursivedefaultdict(defaultdict): > def __init__(self): > self.default_factory = type(self) > > -- > Carsten Haesehttp://informixdb.sourceforge.net- Hide quoted text - > > - Show quoted text - Of course, very short and sweet! Any special reason you wrote: self.default_factory = type(self) instead of: self.default_factory = recursivedefaultdict ? -- Paul From paddy3118 at googlemail.com Mon Aug 13 16:08:49 2007 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 13 Aug 2007 13:08:49 -0700 Subject: Dictionary viewer and editor In-Reply-To: <mailman.1932.1187032259.22759.python-list@python.org> References: <46C09E65.6060607@indiana.edu> <mailman.1932.1187032259.22759.python-list@python.org> Message-ID: <1187035729.100326.241440@57g2000hsv.googlegroups.com> On Aug 13, 8:10 pm, Thomas Jollans <tho... at jollans.com> wrote: > On Monday 13 August 2007, Ariel Balter wrote: > > >http://mail.python.org/pipermail/python-list/2001-August/100288.html > > > Did you ever finish writing this? > > YAML (without flow style) could qualify as "tree format". example: > > yaml.dump ( {"alpha": 1, "beta": 2, "otherstuff": {"bug": None, "cool": > True, "foo": ["bar", 2e64, {13: 'many eyes', 14: 'make all', 15: 'bugs > shallow'}]}}, default_flow_style=False ) > > ... is ... > > alpha: 1 > beta: 2 > otherstuff: > bug: null > cool: true > foo: > - bar > - !!float '2e+64' > - 13: many eyes > 14: make all > 15: bugs shallow I thought he wanted something graphical, but if text will do there is the PrettyPrint module... - Paddy. From carsten at uniqsys.com Thu Aug 16 22:32:19 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 16 Aug 2007 22:32:19 -0400 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: <1187311999.880853.135780@j4g2000prf.googlegroups.com> References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> <fa2m4s$k1g$1@daisy.noc.ucla.edu> <1187311999.880853.135780@j4g2000prf.googlegroups.com> Message-ID: <1187317939.3333.12.camel@localhost.localdomain> On Fri, 2007-08-17 at 00:53 +0000, beginner wrote: > $b is supposed to be a hash-table of hash-table. If a key exists in > $b, it points to another hash table. The $a=$b->{"A"} ||={} pattern is > useful when you want to add records to the double hash table. > > For example, if you have a series of records in the format of (K1, K2, > V), and you want to add them to the double hash-table, you can do > $a=$b->{K1} || ={} > $a->{K2}=V What is the best solution in Perl need not be the best solution in Python. In Python you should just use a tuple as your dict key, i.e. a[k1,k2] = v, unless you have some other constraints you're not telling us. HTH, -- Carsten Haese http://informixdb.sourceforge.net From steve at holdenweb.com Fri Aug 17 20:42:28 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 17 Aug 2007 20:42:28 -0400 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: <1187395351.199508.111720@m37g2000prh.googlegroups.com> References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> <1187314114.873306.187500@e9g2000prf.googlegroups.com> <1187316113.424465.34650@19g2000hsx.googlegroups.com> <1187395351.199508.111720@m37g2000prh.googlegroups.com> Message-ID: <fa5f9c$hf2$1@sea.gmane.org> Carl Banks wrote: > On Aug 16, 10:01 pm, Paul McGuire <pt... at austin.rr.com> wrote: >> On Aug 16, 8:28 pm, Jonathan Gardner >> >> >> >> <jgardner.jonathangardner.... at gmail.com> wrote: >>> On Aug 16, 3:35 pm, beginner <zyzhu2... at gmail.com> wrote: >>>> In perl it is just one line: $a=$b->{"A"} ||={}. >>> a = b.setdefault('A', {}) >>> This combines all two actions together: >>> - Sets b['A'] to {} if it is not already defined >>> - Assigns b['A'] to a >>> More info on dict methods here: >>> http://docs.python.org/lib/typesmapping.html >> No, this has already been proposed and discarded. The OP does NOT >> want this, because it always generates an empty {} whether it is >> needed or not. Not really a big hardship, but if the default value >> were some expensive-to-construct container class, then you would be >> creating one every time you wanted to reference a value, on the chance >> that the key did not exist. >> >> Carl Banks' post using defaultdict is the correct solution. The >> raison d'etre for defaultdict, and the reason that it is the solution >> to the OP's question, is that instead of creating a just-in-case >> default value every time, the defaultdict itself is constructed with a >> factory method of some kind (in practice, it appears that this factory >> method is usually the list or dict class constructor). If a reference >> to the defaultdict gives a not-yet-existing key, then the factory >> method is called to construct the new value, that value is stored in >> the dict with the given key, and the value is passed back to the >> caller. No instances are created unless they are truly required for >> initializing an entry for a never-before-seen key. > > > When I made my response, it occurred to me that Python could be > improved (maybe) if one could overload dict.get() to use a factory, > like so: > > b = {} > a = b.get(k,factory=dict) > a['A'] = 1 > > That's a slight improvement (maybe) over defaultdict since it would > still allow the same dict to have the membership check in other > places. I'm not so sure overloading get to let it modify the dict is > a good idea, though. > > Actually, it'd probably be fairly uncontroversial to add a factory > keyword to dict.setdefault(). At least insofar as setdefault is > uncontroversial. > Well it's uncontroversial enough to have made it into the distribution, which represents a tacit admission by Guido that the .get() method alone didn't implement his full vision. The python-dev thread that discussed the feature before implementation (as so often is the case) exercised many of the possible design paths, and would be a useful read. [Damn, now I have to well-known-search-engine it]. Aah, right - I'd forgotten how long it took to get it right. This would be a suitable starting-point - it's the beginning of the /third/ round of discussion: http://mail.python.org/pipermail/python-dev/2006-February/061485.html Many alternatives were discussed, and my memory at this distance is that Guido had good reasons for choosing the exact API he did for defaultdict. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From nmin at freenet.de Tue Aug 14 05:54:57 2007 From: nmin at freenet.de (nmin at freenet.de) Date: Tue, 14 Aug 2007 02:54:57 -0700 Subject: Jython - problem import os In-Reply-To: <mailman.1769.1186616127.22759.python-list@python.org> References: <1186575029.494729.327550@b79g2000hse.googlegroups.com> <mailman.1769.1186616127.22759.python-list@python.org> Message-ID: <1187085297.163751.257670@k79g2000hse.googlegroups.com> Thats it ... Additionally I had to set the python path with sys.path.append to the Lib folder .. and now it works perfect. thanks a lot Simon From ldo at geek-central.gen.new_zealand Fri Aug 31 23:49:39 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 01 Sep 2007 15:49:39 +1200 Subject: Python Unicode to String conversion References: <1188600916.528901.189680@d55g2000hsg.googlegroups.com> Message-ID: <fbanbu$smu$1@lust.ihug.co.nz> In message <1188600916.528901.189680 at d55g2000hsg.googlegroups.com>, thijs.braem at gmail.com wrote: > The error I keep having is something like this: > ERREUR: S?quence d'octets invalide pour le codage ?UTF8? : 0xe02063 It would be useful to see some actual code snippet, traceback listing etc. From arnodel at googlemail.com Thu Aug 30 17:51:30 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 30 Aug 2007 14:51:30 -0700 Subject: Setting a read-only attribute In-Reply-To: <1188509700.915517.178440@z24g2000prh.googlegroups.com> References: <1188509700.915517.178440@z24g2000prh.googlegroups.com> Message-ID: <1188510690.622808.247220@z24g2000prh.googlegroups.com> On Aug 30, 10:35 pm, "tleeuwenb... at gmail.com" <tleeuwenb... at gmail.com> wrote: > I have an object and wish to set an attribute on it which, > unfortunately for me, is read-only. If it's read-only then you can't set it! > How can I go about this? Joke aside, I think you need to be more specific. -- Arnaud From wescpy at gmail.com Thu Aug 23 03:43:53 2007 From: wescpy at gmail.com (wesley chun) Date: Thu, 23 Aug 2007 00:43:53 -0700 Subject: [ANN] Python courses this Fall Message-ID: <78b3a9580708230043k35ff6729vc7fefefb2068531b@mail.gmail.com> Folks, I'd like to announce my final Python courses for 2007: Need to get up-to-speed with Python as quickly as possible? Come join me, Wesley Chun, author of Prentice-Hall's well-received "Core Python Programming," for another set of courses this Fall in beautiful Northern California! This will be the final set for 2007... if you miss these, you'll have to wait until next year. I look forward to meeting you! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (COMPREHENSIVE) INTRODUCTION TO PYTHON: Mon-Wed, 2007 Oct 8-10 This is course is meant for those new to Python and/or want to get more in-depth formal training. We will immerse you in the world of Python in only a few days. We will show you more than just its syntax (which you don't really need a book to learn, right?). Knowing more about how Python works under the covers, including the relationship between data objects and memory management, will make you a much more effective Python programmer coming out of the gate. 3 hands-on labs each day will help hammer the concepts home. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - INTERNET PROGRAMMING WITH PYTHON: Sat, 2007 Oct 13 This 1-day course will introduce current Python programmers to 3 distinct areas of Internet programming, each in self-contained modules with a set of lab exercises following each lecture topic: Network Programming using Sockets -- Underneath all of today's network protocols, i.e., HTTP, FTP, RDBMS, IM, e-mail, etc., lies the main communication mechanism, sockets. Here, we introduce client/server architecture and how to program sockets using Python. Internet Client Programming -- One level above the socket layer are well-known Internet protocols such as FTP, NNTP, POP3, and SMTP. In this section, we learn how to create Internet clients of these protocols to transfer files, send and receive e-mail, and read Usenet newsgroup postings. Web/CGI Programming -- Yes, pure CGI is "sooo yesterday," but before you jump on all the web framework bandwagons, it's a good idea to learn basics and the basis of how all web servers deliver dynamic content back to the client browser so that you can appreciate all the work that is done on your behalf by a more fully-featured frame- work. Time-permitting, we will also give a high-level overview of one of the more popular Python web frameworks, Django. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WHERE: near the San Francisco Airport (SFO/San Bruno), CA, USA WEB: http://cyberwebconsulting.com (click "Python Training") LOCALS: easy freeway (101/280/380) with lots of parking plus public transit (BART and CalTrain) access via the San Bruno stations, easily accessible from all parts of the Bay Area VISITORS: free shuttle to/from the airport, free high-speed internet, free breakfast and regular evening receptions; fully-equipped suites See website for costs, venue info, and registration. Discounts are available for multiple registrations as well as for teachers/students. Hope to see you there! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wildemar at freakmail.de Fri Aug 24 12:44:15 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 24 Aug 2007 18:44:15 +0200 Subject: How to replace a method in an instance. In-Reply-To: <alpine.LFD.0.999.0708241223480.30194@saturn.syslang.net> References: <mailman.258.1187971369.32294.python-list@python.org> <1187971953.261328.219000@q3g2000prf.googlegroups.com> <alpine.LFD.0.999.0708241223480.30194@saturn.syslang.net> Message-ID: <46CF0ADF.9050305@freakmail.de> Steven W. Orr wrote: > Sorry. I need repmeth to have self passed to it automatically if it's > called. I didn't mean to obfuscate the problem by not making a reference > to self in repmeth. > > Am I being clear? > > Sort of. Maybe you fare better if you state what you want to achieve, instead of how you think you should do it. Chances are you don't need to replace a method in __init__, but there's another, less tricky way. /W From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Aug 2 17:37:03 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 02 Aug 2007 23:37:03 +0200 Subject: Representation of new-style instance References: <mailman.1467.1186011333.22759.python-list@python.org> Message-ID: <5hf13vF3knjorU1@mid.individual.net> Raj B wrote: > Which C struct in the Python implementation is used to represent > the instances c1 and c2 of the new-style class? You don't try to send this raw over some stream connection, do you? Regards, Bj?rn -- BOFH excuse #349: Stray Alpha Particles from memory packaging caused Hard Memory Error on Server. From joshua at eeinternet.com Wed Aug 1 18:55:49 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 01 Aug 2007 14:55:49 -0800 Subject: Wing IDE for Python v. 3.0 beta1 released References: <46AF8ED7.2070206@wingware.com> <20070801212840.GA25065@spookie1.spookiegate> <f8quug$m7j$1@sea.gmane.org> <20070801221522.GC25065@spookie1.spookiegate> Message-ID: <f8r31l$sa$1@sea.gmane.org> On Wednesday 01 August 2007 14:15, John K Masters wrote: >> > I have been trying wing for a few days but have noticed that >> > auto-completion does not work on all modules. I submitted this to wing >> > and was told that probably my PYTHONPATH was wrong. >> It may also not work if the IDE isn't sure what kind of object you are >> dealing with. You can "clarify" this as documented with an >> assert(isinstance()) statement. > But as I pointed out to the wingware people the autocompletion was > recognising some methods but not others from the same module, I just remembered: I've been around the block with them on this one too. It was with PyTables. There are some modules (PyTables includes) that use certain names that are valid when called, but are no where defined in the module. Yes, it happens, and yes, it sounds quite tweaky. I can dig up details if you want me to. But, since the names are defined, basically, at run time, there is no way Wing can find them for autocompletion. >> > I subsequently submitted a question about the licensing, i.e. whether I >> > could use wing on a home setup using Debian Etch, where I develop my >> > apps, and a work setup, using Debian Etch, with no net access. >> >> From http://www.wingware.com/wingide/license: >> >> "Each Wing IDE user may run Wing on as many machines as needed for their >> own work, for all the operating systems which they have licensed. In >> order to reduce casual license sharing, which is a unfortunately a >> problem for small businesses like Wingware, licenses must be activated >> after installation on each machine." >> >> "We've worked hard to make this flexible and forgiving for valid >> customers. For example, reinstalling an OS and/or altering hardware >> usually should not break your activation. Also, activation can be done >> directly from Wing IDE and off-line activation is available if your >> machine does not have TCP port 80 (http) access to wingware.com. Each >> license is allowed three activations by default and more can be obtained >> on request from identifiable customers." >> > > But this requires activation via a web connection. It does? "off-line activation is available if your machine does not have TCP port 80 (http) access to wingware.com." What part still requires web access? j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE From nepbabucxspamfree at yahoo.ca Tue Aug 21 07:00:19 2007 From: nepbabucxspamfree at yahoo.ca (Bikal KC) Date: Tue, 21 Aug 2007 20:30:19 +0930 Subject: C# and Python In-Reply-To: <1187690505.903506.79690@d55g2000hsg.googlegroups.com> References: <1187690505.903506.79690@d55g2000hsg.googlegroups.com> Message-ID: <46cac5ba$1_1@news.chariot.net.au> subeen wrote: > When the user clicks Quick Sort button, the quicksort.py will be > called and it will sort the numbers. One way to do this: In your C# app, have the mouse click event handler call python interpreter "/path/to/python /path/to/quicksort.py". Make quicksort.py write to a file the result. After the quicksort.py finishes, read the file from your normal C# app. Cheers. From cjankowski at hbr-inc.com Mon Aug 6 15:15:12 2007 From: cjankowski at hbr-inc.com (cjankowski at hbr-inc.com) Date: Mon, 06 Aug 2007 12:15:12 -0700 Subject: RTF 2 Tiff Message-ID: <1186427712.284976.207560@d30g2000prg.googlegroups.com> Hi all, I am trying to convert an RTF file to a Tiff image using Python. This process will convert several hundred images daily. Currently I am able to get the RTF file into a text format using Rtf2Txt.py, but I loose the images contained in the RTF file. I have the same problem when I convert to .HTML using Rtf2Html.py. I do not have a sample that I can share because of HIPPA regulations. Can anyone please help me? Thanks, Chris J. From jocago at gmail.com Wed Aug 8 13:28:57 2007 From: jocago at gmail.com (jocago at gmail.com) Date: Wed, 08 Aug 2007 10:28:57 -0700 Subject: Launch file from Python Message-ID: <1186594137.971393.128780@57g2000hsv.googlegroups.com> Good afternoon from someone who is trying to learn Python. I would like to launch an app from within a Python script. From the examples I have found, I should be able to do this with os.system. I use this: os.system("xplanet-1.2.0/xplanet.exe -fontsize 24 -label -target earth -lat 33.65 -lon -84.42 -radius 40 -num_times 1 -tmpdir .") This is copied directly from the .bat file that launches the xplanet app. It works there. and get this: 1 Can someone fill me in? Thanks. From paddy3118 at googlemail.com Sun Aug 5 10:10:17 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 05 Aug 2007 14:10:17 -0000 Subject: (no) fast boolean evaluation ? In-Reply-To: <1186245190.970687.307920@k79g2000hse.googlegroups.com> References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> <1186240708.874804.271030@b79g2000hse.googlegroups.com> <1186245190.970687.307920@k79g2000hse.googlegroups.com> Message-ID: <1186323017.756294.77350@k79g2000hse.googlegroups.com> On Aug 4, 5:33 pm, Paddy <paddy3... at googlemail.com> wrote: > On Aug 4, 4:18 pm, Paddy <paddy3... at googlemail.com> wrote: > > > > > On Aug 2, 10:47 pm, Stef Mientki <S.Mientki-nos... at mailbox.kun.nl> > > wrote: > > > > hello, > > > > I discovered that boolean evaluation in Python is done "fast" > > > (as soon as the condition is ok, the rest of the expression is ignored). > > > > Is this standard behavior or is there a compiler switch to turn it on/off ? > > > > thanks, > > > Stef Mientki > > > The following program shows a(clumsy)? way to defeat the short- > > circuiting: > > > def f(x): > > print "f(%s)=%s" % ('x',x), > > return x > > def g(x): > > print "g(%s)=%s" % ('x',x), > > return x > > > print "\nShort circuit" > > for i in (True, False): > > for j in (True, False): > > print i,j,":", f(i) and g(j) > > > print "\nShort circuit defeated" > > for i in (True, False): > > for j in (True, False): > > print i,j,":", g(j) if f(i) else (g(j) and False) > > > The output is: > > > Short circuit > > True True : f(x)=True g(x)=True True > > True False : f(x)=True g(x)=False False > > False True : f(x)=False False > > False False : f(x)=False False > > > Short circuit defeated > > True True : f(x)=True g(x)=True True > > True False : f(x)=True g(x)=False False > > False True : f(x)=False g(x)=True False > > False False : f(x)=False g(x)=False False > > > - Paddy. > > And here are the bits for boolean OR: > > print "\n\nShort circuit: OR" > for i in (True, False): > for j in (True, False): > print i,j,":", f(i) or g(j) > > print "\nShort circuit defeated: OR" > for i in (True, False): > for j in (True, False): > print i,j,":", (g(j) or True) if f(i) else g(j) > > - Paddy. Dumb! Use & and | Gosh That port last night was good ;-) From mugi at pinesalad.net Tue Aug 21 00:06:43 2007 From: mugi at pinesalad.net (Signal) Date: Mon, 20 Aug 2007 21:06:43 -0700 Subject: File Read Cache - How to purge? Message-ID: <1187669203.698637.81990@i38g2000prf.googlegroups.com> To become part of a larger script that will read through all files on a given drive, I was playing around with reading files and wanted to see if there was an optimum value for a read size on my system. What I noticed is that the file being read is "cached" on subsequent reads. Based on some testing it looks like it's by the underlying OS (windows in this case) but have a few questions. Here's a code sample: ------------------------------------------------------------------------- import os, time # Set the following two variables to # different large files on your system. # Suggest files in the range of 500MB to 1Gig testfile1 = "d:\\test1\\junk1.file" testfile2 = "d:\\test1\\junk2.file" def readfile(filename): size = os.path.getsize(filename) bufsize = 4096 print filename, size, "Bytes" while bufsize < 132000: start = time.clock() f = open(filename, "rb") buf = f.read(bufsize) while buf: buf = f.read(bufsize) f.flush() # note: put here as a test and # it doesn't make a difference f.close() end = time.clock() print bufsize, round(end - start,3) bufsize = bufsize*2 print " " # Comment the second and third readfile and run # the program twice to see a similar result for testfile1 readfile(testfile1) readfile(testfile1) readfile(testfile2) ----------------------------------------------------------------- Sample output for first testfile1: d:\test1\junk1.file 759167228 Bytes 4096 20.366 8192 0.923 16384 0.783 32768 0.737 65536 0.74 131072 0.82 After the first read test at 4096, subsequent read tests seem to be cached. This is even though the file is being closed before initiating another read test. Sample output for second testfile1 d:\test1\junk1.file 759167228 Bytes 4096 1.258 8192 0.944 16384 0.795 32768 0.743 65536 0.725 131072 0.826 Ok, didn't expect much difference here based on the first read, but wanted to note how 4096 is now 1.2 seconds. Sample output for testfile2: d:\test1\junk2.file 1142511616 Bytes 4096 31.514 8192 1.417 16384 1.202 32768 1.11 65536 1.089 131072 1.245 Same situation as our first sample for testfile1. 4096 is not cached, but subsequent reads are. Now some things to note: So it seems the file is being cached, however on my system only ~2MB of additional memory is used when the program is run. This 2MB of memory is released when the script exits. If you comment the second and third readfile lines (as noted in the code): a. Run the program twice, you will see that even if the program exits, this cache is not cleared. b. If you open another command prompt and run the code, it's cached. c. If you close both command prompts, open a new one and run the code it's still cached. It isn't "cleared" until another large file is read. My questions are: 1. I don't quite understand how after one full read of a file, another full read of the same file is "cached" so significantly while consuming so little memory. What exactly is being cached to improve the reading of the file a second time? 2. Is there anyway to somehow to take advantage of this "caching" by initializing it without reading through the entire file first? 3. If the answer to #2 is No, then is there a way to purge this "cache" in order to get a more accurate result in my routine? That is without having to read another large file first? From bronger at physik.rwth-aachen.de Sat Aug 25 06:24:16 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 25 Aug 2007 12:24:16 +0200 Subject: Co-developers wanted: document markup language References: <87odgyyx9u.fsf@wilson.homeunix.com> <mailman.285.1187992595.32294.python-list@python.org> <87tzqotwkk.fsf@wilson.homeunix.com> <faoso8$oa$1@gemini.csx.cam.ac.uk> Message-ID: <877injud2n.fsf@wilson.homeunix.com> Hall?chen! Jeremy Sanders writes: > Torsten Bronger wrote: > >> I don't know exactly what you mean but the answer is probably no. >> For example, I want the author to state the title, keywords, etc >> of his document, however, he should not state that he wants the >> title printed centred and 4cm from the top of the page. >> >> The latter is defined in the "theme" which will be given as a set >> of ordinary LaTeX commands (for the LaTeX backend). > > Isn't the problem that making such a theme will be very hard? Well, it will be a lot of work because there are so many elements but there is no high complexity. There will be a standard LaTeX backend, and further backends can be built of top of that so that for some of them, only very little extra code is necessary. > One of the annoying things about LaTeX is lack of control over > positioning (e.g. floats, page breaks...). The one thing most > LaTeX users moan about is trying to get their document to fit into > an n page limit (e.g. for a proposal). Well, trying to meet a page limit is a more exotic requirement in my opinion. Anyway, apart from the theme and some parameters that you can pass to it, there will be a LaTeX cfg file which, if present in the document directory, will be inserted directly before "\begin{document}". This is a quick and simple way for LaTeX wizards to configure the LaTeX process. In this file, you can set a smaller lineskip and a tighter font, for example. > Maybe the theme could have some options to control spacing, > however, like some sort of CSS. At least *I* won't include a CSS parser, escpecially not for the document source file. My aim is to keep the list of parameters for the backend a one-liner for most documents. Themes may recognize arbitrary many parameters but the standard themes will know only a few (paper size, margins, font/fontsize, columns, one/twoside, and a few more). Of course, a third-party theme may use CSS for LaTeX, possibly the very same CSS file which is used for the accompanying HTML backend. > I think the one thing that would improve LaTeX is orthogonality in > its commands (e.g. why no 8pt option for the document, why the > crazy \small, \LARGE, etc commands?), (There is the extsizes package.) I understand "orthogonality" as the independence of features, and by and large this is true for LaTeX. \small is not for *global* font changes after all. You may miss completeness, well, Gummi will surely offer even less, which I think is one of its chances. I certainly miss homogeneity in LaTeX (for example, 10-12pt is in the standard classes, 8-20pt is in extsizes), and in this respect, Gummi will offer much more. > and fixing the font system to be based around modern > fonts. Finally making bibtex part of the core and making it easy > to use would be great. This is another opportunity: You can hide the toolchain (well, this is done by LaTeX editors, too) and implementation uglinesses from the author. By the way, Gummi will use the new biblatex package for the bibliography. It's really a relief to abandon the notorious BibTeX style language for good. Some people asked me whether it wouldn't be better to improve LaTeX instead, however, this would make possible only a small fraction of these goals. BibTeX is a good example: Its syntax is utter crap, and even with biblatex you have to learn how to use the outdated 7bit (sometimes 8bit) format of bib files. The whole LaTeX system is immutably optimised for English letters. Aleph will ease this somewhat sometime. In Gummi, the only thing left of all this is that "en" is the default document language. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From grahn+nntp at snipabacken.dyndns.org Sun Aug 12 14:03:11 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 12 Aug 2007 18:03:11 GMT Subject: Public Telnet Server? References: <1186844845.304731.18300@x40g2000prg.googlegroups.com> Message-ID: <slrnfbuirp.52s.grahn+nntp@frailea.sa.invalid> On Sat, 11 Aug 2007 15:07:25 -0000, Dave <davmillar at gmail.com> wrote: > Hi there. I'm a beginner at Python and I'm writing my first Python > script. It's a text adventure about coffee and mixing drinks and being > crazy and such. I keep updating it and want my friends to beta test it > for me, but some of them don't have the right version of Python or > don't want to get Python at all. Is there an easy way I can set up a > public telnet server so they can just telnet the server and play it? - get yourself a Unix machine with a real, routable IP address - enable telnet (or better, ssh) access - create a new user - make the game this user's login shell, or let her login script exec the game - test it out - distribute address, user name and password to people "netcat ... -e the_game" may be another option. However, the security implications of this may be serious. You should assume these people can get local user shell access whenever they feel like it, and use your machine for evil purposes. I trust my brother with local access to my machines, and noone else[1]. /J?rgen [1] Well, his two cats too, but they have never logged in so far. Probably forgot the password, too. -- // Jorgen Grahn <grahn@ Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.dyndns.org> R'lyeh wgah'nagl fhtagn! From miki.tebeka at gmail.com Tue Aug 14 14:44:08 2007 From: miki.tebeka at gmail.com (Miki) Date: Tue, 14 Aug 2007 18:44:08 -0000 Subject: Fast kNN from python In-Reply-To: <1187086584.076990.260680@r34g2000hsd.googlegroups.com> References: <1187086584.076990.260680@r34g2000hsd.googlegroups.com> Message-ID: <1187117048.992003.103700@x35g2000prf.googlegroups.com> Hello, > I am looking for a Python implementation or bindings to a library that > can quickly find k-Nearest Neighbors given an arbitrary distance > metric between objects. Specifically, I have an "edit distance" > between objects that is written in Python. First Google search for "k-Nearest Neighbors python", yielded http://people.revoledu.com/kardi/tutorial/KNN/resources.html which pointed to http://biopython.org/DIST/docs/api/public/Bio.kNN-module.html HTH, -- Miki <miki.tebeka at gmail.com> http://pythonwise.blogspot.com From grante at visi.com Tue Aug 28 08:19:28 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 28 Aug 2007 12:19:28 -0000 Subject: Chaining programs with pipe References: <1187734166.384152.178040@o80g2000hse.googlegroups.com> <13cnbi87neru8c3@corp.supernews.com> <mailman.97.1187757319.32294.python-list@python.org> <13cogr3n6no937b@corp.supernews.com> <1187795716.083417.299540@q4g2000prc.googlegroups.com> <fau28j$gle$3@lust.ihug.co.nz> <mailman.51.1188274035.28954.python-list@python.org> <fb0alf$hgr$3@lust.ihug.co.nz> <1188290735.746264.280650@y42g2000hsy.googlegroups.com> Message-ID: <13d84mghdg7990f@corp.supernews.com> On 2007-08-28, Gabriel Genellina <gagsl-py2 at yahoo.com.ar> wrote: > On Windows, windowed applications (as opposed to console > applications) start with no stdin/stdout/stderr by default. > The application developer can modify that if desired, of > course - I've menctioned some ways to do that. This fact > simply means that those OS's *are* different - most of the > time one can ignore the differences, but not always. Neither > of them is doing the absolute "Right Thing". We're never going have any good flames with that sort of attitude. ;) -- Grant Edwards grante Yow! I know how to do at SPECIAL EFFECTS!! visi.com From Shawn at Milochik.com Tue Aug 14 14:44:17 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Tue, 14 Aug 2007 14:44:17 -0400 Subject: curses library In-Reply-To: <20070814211043.286b8aa6.ghirai@ghirai.com> References: <20070814211043.286b8aa6.ghirai@ghirai.com> Message-ID: <2dc0c81b0708141144n40c3209bgce3cf51f966c7fc7@mail.gmail.com> You should try Google -- you'll get results faster: http://www.amk.ca/python/howto/curses/ http://docs.python.org/lib/module-curses.html On 8/14/07, Ghirai <ghirai at ghirai.com> wrote: > Hello list, > > I need to write a console application. > > Are there any wrappers around curses/ncurses? > Or any other similar libraries? > > Thanks. > -- > Regards, > Ghirai. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Please read: http://milocast.com/2007/07/31/this-i-believe/ From buzzard at urubu.freeserve.co.uk Sun Aug 19 19:58:52 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Mon, 20 Aug 2007 00:58:52 +0100 Subject: Syntax Question - list multiplication In-Reply-To: <4L3yi.61391$W21.1628190@phobos.telenet-ops.be> References: <1187560273.146491.90530@r29g2000hsg.googlegroups.com> <4L3yi.61391$W21.1628190@phobos.telenet-ops.be> Message-ID: <faalcb$30v1$1@energise.enta.net> Roel Schroeven wrote: > Pablo Torres schreef: > >> Hi guys! >> >> I am working on Conway's Game of Life right now and I've run into a >> little problem. >> I represent dead cells with 0s and live ones with 1s. Check this out: >> >> >>> grid = [[0] * 3] * 3 >> >>> grid >> [[0, 0, 0], [0, 0, 0], [0, 0, 0]] >> >>> grid[0][0] = 1 >> [[1, 0, 0], [1, 0, 0], [1, 0, 0]] >> >> Now, that's not what I want. I just want the first element of the >> first sublist to be a 1, not the first of every one. Here's what I >> tried and didn't work: >> >> 0. grid = [[0] * 3][:] * 3 then the same grid[0][0] = 1 statement >> 1. grid = [[0][:] * 3] * 3 followed by the same assignment >> 2. (grid[0])[0] = 1 with the original initialization of the grid >> >> So, that means that it isn't a problem with two different variables >> refering to the same list (0. and 1. prove that). What I don't >> understand is why 2. doesn't work either. I'm baby-feeding my >> instructions to Python and the mistake is still there. Any ideas? >> >> Hope you can help. Thanks in advance, > > > The multiplication operator doesn't make new copies; all elements > reference the same object, as you can see with id(): > >>>> lst = [0] * 3 >>>> lst > [0, 0, 0] >>>> id(lst[0]), id(lst[1]), id(lst[2]) > (9788716, 9788716, 9788716) > I think you probably meant something like, >>> lst = [[0] * 3] * 3 >>> lst [[0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> id(lst[0]), id(lst[1]), id(lst[2]) (15937704, 15937704, 15937704) >>> i.e. a list of mutable types where the difference between multiple objects and multiple references to the same object will be apparent. With small integers you're likely to find you have multiple references to the same integer objects however the list is constructed. Duncan From see_website at mindprod.com.invalid Mon Aug 20 07:13:46 2007 From: see_website at mindprod.com.invalid (Roedy Green) Date: Mon, 20 Aug 2007 11:13:46 GMT Subject: best GUI library for vector drawing program References: <1187357244.883516.79840@j4g2000prf.googlegroups.com> Message-ID: <sptic31137mal5t4cajdo6lvddo8spjkbp@4ax.com> >What would be the best cross-platform GUI library to use for a vector >based CAD program ( something like Visio on Windows ) I don't know about he best, but I have collected a list of them at http://mindprod.com/jgloss/graph.html -- Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com From pangj at juno.com Thu Aug 23 04:19:32 2007 From: pangj at juno.com (Jeff Pang) Date: Thu, 23 Aug 2007 08:19:32 GMT Subject: [ANN] Python courses this Fall Message-ID: <20070823.011932.12838.0@webmail31.lax.untd.com> Sounds good.How about the costs for those lessons?thanks. -- "wesley chun" <wescpy at gmail.com> wrote: Folks, I'd like to announce my final Python courses for 2007: Need to get up-to-speed with Python as quickly as possible? Come join me, Wesley Chun, author of Prentice-Hall's well-received "Core Python Programming," for another set of courses this Fall in beautiful Northern California! This will be the final set for 2007... if you miss these, you'll have to wait until next year. I look forward to meeting you! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (COMPREHENSIVE) INTRODUCTION TO PYTHON: Mon-Wed, 2007 Oct 8-10 This is course is meant for those new to Python and/or want to get more in-depth formal training. We will immerse you in the world of Python in only a few days. We will show you more than just its syntax (which you don't really need a book to learn, right?). Knowing more about how Python works under the covers, including the relationship between data objects and memory management, will make you a much more effective Python programmer coming out of the gate. 3 hands-on labs each day will help hammer the concepts home. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - INTERNET PROGRAMMING WITH PYTHON: Sat, 2007 Oct 13 This 1-day course will introduce current Python programmers to 3 distinct areas of Internet programming, each in self-contained modules with a set of lab exercises following each lecture topic: Network Programming using Sockets -- Underneath all of today's network protocols, i.e., HTTP, FTP, RDBMS, IM, e-mail, etc., lies the main communication mechanism, sockets. Here, we introduce client/server architecture and how to program sockets using Python. Internet Client Programming -- One level above the socket layer are well-known Internet protocols such as FTP, NNTP, POP3, and SMTP. In this section, we learn how to create Internet clients of these protocols to transfer files, send and receive e-mail, and read Usenet newsgroup postings. Web/CGI Programming -- Yes, pure CGI is "sooo yesterday," but before you jump on all the web framework bandwagons, it's a good idea to learn basics and the basis of how all web servers deliver dynamic content back to the client browser so that you can appreciate all the work that is done on your behalf by a more fully-featured frame- work. Time-permitting, we will also give a high-level overview of one of the more popular Python web frameworks, Django. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WHERE: near the San Francisco Airport (SFO/San Bruno), CA, USA WEB: http://cyberwebconsulting.com (click "Python Training") LOCALS: easy freeway (101/280/380) with lots of parking plus public transit (BART and CalTrain) access via the San Bruno stations, easily accessible from all parts of the Bay Area VISITORS: free shuttle to/from the airport, free high-speed internet, free breakfast and regular evening receptions; fully-equipped suites See website for costs, venue info, and registration. Discounts are available for multiple registrations as well as for teachers/students. Hope to see you there! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -- http://mail.python.org/mailman/listinfo/python-list ________________________________________________________________________ Send your friends personalized video messages! Sign up for a FREE Juno account and start sending Video Mail today! http://track.juno.com/s/lc?u=http://ads.addynamix.com/click/2-2130421-177 From python at jayloden.com Mon Aug 20 16:24:42 2007 From: python at jayloden.com (Jay Loden) Date: Mon, 20 Aug 2007 16:24:42 -0400 Subject: reading a line in file In-Reply-To: <2dc0c81b0708201314q727ca3a1s12bef74a25b20abc@mail.gmail.com> References: <93066C069973ED448DC2BCEA9C44A7383BE2B2@efmailx> <2dc0c81b0708201029k5909d919vcf0deebae74a79c7@mail.gmail.com> <93066C069973ED448DC2BCEA9C44A7383BE2B4@efmailx> <2dc0c81b0708201207p7f83f2e0l6de15fd70be252a5@mail.gmail.com> <93066C069973ED448DC2BCEA9C44A7383BE2B6@efmailx> <46C9F561.50405@jayloden.com> <2dc0c81b0708201314q727ca3a1s12bef74a25b20abc@mail.gmail.com> Message-ID: <46C9F88A.9090400@jayloden.com> Shawn Milochik wrote: > Everybody hates regexes. Except me. Discrimination! Actually, I love them, they are an amazingly powerful tool. I just happen to also believe the old axiom "when all you have is a hammer, everything looks like your thumb". Also the related "some people think when they see a problem 'I know, I'll solve it with regexes' - now they have two problems" ;) I work with a lot of Perl at work and the mindset with Perl is precisely the opposite, since the regexes in Perl are so fast and so built-in/easy to work with. I guess it's sort of a language design and culture thing. -Jay From franz.steinhaeusler at gmx.at Sun Aug 5 11:03:01 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhäusler) Date: Sun, 05 Aug 2007 17:03:01 +0200 Subject: Best programs written completly in Python References: <mailman.1647.1186320975.22759.python-list@python.org> Message-ID: <qjpbb39h0rsgrp7mnqpecdqi7apf2uhq78@4ax.com> On Sun, 05 Aug 2007 15:35:53 +0200, David Boddie <david at boddie.org.uk> wrote: >On Sun Aug 5 14:44:55 CEST 2007, Franz Steinh?usler wrote: > >> I'm only interested to have a list, or even help to >> extend an existing one. > >If the main criterion is that the programs are written in Python then >surely the PythonInfo Wiki is the place for such a list: > > http://wiki.python.org/moin/Applications > >May I suggest that you extend this one? > >David David, thank you very much, perfect! :) -- Franz Steinhaeusler From bignose+hates-spam at benfinney.id.au Wed Aug 8 17:47:13 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 09 Aug 2007 07:47:13 +1000 Subject: How to avoid reverse code engineering of a python executable References: <1186573228.419760.272240@k79g2000hse.googlegroups.com> Message-ID: <87vebp66n2.fsf@benfinney.id.au> NicolasG <nicolasg at gmail.com> writes: > Now I want to proceed a little bit further asking how can I avoid > (or at least make it difficult) for some one to extract my code by > using reverse code engineer techniques? I came on pyobfuscate but I > would like more suggestions and guide to achieve the most possible > security in this matter. The best possible security is to examine and change the threat model. Why are you treating the code recipient as the bad guy? In other words, why do you care whether the recipient reverse engineers the program? Whatever effort you put into obfuscation, you can't prevent even a mildly interested attacker from reverse engineering a program they have in their posession. -- \ "Laugh and the world laughs with you; snore and you sleep | `\ alone." -- Anonymous | _o__) | Ben Finney From mail at microcorp.co.za Wed Aug 22 03:25:01 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 22 Aug 2007 09:25:01 +0200 Subject: Submit Your Python Scripts References: <1187718492.549619.164440@w3g2000hsg.googlegroups.com> <fafrkd$5n3$2@sea.gmane.org> Message-ID: <01e001c7e48d$e05a89a0$03000080@hendrik> "Steve Holden" <ste..nweb.com> wrote: > Ooh, goody. I just *live* to expose my scripts. Not. What? And miss out on all the wonderful special offers? ;-) - Hendrik From monty.python at fastmail.fm Tue Aug 21 11:59:34 2007 From: monty.python at fastmail.fm (David N Montgomery) Date: Tue, 21 Aug 2007 16:59:34 +0100 Subject: How to optimise this code? Message-ID: <1187711974.29800.1206519007@webmail.messagingengine.com> class testCase: def __init__(self, tc): if tc == 1:self.testCase1() if tc == 2:self.testCase2() if tc == 3:self.testCase3() if tc == 4:self.testCase4() if tc == 5:self.testCase5() if tc == 6:self.testCase6() def testCase1(self): print "tc1" def testCase2(self): print "tc2" def testCase3(self): print "tc3" def testCase4(self): print "tc4" def testCase5(self): print "tc5" def testCase6(self): print "tc6" def testCaseX(self): print "tcX" totalNumberOfTestCases = 6 x = 0 while x <= totalNumberOfTestCases: x += 1 testCase(x) This template code is working, but I envisage having 100+ test cases and am concerned about my useage of if statements. I would be grateful for any pointers as to how I can run all tests cases, regardless of how many, in a more efficient manner. Thank you in advance. From joesox at gmail.com Mon Aug 20 09:53:52 2007 From: joesox at gmail.com (JoeSox) Date: Mon, 20 Aug 2007 06:53:52 -0700 Subject: How do I call anonymous classes from imported modules? In-Reply-To: <8I8yi.6116$924.1335@newssvr23.news.prodigy.net> References: <mailman.2179.1187578824.22759.python-list@python.org> <fab13k$9tn$1@zinnia.noc.ucla.edu> <mailman.2182.1187582709.22759.python-list@python.org> <8I8yi.6116$924.1335@newssvr23.news.prodigy.net> Message-ID: <785694cd0708200653n79ef4fcfo1f2c02a59763956f@mail.gmail.com> On 8/19/07, James Stroud <jstroud at mbi.ucla.edu> wrote: > This was the poor design I was hinting to. do_foobar is type-checking > for ticker. "Casting" as you might think of it does not exist in python. > Creating new objects based on the values of existing objects (lets call > it "conversion" for lack of a better name) does (e.g. int(2.0)). But > this is not casting. Unless you have the power to re-author all of the > do_foobar()s to not type-check, you should create an instance of ticker > and pass that: > > t = ticker(param1, param2, parametc) > [...] > anobj.do_foobar(t) > > The "got nothing instead" means that you should have passed an > argument--and unfortunately whoever authored do_foobar() type-checked > for a ticker, which is not a desirable way to design an API. I designed the system using this 'tutorial' http://lucumr.pocoo.org/blogarchive/python-plugin-system With your help and revisiting the article I figured out that this call works: >>> for plugin in get_plugins_by_capability('do_foobar'): plg=plugin() print plg.do_foobar() -- Thanks, Joe From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Aug 31 05:07:17 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 31 Aug 2007 11:07:17 +0200 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188523096.427717.87380@x35g2000prf.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> <mailman.120.1188423362.28954.python-list@python.org> <1188430887.481586.106760@l22g2000prc.googlegroups.com> <mailman.159.1188499976.28954.python-list@python.org> <1188504811.019632.186580@x35g2000prf.googlegroups.com> <46d75116$0$401$426a74cc@news.free.fr> <1188517050.174081.265900@x40g2000prg.googlegroups.com> <46d75d33$0$6231$426a34cc@news.free.fr> <1188520454.996940.293030@m37g2000prh.googlegroups.com> <46d76790$0$410$426a74cc@news.free.fr> <1188523096.427717.87380@x35g2000prf.googlegroups.com> Message-ID: <46d7da35$0$6451$426a74cc@news.free.fr> Russ a ?crit : >> Pre and post conditions applying to the class ? Now that's an >> interesting concept. IIRC, Eiffels pre and post conditions only apply to >> methods, and I fail to see how they could apply to a class. But since >> you're an expert on the subject, I don't doubt you'll enlighten us ? > > I made a simple mistake. Excuse me. Oh wait ... aren't you one of the > sensitivity police who > laid into me for criticizing someone else. Nope, I'm one of the regular citizens here that tried to make you realize you were acting as an arrogant clueless newbie. > For the record, the guy I > criticized > made ridiculous assertions about DBC. For the record, the guy you treaded as he was a retarted knows much more than you about both Python and DbC. Thinking that someone is "ignorant" or "ridiculous" because he does not happen to share your opinions on some subject is certainly not what's I'd call an intelligent, civilized, respectful attitude. > All I did was to make a simple > mistake about > an inconsequential matter. All you did was persisting on being arrogant while showing your lack of knowledge on both Python and DbC. > No, pre and post conditions obviously don't > apply to classes, > but all I said was that that's how it appeared to me "at first > glance." > > If you are upset about my criticism of one of your colleagues, please > tell him to quite making > outrageous assertions about something he obviously knows little about. > I'm not upset. I'm actually trying to help you realizing the dumbness of your attitude. But I'm afraid this is going to be a lost cause... From mcl.office at googlemail.com Wed Aug 29 14:58:59 2007 From: mcl.office at googlemail.com (mcl) Date: Wed, 29 Aug 2007 11:58:59 -0700 Subject: Unzip: Memory Error Message-ID: <1188413939.834662.193180@y42g2000hsy.googlegroups.com> I am trying to unzip an 18mb zip containing just a single 200mb file and I get a Memory Error. When I run the code on a smaller file 1mb zip, 11mb file, it works fine. I am running on a hosted Apache web server I am using some code I found on the web somewhere. def unzip_file_into_dir(file, dir): #os.mkdir(dir, 0777) zfobj = zipfile.ZipFile(file) for name in zfobj.namelist(): if name.endswith('/'): os.mkdir(os.path.join(dir, name)) else: outfile = open(os.path.join(dir, name), 'wb') outfile.write(zfobj.read(name)) outfile.close() Error Traceback: Line 357 gives the Memory Error I have removed paths from file references ============================================== MemoryError Python 2.3.4: /usr/bin/python Wed Aug 29 19:38:22 2007 A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. /qlunzip.py 58 59 60 if __name__ == "__main__" : 61 unzipMain() 62 unzipMain = <function unzipMain> /qlunzip.py in unzipMain() 53 destdir = getDestDir() 54 print destdir, gv.nl 55 unzip_file_into_dir(zips, destdir) 56 57 global unzip_file_into_dir = <function unzip_file_into_dir>, zips = '/ pcodes.zip', destdir = '/pcodes/' /qlunzip.py in unzip_file_into_dir(file='pcodes.zip', dir='pcodes/') 34 else: 35 outfile = open(os.path.join(dir, name), 'wb') 36 outfile.write(zfobj.read(name)) 37 outfile.close() 38 outfile = <open file 'pcodes/pcodes.lst', mode 'wb'>, outfile.write = <built-in method write of file object>, zfobj = <zipfile.ZipFile instance>, zfobj.read = <bound method ZipFile.read of <zipfile.ZipFile instance>>, name = 'pcodes.lst' /usr/lib/python2.3/zipfile.py in read(self=<zipfile.ZipFile instance>, name='pcodes.lst') 355 # zlib compress/decompress code by Jeremy Hylton of CNRI 356 dc = zlib.decompressobj(-15) 357 bytes = dc.decompress(bytes) 358 # need to feed in unused pad byte so that zlib won't choke 359 ex = dc.decompress('Z') + dc.flush() bytes = '\xc4\x9d]\x93\xab8\x92\x86\xef7b\xff\x83\xa3/\xf6f\xba \xa7\xe7\xa2g#vwf6\x8a\x02\xc3\xd04\x8d\r\x1e\x7f\xdclP\xb6\xcav\x1c \xca\xd4`\xfbx...; \xb7jp\x06V{\xaf\xc3\xa5\xa7;\xdd\xd2\xaaD\x7f)c \xc6\x9d\x0f\xf2\xff-\xc9\x92\xc3\x1d\xa4`\xe0\xb8\x06)\x188\x9cA\n \x06\x8e\x1bPc\xf8\xf0\x1f', dc = <zlib.Decompress object>, dc.decompress = <built-in method decompress of zlib.Decompress object> MemoryError: args = () ============================================================ Any help much appreciated Richard From afriere at yahoo.co.uk Tue Aug 21 03:41:59 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 21 Aug 2007 00:41:59 -0700 Subject: Newbee Question In-Reply-To: <mailman.15.1187620149.26576.python-list@python.org> References: <mailman.15.1187620149.26576.python-list@python.org> Message-ID: <1187682119.353756.278840@i13g2000prf.googlegroups.com> Oh well since a few solutions have already been posted I thought I might add another, just so you at the very least you have to do some work making up your mind which one to choose. Using an incremental approach just to be different ... from decimal import Decimal normal = Decimal('0.04') over = Decimal('1.40) def calcStopPay (stops) : pay = Decimal('0.00') while stops : incr = normal if stops < 23 else over pay += incr stops -= 1 return pay #testing: for x in range(50) : print "Stop pay for %s stops: $%s" % (x, calcStopPay(x)) From fperez.net at gmail.com Thu Aug 2 18:23:07 2007 From: fperez.net at gmail.com (Fernando Perez) Date: Thu, 02 Aug 2007 16:23:07 -0600 Subject: Bug in execfile? References: <f8t80e$gvh$1@sea.gmane.org> <f8tgfq$e2u$1@sea.gmane.org> Message-ID: <f8tlgc$tld$1@sea.gmane.org> Ian Clark wrote: > Fernando Perez wrote: >> Hi all, >> >> (snip) >> >> I'm really, really puzzled by this. From reading the execfile() docs, I had >> the hunch to change the call to: >> >> execfile(fname,{}) >> >> and now the problem disappears, so I can keep on working. >> >> But I'm still very bothered by the fact that changing that first call 'if 0' >> to 'if 1' has any effect on the later call to runscript(). That really >> doesn't feel right to me... [...] > By default execfile works on the *current* namespace. So exec'ing a > script that modified it's global namespace will also modify the global > namespace of the calling module (see my first example). If you specify a > dictionary then execfile will use that as the global and local (maybe) > namespace of the file that it is running (hence the global namespace of > the calling module stays in tact per the second example). That is why > execfile(fname, {}) works for you, it doesn't pollute your current > namespace. It uses a different namespace when calling the file then is > being used by the calling module. Right, it makes complete sense that the first execfile() call puts the symbols in the global namespace, and that's why the failure disappears when calling the runscript wrapper. I just didn't think carefully enough, thanks. > No idea why your function failed though. *shrug* Yes, that still bothers me. That a simple def runscript(f): execfile(f) won't work just like execfile would is, at the least, a bit puzzling to me. Cheers, f From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Aug 10 06:10:53 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 10 Aug 2007 12:10:53 +0200 Subject: programmatically define a new variable on the fly In-Reply-To: <1186697500.024593.303820@x35g2000prf.googlegroups.com> References: <1186697500.024593.303820@x35g2000prf.googlegroups.com> Message-ID: <46bc39a0$0$400$426a74cc@news.free.fr> Lee Sander a ?crit : > Hi, > > I would like to define a new variable which is not predefined by me. > For example, > I want to create an array called "X%s" where "%s" is to be determined > based on the data I am processing. So, for example, if I the file > I'm reading has > g 99 > on the first line, I want to create a new variable called "Xg" whose > length > is 99. > I tried eval("Xg=[0]*99") but that did not work. > > any help would be greatly appreciated As others already pointed out, the canonical solution is to use a dict, and it's almost always the best solution - a variant being to use an object (eventually a module object) and dynamically add attributes to it using setattr()[1]. Now, for the corner case where you *really* want to dynamically create new names in the module itself, the solution is to use exec. But I would definitively *not* recommand this solution unless you really know what you're doing and why you're doing it. For the record, I did use this last solution twice in seven years. And it was mostly to avoid repeating boilerplate code in some low-level module of a framework. Definitively not a common case... [1] which, FWIW, doesn't make much differences since attributes are stored in dicts.... > Lee > From padraigkitterick at gmail.com Thu Aug 23 12:48:46 2007 From: padraigkitterick at gmail.com (=?iso-8859-1?B?UOFkcmFpZw==?=) Date: Thu, 23 Aug 2007 09:48:46 -0700 Subject: Python submodules and name imports In-Reply-To: <mailman.175.1187878437.32294.python-list@python.org> References: <mailman.175.1187878437.32294.python-list@python.org> Message-ID: <1187887726.005976.71600@l22g2000prc.googlegroups.com> On Aug 23, 2:58 pm, Frank Aune <Frank.A... at broadpark.no> wrote: > Hi, > > First take a look at: > > http://www.network-theory.co.uk/docs/pytut/Packages.html > > as I will use this module file layout as an example. > > If I want to do the following: > > from Sound import Effects > ... > Effects.echo.echofilte(bla bla) > > What will Sound/Effects/__init__.py need to contain then? I tried to define > the __all__ = ['echo','surround','reverse'] parameter in the init file, but > this only seems to be effective for " .. import *" statements. > > Is the correct way of accomplishing this to explicitly import the submodules > in sound/Effects/__init__.py? I'm looking for the "official" way of doing > this. > > Thank you, > Frank Aune You can put 'import echo' into sound/Effects/__init__.py. This is a widespread practice. You could also put 'from echo import *' into the file, if you wanted to have a single namespace for all methods in Effects. From raims at dot.com Wed Aug 15 14:40:17 2007 From: raims at dot.com (Lawrence Oluyede) Date: Wed, 15 Aug 2007 20:40:17 +0200 Subject: All names in the current module References: <87d4xowymq.fsf@wilson.homeunix.com> <1i2whvw.1qje42i1bh18bkN%raims@dot.com> <46c33e5a$0$36450$4fafbaef@reader5.news.tin.it> Message-ID: <1i2wmoi.vjjbh81fboc6kN%raims@dot.com> Fabio Z Tessitore <fabioztessitore at libero.it> wrote: > to get names' list you can simply call globals() Not strictly true. globals() returns the current's scope global vars. If you import a module in the current scope globals() won't display the names inside it. -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From half.italian at gmail.com Mon Aug 27 18:25:25 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Mon, 27 Aug 2007 15:25:25 -0700 Subject: Socket - gaierror In-Reply-To: <1188244050.029920.314700@i13g2000prf.googlegroups.com> References: <1188242671.182072.130150@r23g2000prd.googlegroups.com> <OIidnbjzCJVLu07bnZ2dnUVZ_gidnZ2d@comcast.com> <1188244050.029920.314700@i13g2000prf.googlegroups.com> Message-ID: <1188253525.718844.115500@q5g2000prf.googlegroups.com> On Aug 27, 12:47 pm, half.ital... at gmail.com wrote: > On Aug 27, 12:32 pm, Larry Bates <larry.ba... at websafe.com> wrote: > > > > > half.ital... at gmail.com wrote: > > > Hi all, > > > > I'm having trouble with the socket module resolving a hostname. It > > > seems like this is a system level problem, but I'm not even sure where > > > to start. I can ping the smtp server by name and IP, but when > > > smtp.SMTP("theHost") tries to get the hostname, it keeps giving me the > > > following error: > > > > File "bin/program.py", line 123, in notify > > > smtp = smtplib.SMTP("theHost") > > > > File "/usr/lib/python2.4/smtplib.py", line 255, in __init__ > > > addr = socket.gethostbyname(socket.gethostname()) > > > > gaierror: (-2, 'Name or service not known') > > > > I tried changing to a different smtp server, using an ip instead of a > > > host name. I could ping both boxes by name oor IP. > > > > any ideas? > > > > ~Sean > > > The specific error shown is a DNS resolution problem. Based on the > > URL "theHost" smtplib can't resolve to an IP address (which is what > > socket.gethostbyname does). You don't say what happened when you changed to ip, > > but I suspect it is a different error or some other problem. Maybe a firewall > > issue (port 25 not open?), but I'm just guessing. > > > -Larry > > Changing it to IP gives me the same exact error... > > File "bin/prgram.py", line 123, in notify > smtp = smtplib.SMTP("XXX.XXX.XXX.XXX") > > File "/usr/lib/python2.4/smtplib.py", line 255, in __init__ > addr = socket.gethostbyname(socket.gethostname()) > > gaierror: (-2, 'Name or service not known') > > Looks like the smtp port is closed on the client machine...doh Should > have gotten to that! > > Thank you. > > ~Sean I take it back, that wasn't the solution. I got it to work by haacking smtplib with a static host instead of the socket.gethostbyname(socket.gethostname()) call...but if I leave that in there I might get shot one day. What could cause the shell to be able to resolve the addresses properly, but not python? nnsswitch.conf ? I don't know enough about what's going on in the background. Any other ideas? Or should I try this on a unix board? ~Sean From donn at _vvanta._om Sun Aug 19 13:18:36 2007 From: donn at _vvanta._om (Donn Cave) Date: Sun, 19 Aug 2007 17:18:36 -0000 Subject: imaplib & Received: header(s)??? References: <mailman.2160.1187512222.22759.python-list@python.org> Message-ID: <13cgurcg663m003@corp.supernews.com> Quoth Petri Savolainen <petri.savolainen at iki.fi>: | Is there a way to get at the "Received" header(s) or is there something | in imaplib or imap server implementations that hides these? If not, what | IMAP FETCH command should be used? I've used for example | "BODY[HEADER.FIELDS (RECEIVED)]" and it always returns empty ("\r\n"). | Despite the Received - header existing, as demonstrated by taking a look | at message sources via desktop email clients. | | I need to get at the Received-for header to figure out at which address | we received an email. We subscribe to a number of mailing lists using | per-mailing-list addresses, and often, To: field contains something else | than our address, thus the need for Received-for. | | Any help would be much appreciated - this is baffling me and I've not | found anything recent that would help. "Anything recent"? If you're getting IMAP advice from comp.lang.python, I think it's fair to say you will need to be more resourceful. The RFC for IMAP4rev1 should be helpful. I don't know the IMAP to get a single header field, but my guess is that your error is there. Can you retrieve other fields that way? Does the one you're looking for appear in the data if you get the whole header, for example with 'RFC822.HEADER'? It certainly does in my Python IMAP client, and this would have at least helped you refine your question. Donn Cave From http Thu Aug 2 16:56:23 2007 From: http (Paul Rubin) Date: 02 Aug 2007 13:56:23 -0700 Subject: __call__ considered harmful or indispensable? References: <mailman.1527.1186079415.22759.python-list@python.org> <7xfy31smuq.fsf@ruckus.brouhaha.com> <46b2428b$0$19638$426a74cc@news.free.fr> Message-ID: <7x8x8tmz9k.fsf@ruckus.brouhaha.com> Bruno Desthuilliers <bdesth.quelquechose at free.quelquepart.fr> writes: > from foo import foo > x = foo(3) > > Or did I miss the point ??? The foo module might define a bunch of additional functions that you still want to be able to access in qualified form. For example it would somewhat clean up the interface to the python random module if you could say import random x = random() # get a random float between 0 and 1 while still having access to random.shuffle, random.choice, etc. From cajnnjonaj at fjireanjtjprodjuctijons.com Sat Aug 18 14:22:54 2007 From: cajnnjonaj at fjireanjtjprodjuctijons.com (Aaron) Date: Sat, 18 Aug 2007 13:22:54 -0500 Subject: yet another indentation proposal Message-ID: <fEZxi.8855$9W6.6492@fe103.usenetserver.com> Hello all. I realize that proposals dealing with alternatives to indentation have been brought up (and shot down) before, but I would like to take another stab at it, because it is rather important to me. I am totally blind, and somewhat new to Python. I put off learning Python for a long time, simply because of the indentation issue. There is no easy way for a screenreader user, such as my self, to figure out how much a particular line of code is indented. A sited person simply looks down the column to make sure that everything lines up. I, on the other hand, generally find my self counting a lot of spaces. Naturally, there are many other special circumstances in which depending on whitespace is impractical, but they have already been mentioned in previous threads on the topic, so I won't bother rehashing them. Borrowing from another proposal, I would submit that the opening block and closing block markers could be _{ and }_ respectively. If it seems that there is even a modicum of support, I'll write up a more complete proposal. But in short, an _{ will signify to the interpreter that one level of indentation is to be added to the current level, that all the statements that follow (until the closing _}) are to be understood to be at that level, and that all whitespace at the beginning of lines, or lack there of, is to be ignored. I realize that this would result in some esthetically ugly code, and so naturally a simple tool to convert this type of block indication back to "normal indented format" should also be developed. Any thoughts or suggestions? I sincerely hope that this proposal can be given some serious consideration, and not simply dismissed as sacrilege. There are many blind programmers, and I would hate to see them opt to learn other languages simply because of this one issue. Thanks. Aaron -- To reply directly, remove j's from email address. From david at nospam.spam Tue Aug 21 00:05:43 2007 From: david at nospam.spam (david) Date: Tue, 21 Aug 2007 14:05:43 +1000 Subject: wxpython thread exception crash Message-ID: <13ckp4nj0kt6583@corp.supernews.com> What am I doing wrong? I'm trying to capture stdErr in a multi-threaded program. This code crashes wxPython with /Py Assertion Error: C++ assertion "m_count=-1 || m_count=-2" failed/ What I'm trying to do is redirect stderr and stdout to a wxPython text control. In an ideal world, when the worker thread crashes, I should get a stderr message, with no effect on the main thread. In an alternate world, I should get an asynchronous exception in the main thread when there is an unhandled exception in the worker thread. In the sample below, the program crashes on the following print statement. Oddly enough, I do catch the unhandled worker exception in the main thread IF THE WORKER THREAD HAS NO INIT PARAMETER. Note: the init parameter is the only subtle thing in the code. Since this is a crash, the exact behaviour will depend on your environment. You may have difficulty seeing stdErr in some environments. Python 2.5, wxPython 2.7.2.0, Windows XP. (david) -------- import wx import sys import threading class ExceptionThread(threading.Thread): def __init__(self,initvar): threading.Thread.__init__(self); def run(self): raise "ET run" class RedirectText: def __init__(self,aWxTextCtrl): self.out=aWxTextCtrl def write(self,string): self.out.WriteText(string) def flush(self): pass class Frame(wx.Frame): def __init__(self, image=None, parent=None): wx.Frame.__init__(self, parent) self.text = wx.TextCtrl(self, style=wx.TE_MULTILINE|wx.TE_RICH2) #---- redirection window ---- redir=RedirectText(self.text) sys.stdout=redir sys.stderr=redir class App(wx.App): def OnInit(self): self.frame=Frame() self.frame.Show() self.Thread=ExceptionThread(1) self.Thread.start(); return True app = App() print 'trigger print failure' app.MainLoop() From andre.roberge at gmail.com Thu Aug 2 10:17:55 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Thu, 02 Aug 2007 14:17:55 -0000 Subject: Determining if file is valid image file In-Reply-To: <1186064098.587590.91210@g4g2000hsf.googlegroups.com> References: <1186064098.587590.91210@g4g2000hsf.googlegroups.com> Message-ID: <1186064275.652416.250540@d55g2000hsg.googlegroups.com> On Aug 2, 11:14 am, Andr? <andre.robe... at gmail.com> wrote: > Other than installing PIL, is there a "simple" way using Python only > to determine if a file is a valid image file? > > I'd be happy if I could at least identify valid images files for gif, > jpeg and png. Pointers to existing modules or examples would be > appreciated. > > The reason why I'd prefer not using PIL is that I'd like to bundle > such a function/module in my app. > > Andr? I should have added: I'm interesting in validating the file *content* - not the filename :-) From antroy at gmail.com Fri Aug 10 05:02:54 2007 From: antroy at gmail.com (Ant) Date: Fri, 10 Aug 2007 02:02:54 -0700 Subject: py2exe with python 2.5 In-Reply-To: <1186731595.139576.107660@e9g2000prf.googlegroups.com> References: <1186731595.139576.107660@e9g2000prf.googlegroups.com> Message-ID: <1186736574.092633.196100@d30g2000prg.googlegroups.com> On Aug 10, 8:39 am, vedrandeko... at v-programs.com wrote: > Hello, > > Now,I was install python 2.5 and remove python 2.4 completely.After I > write: > $ python mysetup.py py2exe > ....... > import py2exe_ util > ImportError: Module use of conflicts with this version of Python > > ...ok, I know what is a problem, I haven't remove python completely, > in my computer is one more folder Panda3D-1.4.0 but when I remove it > and all dll files include python24.dll, I cannot run python or make > that setup. > (That panda3d contain python) > > Regards, > Vedran Sounds like your path needs setting up properly. Try typing echo %PATH % into your console window to find out if Python2.5 is in the path. If you are using the default setup, then c:\Python25 should be on the path. -- Ant... http://antroy.blogspot.com/ From bj_666 at gmx.net Tue Aug 21 06:06:07 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Aug 2007 10:06:07 GMT Subject: File Read Cache - How to purge? References: <1187669203.698637.81990@i38g2000prf.googlegroups.com> <5ivl9fF3rafecU1@mid.uni-berlin.de> <1187688554.043448.212260@l22g2000prc.googlegroups.com> Message-ID: <5ivrofF3rafecU2@mid.uni-berlin.de> On Tue, 21 Aug 2007 02:29:14 -0700, Signal wrote: >> It (the whole file) is cached by the operating system totally independent >> of your program, so the memory used does of course not show up in the memory >> stats of your program... <snip> > > In this case the OS is Windows and monitoring the memory usage in Task > Manager, not through the script. The entire 759MB file is not being > cached in memory and only 2MB of memory is used when the script runs. If you read from a file the operating system usually caches all read data until there is no cache memory left, then some old cached data is replaced. So if you read the whole 756?MB file, even in small blocks, and have enough RAM chances are that the whole file is in the cache. And of course the memory consumption of the process is just the memory for interpreter, program and data. 2?MB sounds reasonable. >> > 2. Is there anyway to somehow to take advantage of this "caching" by >> > initializing it without reading through the entire file first? >> >> You mean reading the file without actually reading it!? :-) >> > > Think you misunderstood. > > What the "tests" are eluding to is: > > a. The whole file itself is NOT being cached in memory. Everything read is cached as long as there's enough space in the cache. > b. If there is mechanism to which it is "caching" something (which > obviously isn't the whole file itself), why not possibly take > advantage of it? How? Your speedup comes from data in caches, but the time putting it there was spend in the previous run. So you only gain something on subsequent reads on the file. Ciao, Marc 'BlackJack' Rintsch From ricaraoz at gmail.com Thu Aug 9 13:06:50 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 09 Aug 2007 14:06:50 -0300 Subject: Misleading wikipedia article on Python 3? In-Reply-To: <cfb58d850708082151u7196d854o140e6acf5df04e2c@mail.gmail.com> References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <mailman.1660.1186380664.22759.python-list@python.org> <7xzm15q8fy.fsf@ruckus.brouhaha.com> <1186583168.447608.114040@d55g2000hsg.googlegroups.com> <5hv7jeF3m75aqU1@mid.individual.net> <cfb58d850708082151u7196d854o140e6acf5df04e2c@mail.gmail.com> Message-ID: <46BB49AA.6030504@bigfoot.com> Evan Klitzke wrote: > On 8/8/07, greg <greg at cosc.canterbury.ac.nz> wrote: >> Istvan Albert wrote: >>> A solution would be writing the code with a logging function to begin >>> with, alas many times that is out of one's hand. >> If the code has been written with calls to a builtin >> print function, the situation isn't much better. You >> could monkeypatch the print function, but that's >> probably worse than swapping sys.stdout. > > You can easily modify print in a safe way. Here's an example, that > will work in any recent version of Python: > > import sys > > def print_(s): > print s > > def logger(method): > def wrapper(s): > sys.stderr.write('Logging: %s\n' % s) > method(s) > return wrapper > > print_ = logger(print_) > > print_('hello') > > > Running this code will do a regular print of 'hello', as well as > "logging" it to stderr. As a function, you can convert print wholesale > to another logging function, or wrap it transparently like this to > provide additional logging functionality. What do you find wrong with > this sort of "monkeypatching"? > foolish question maybe. Why wouldn't you do it this way ? def print_(s): print s def logger(m): sys.stderr.write('Logging: %s\n' % m) method(m) print_ = logger(print_) print_('hello') From rschroev_nospam_ml at fastmail.fm Sat Aug 11 13:33:57 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 11 Aug 2007 17:33:57 GMT Subject: Who told str() to round my int()'s!!! In-Reply-To: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> References: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> Message-ID: <9qmvi.47364$s5.1537219@phobos.telenet-ops.be> Adam W. schreef: > After a fair amount of troubleshooting of why my lists were coming > back a handful of digits short, and the last digit rounded off, I > determined the str() function was to blame: > >>>> foonum > 0.0071299720384678782 >>>> str(foonum) > '0.00712997203847' > > Why in the world does str() have any business rounding my numbers, and > how do I get around this? You could use repr() instead of str() (AFAIK that's what the interactive interpreter used to print your foonum), but in any case you should be aware of the limits inherent in floating point arithmetic and in conversions between decimal and binary fractions. See e.g. http://docs.python.org/tut/node16.html -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From rdm at rcblue.com Tue Aug 14 11:48:53 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 14 Aug 2007 08:48:53 -0700 Subject: Opinions about this new Python book? In-Reply-To: <1187096231.194685.86030@m37g2000prh.googlegroups.com> References: <mailman.1957.1187093157.22759.python-list@python.org> <1187096231.194685.86030@m37g2000prh.googlegroups.com> Message-ID: <20070814154913.D8C3C1E400A@bag.python.org> At 05:57 AM 8/14/2007, kyosohma at gmail.com wrote: >On Aug 14, 7:05 am, Dick Moores <r... at rcblue.com> wrote: > > I'd appreciate opinions about this new Python book. > > > > Title: Python Power!: The Comprehensive Guide > > Author: Matt Telles > > Publisher: Course Technology > > Pub. Date: Jul 27, 2007 > > Edition: 1st edition > > Binding: Paperback > > Pages: 508 > > ISBN: 1598631586 > > List Price: 34.99 USD > > > > The book on the publisher's website: <http://tinyurl.com/2dkhzg> > > > > And at BestBookDeal.com: > > <http://www.bestbookdeal.com/book/compare/1598631586> > > > > Thanks, > > > > Dick Moores > >I just got this book over the weekend. I'll start reading/skimming >through it this week and hopefully remember to get back to you. Thanks! > By the >way, why do you want to know? If the experts like it, I'll buy it. Dick From uymqlp502 at sneakemail.com Fri Aug 31 14:40:30 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Fri, 31 Aug 2007 11:40:30 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <mailman.217.1188577500.28954.python-list@python.org> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> <mailman.181.1188527203.28954.python-list@python.org> <1188537516.622167.115080@z24g2000prh.googlegroups.com> <mailman.217.1188577500.28954.python-list@python.org> Message-ID: <1188585630.539835.242460@i38g2000prf.googlegroups.com> Steve Holden wrote: > Frankly I am getting a little tired of they way you are unable to even > recognize that your readers may well have a sensible appreciation of the > difficulties about which you write. As has been pointed out already, > many readers here are extremely experienced programmers. > You said in an earlier post "that's not an insult", but that isn't > really up to you to decide. If it gives offense then it probably is, > whether it was intended to do so or not. You don't seem to appreciate > the insulting nature of your tone, and calling people bozos is not > likely to endear you to most c.l.py readers since it comes off as arrogant. You quoted what I wrote in reply to a personal attack against me, but you conveniently neglected to quote the original insult that I was replying to. OK, I'll concede that I shouldn't have replied to a personal insult with another insult, but why am I the only one at fault here rather than the guy who started it? Frankly, Mr. Holden, I'm getting a bit tired of the clannish behavior here, where "outsiders" like me are held to a higher standard than your "insider" friends. I don't know who you are, nor do I care what you and your little group think about me. As for DbC or what I call "self-testing code," I have come to the (tentative) realization that it is easy to implement in current Python -- without resorting to the "decorators" hack. OK, maybe this should have been obvious to me from the start, but here goes: All you really need to test the pre-conditions of a function is a call at the top of the function to another function that checks the inputs. To test the post-conditions, you just need a call at the bottom of the function, just before the return, that checks the return values. Those functions can also check the invariants. Then you define a global variable to switch all the self-test functions on or off at once. An advantage of this approach is that all the self tests can be put at the bottom of the file (or perhaps in another file) to reduce "clutter" in the primary code. I'd still prefer PEP 316, but this seems like a reasonable alternative. One suggestion I have for PEP 316 is to provide a way to place the self-test checks in a separate file to reduce clutter. From sjmachin at lexicon.net Mon Aug 20 21:30:45 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 20 Aug 2007 18:30:45 -0700 Subject: str().join() isn't working In-Reply-To: <1187634895.387910.179500@m37g2000prh.googlegroups.com> References: <496954360708200905i2100b32ag5983ab729e5d216f@mail.gmail.com> <mailman.4.1187633821.32294.python-list@python.org> <1187634895.387910.179500@m37g2000prh.googlegroups.com> Message-ID: <1187659845.080166.78060@l22g2000prc.googlegroups.com> On Aug 21, 4:34 am, kyoso... at gmail.com wrote: > In your statement, your script tries to > concatenate 2 lists to each other before it does the join, which is > impossible in Python. The "+" operator is only for addition and for > two or more strings. Not so; the + operator is "for" *any* class which has an __add__ method: >>> dir([]) ['__add__', ... <snip>] >>> a = [1,2,3] >>> b = [4,5,6] >>> c = a + b >>> c [1, 2, 3, 4, 5, 6] >>> b += c >>> b [4, 5, 6, 1, 2, 3, 4, 5, 6] >>> ('foo', 'bar') + (0, 1, 42, 666) ('foo', 'bar', 0, 1, 42, 666) >>> More than two strings? I don't think so; one + can have no more than two operands. From mccredie at gmail.com Mon Aug 13 19:28:45 2007 From: mccredie at gmail.com (Matimus) Date: Mon, 13 Aug 2007 23:28:45 -0000 Subject: (sort of) deterministic timing in Python In-Reply-To: <1i2si8h.1qc8f77i68gyeN%johnmfisher@comcast.net> References: <1i2si8h.1qc8f77i68gyeN%johnmfisher@comcast.net> Message-ID: <1187047725.390705.264580@i38g2000prf.googlegroups.com> > Do you see the difference? I get a true fixed interval from the first, > including the time to accomplish the event task(s). In the second case, > the sleep just gets tacked on at the end of the events, not very > deterministic (timing-wise). Check out the sched (scheduler) module http://docs.python.org/lib/module-sched.html. Here is an example that shows how to implement a loop (modified from the documentation): (warning, this will run forever) [code] import sched, time s=sched.scheduler(time.time, time.sleep) def print_time(): s.enter(1,1, print_time, ()) print "From print_time", time.time() def print_some_times(): print time.time() s.enter(5, 1, print_time, ()) s.run() if __name__ == "__main__": print_some_times() [/code] From cjw at sympatico.ca Wed Aug 15 20:54:13 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 15 Aug 2007 20:54:13 -0400 Subject: sub-classing the types in the builtin module datetime Message-ID: <fa077r$vqp$1@sea.gmane.org> I posted this about 5 hours ago, but it seems to have gone astray. cjw Jay Loden wrote: > Colin J. Williams wrote: > >> I wish to sub-class (if that's the right word) datetime and to use a >> different signature for the constructor. >> >> The second part has gone smoothly, but it is difficult to access the >> type's methods from the sub-class instance. >> >> I'm beginning to wonder whether it might might be simpler to write my >> own Date class. >> >> Does anyone have any comments please? >> >> Colin W. >> > > I think it would be most effective if you can post the code you're using that illustrates the issue, and what you're trying to do so that the list members can analyze the actual problem. Tracebacks etc are also welcome if applicable. > > -Jay > > Jay, Yes, I should have posted an example, but I thought that others might have experienced the problem. It is illustrated at the bottom of this script: # subClassing.py import datetime import new import sys import types class Date(datetime.datetime): ''' Date(s) -> a date object.__class__ where s is an 8 digit string''' def __new__(cls, YYmmdd): ''' YYmmdd is a string, in the form yyyymmdd i.e. 8 digits. or a 3-tuple of integers in the form (y, m, d) or a 6-tuple of integers in the form (y, m, d, h, m, s) ''' #todo needs a cleanup print '__new__' self= datetime.datetime.__new__(cls, 1, 1, 1) ln= len(YYmmdd) if type(YYmmdd) not in (types.StringType, types.TupleType): raise ValueError, str(YYmmdd) + ' is invalid for Date' ids= ('year', 'momth', 'day', 'hour', 'minute', 'second', 'microsecond') if type(YYmmdd) is types.StringType: if ln is 8: try: values= [int((YYmmdd[:4], YYmmdd[4:6], YYmmdd[6:8])[i]) for i in range(3)] except: raise ValueError, YYmmdd + ' should be an eight digit date string' else: raise ValueError, YYmmdd + ' should be an eight digit date string' elif ln in (3, 6): try: for i in range(ln): if type(YYmmdd[i]) == types.IntType: self.__setattr__(ids[i], YYmmdd[i]) else: raise ValueError, str(YYmmdd) + ' contains a non-integer' except: print sys.exc_info() raise ValueError, 'This should not occur, drop after tests #todo' else: raise ValueError, str(YYmmdd) + ' is not of an acceptable length' return datetime.datetime.__new__(cls, *values) def __repr__(self): return self.__class__.__name__ + ' : ' + str(self) def __str__(self): return "%04d%02d%02d" % (self.year, self.month, self.day) ## # Failures of subclassing ## def ctime(self): ## ''' ctime: Not available in Date. ''' ## pass ## def date(self): ## pass ## def now(self): ## pass ## def today(self): ## pass a= datetime.datetime(2007, 7, 31) d= Date('20070731') tm= datetime.time(1, 2) try: print a.today() # print d.today() # grief print a.now() # print d.now() # grief print a.combine(a, tm) # OK, but why not a.combine(tm)? # e= d.combine(d, tm) # grief print a.utcnow() # print d.utcnow() # grief print a.ctime() print d.ctime() except: print 'Grief' print sys.exc_info() Colin W. From kyosohma at gmail.com Fri Aug 10 09:20:31 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 10 Aug 2007 06:20:31 -0700 Subject: The Future of Python Threading In-Reply-To: <mailman.1826.1186743471.22759.python-list@python.org> References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <mailman.1826.1186743471.22759.python-list@python.org> Message-ID: <1186752031.688447.305630@z24g2000prh.googlegroups.com> On Aug 10, 5:57 am, Steve Holden <st... at holdenweb.com> wrote: > Justin T. wrote: > > Hello, > > > The nice thing is that this requires a fairly doable amount of work. > > First, stackless should be integrated into the core. Then there should > > be an effort to remove the reliance on the GIL for python threading. > > After that, advanced features like moving tasklets amongst threads > > should be explored. I can imagine a world where a single python web > > application is able to redistribute its millions of requests amongst > > thousands of threads without the developer ever being aware that the > > application would eventually scale. An efficient and natively multi- > > threaded implementation of python will be invaluable as cores continue > > to multiply like rabbits. > > Be my guest, if it's so simple. > > > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- I've been watching this Intel TBB thing and it sounds like it might be useful for threading. This fellow claims that he's going to play with SWIG and may use it to create bindings to TBB for Python, although he's starting with Perl: http://softwareblogs.intel.com/2007/07/26/threading-building-blocks-and-c/ Dunno what the license ramifications are though. Mike From gagsl-py2 at yahoo.com.ar Thu Aug 23 22:34:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 23 Aug 2007 23:34:25 -0300 Subject: redirect or cover .bat log References: <1187764689.836375.212730@z24g2000prh.googlegroups.com> <5j26bvF3s7lbpU2@mid.uni-berlin.de> <1187767578.925671.107000@q4g2000prc.googlegroups.com> <5j2br6F3r2avsU1@mid.uni-berlin.de> <1187787876.962883.66970@r34g2000hsd.googlegroups.com> <1187791309.427046.22400@q3g2000prf.googlegroups.com> <1187810295.951965.239300@m37g2000prh.googlegroups.com> <1187851372.042098.297240@q4g2000prc.googlegroups.com> Message-ID: <op.txjlfneqx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 23 Aug 2007 03:42:52 -0300, <vedrandekovic at v-programs.com> escribi?: > On 22 kol, 21:18, vedrandeko... at v-programs.com wrote: >> On 22 kol, 16:01, Gabriel Genellina <gagsl-... at yahoo.com.ar> wrote: >> > > > >> > Can I cover or redirect log of that process into my wx >> program? >> > > > >> > I'am using Windows XP SP2, and Python 2.5. >> >> > Try the subprocess module. For the single line command you posted >> > earlier, you don't even need the bat file: >> >> > import subprocess >> > p = subprocess.Popen(["python", "myscript_setup.py", "py2exe"], >> > stdout=subprocess.PIPE, stderr=subprocess.STDOUT) >> > p.wait() >> > output_from_process = p.stdout.readlines() > This,works fine except this last line: > > output_from_process = p.stdout.readlines() > > I get an error: > > p has not attribute stdout It should! p should be an instance of subprocess.Popen - perhaps you reassigned some other thing to that name? (sorry for using a one-letter name, that's not a good idea, you should use a much better name instead, in order to avoid naming conflicts) -- Gabriel Genellina From kay.schluehr at gmx.net Sat Aug 11 04:02:45 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 11 Aug 2007 01:02:45 -0700 Subject: Destruction of generator objects In-Reply-To: <20070809011441.05d7dfb6@cube.tz.axivion.com> References: <20070808002852.6228ae91@cube.tz.axivion.com> <1186613044.494852.306970@q75g2000hsh.googlegroups.com> <20070809011441.05d7dfb6@cube.tz.axivion.com> Message-ID: <1186819365.988117.232230@g4g2000hsf.googlegroups.com> On Aug 9, 1:14 am, Stefan Bellon <sbel... at sbellon.de> wrote: > On Wed, 08 Aug, MRAB wrote: > > Simple! :-) > > Sorry, I forgot to mention that I am forced to using Python 2.4. > > -- > Stefan Bellon It doesn't matter. You can use try...finally as well in Python 2.4. It's just not possible to use except and finally clauses in one statement such as: try: 1/0 except ZeroDivisionError: print "incident!" finally: print "cleanup" However in theory you don't really need finally but you can simulate it using nested try...except statements: ----- try: try: 1/0 try: print "cleanup" except Exception: raise FinallyException( sys.exc_info() ) except ZeroDivisionError: print "incident!" try: print "cleanup" except Exception: raise FinallyException( sys.exc_info() ) except Exception: exc_cls, exc_value, exc_tb = sys.exc_info() if exc_cls == FinallyException: fin_exc_cls, fin_exc_value, fin_exc_tb = exc_value[0] raise fin_exc_cls, fin_exc_value, fin_exc_tb else: print "cleanup" except Exception: raise FinallyException( sys.exc_info() ) raise exc_cls, exc_value, exc_tb ------- Note that this expression is regenerated from the above try...except..finally statement using Py25Lite ( see [1],[2] ) which is a tool used to provide some Python 2.5 constructs for programmers working with Python 2.4. [1] http://www.fiber-space.de/EasyExtend/doc/EE.html [2] http://www.fiber-space.de/EasyExtend/doc/Py25Lite/Py25Lite.html From mmacrobert at gmail.com Fri Aug 31 10:37:20 2007 From: mmacrobert at gmail.com (mmacrobert) Date: Fri, 31 Aug 2007 14:37:20 -0000 Subject: Fatal Python error using ctypes & python exceptions Message-ID: <1188571040.183691.20910@22g2000hsm.googlegroups.com> Hi Everyone, I've created a 'C' dll that is accessed via ctypes library containing a bunch of functions. I've successfully been able to use the functions. However, I would like to throw python exceptions from some of them. I throw them using: ::PyErr_SetString(::PyExc_RuntimeError, theErrorString); I crash the console when this function is invoked in the 'C' domain. I get an error stating: Fatal Python error: PyThreadState_Get: no current thread when the calling code in python is: try: cdll.MyDll.ThrowingFunction() except: print "An error has occurred" The dll is just a plain win32 'C' dll, built with an MS compiler. How do I throw python exceptions correctly? Is there some kind of "init" function that needs to be called? Any help much appreciated. Thanks, Martin From bj_666 at gmx.net Thu Aug 30 16:12:41 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Aug 2007 20:12:41 GMT Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <87hcmhebwv.fsf@benfinney.id.au> <1188492060.983148.90000@r34g2000hsd.googlegroups.com> Message-ID: <5jomlpFh543U3@mid.uni-berlin.de> On Thu, 30 Aug 2007 09:41:00 -0700, zzbbaadd wrote: > On Aug 30, 12:09 am, Ben Finney <bignose+hates-s... at benfinney.id.au> > wrote: >> zzbba... at aol.com writes: >> > What's with the index() function of lists throwing an exception on not >> > found? >> >> It's letting you know that the item isn't in the list. There's no >> sensible return value from an "index" function in that condition. > > for str: > > find( sub[, start[, end]]) > Return the lowest index in the string where substring sub is > found, such that sub is contained in the range [start, end]. Optional > arguments start and end are interpreted as in slice notation. Return > -1 if sub is not found. But that is a valid index into a string! So this may go unnoticed if one doesn't check after every call to `str.find()`. And that method is going away in Python?3.0. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Fri Aug 24 00:06:33 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 24 Aug 2007 01:06:33 -0300 Subject: advice about `correct' use of decorator References: <46C4B097.4080309@fmed.uba.ar> <740c3aec0708170529s6f7e7fe2l8c92771c2d0a51d4@mail.gmail.com> <46C5C9AE.5020508@fmed.uba.ar> <mailman.112.1187787625.32294.python-list@python.org> <1187792001.935204.42330@e9g2000prf.googlegroups.com> <740c3aec0708230520h6a92a29ar180efed41730f563@mail.gmail.com> Message-ID: <op.txjpo7ixx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 23 Aug 2007 09:20:21 -0300, BJ?rn Lindqvist <bjourne at gmail.com> escribi?: > On 8/22/07, Gabriel Genellina <gagsl-py2 at yahoo.com.ar> wrote: >> On 22 ago, 10:00, "BJ?rn Lindqvist" <bjou... at gmail.com> wrote: >> > As I said, you can accomplish the exact same thing by calling a >> > function from within the function that requires the user to be logged >> > in. >> > >> > def change_pass(): >> > check_user_logged_in() >> > ... more stuff here... >> > >> > is less complex (and therefore preferable) than: >> > >> > @check_user_logged_in >> > def change_pass(): >> > ... more stuff here... >> > >> > An important principle in engineering is that you should always strive >> > to make your design as simple as possible. If you have two equal >> > designs, you should always choose the one that is simpler because >> > simple things are easier to understand than complex things. >> >> I don't see the complexity in this case - both are a single line of >> code. Any internal complexity is hidden by the language. In fact, I > > "Hiding" doesn't reduce complexity, quite the opposite. >> consider the decorated function simpler than the other: its body >> represents exactly what the function does, without any distracting >> precondition calls. > > Think about how the decorator is implemented. It is a high order > function, taking a function and returning a new function. Something > like this: > > def check_user_logged_in(func): > def f(*args, **kwargs): > if global_state.the_user.is_logged_in: > return func(*args, **kwargs) > return show_login_page() > return f I think there is a semantic problem, perhaps we are not talking about the same thing. I'm considering the software complexity AS PERCEIVED BY THE PROGRAMMER, looking at the interactions between a program and a programmer who is working on some task; some people would say "cognitive complexity" to make it clear. Coupling and cohesion are some of its main attributes. I'm *not* talking about "algorithmic complexity", by example; nor any other aspect of complexity. Given this frame, I think you may understand why "hiding details" reduces complexity: the programmer does not have to think/worry about those particular items. Which API is more complex: one in which you can play a movie with just a single call like PlayMovie(Title), or one on which you must call a zillion functions to firtly initialize the stream format, configure the display, disable undesired user interfase elements, locate the movie file, load it in chunks, etc.? The first one is certainly much simpler to use (simpler = less complex), and maybe internally it calls the same functions as the second one, but nobody cares. Let's look at a generator. Internally it's a complex thing: it has to keep its execution state, the stack frames, local and global variables... But all that internal complexity is hidden by the language, and the Python programmer only sees a continuable function. And that's great. Suppose you have a producer bound to a consumer - they are tightly coupled and that makes the code too complex. Using a generator you can decouple consumer from producer, making the code a lot simpler. What's important is how the programmer sees it; it doesn't matter if the underlying structures and tools were hard to program; it does matter if *now*, using those structures and tools, the programmer can write simpler and more comprehensible code (and faster, and less likely to contain bugs). Back to your example, the fact that a decorator builds a higher order function, does NOT make it more complex - because the programmer does not see that. In fact, hiding the details makes it simpler. >> The decorator has some advantages: can have syntax support on your >> editor, can perform some registering/logging, it's even easier to >> quickly check visually if it's here. > > The decorator has just as many disadvantages. For example, what if you > want to redirect back to the change_pass page once the user has > pressed the Login button on the login_page? Or if you want to show > different login pages depending on user properties? How much control > flow do you really want to "hide" in your decorator? I can't see the disadvantages; using a decorator, you have available the function being decorated, and you can manipulate it as you wish. -- Gabriel Genellina From pyth0nc0d3r at gmail.com Thu Aug 23 11:15:11 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Thu, 23 Aug 2007 09:15:11 -0600 Subject: I know almost all basics Message-ID: <eb79828c0708230815o6e3a123k857e65e3b3030bb@mail.gmail.com> Now I'm moving more into the gaming world. What libs/modules would you recommend? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070823/564eb368/attachment.html> From deets at nospam.web.de Tue Aug 21 15:50:54 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 21 Aug 2007 21:50:54 +0200 Subject: Partial Blur In-Reply-To: <1187724586.607512.227110@m37g2000prh.googlegroups.com> References: <1187724586.607512.227110@m37g2000prh.googlegroups.com> Message-ID: <5j0u1cF3r4pp5U1@mid.uni-berlin.de> chicorbleak at gmail.com schrieb: > Hello, > > I'm looking for an image manipulation library which would allow me to > blur an oval-shaped part of my picture, instead of the whole thing. I > couldn't find a way to do this using the > tools I see in the API of Python Imaging Library. Create a copy of the picture (or a rectangle just large enough) with e.g. Image.crop() followed by a load. Then blur that image using the appropriate filter. Using the composite-function you should be able to compose the old image with the new + an oval mask. HTH, Diez From lars.wessman at gmail.com Sun Aug 12 19:52:33 2007 From: lars.wessman at gmail.com (Lars Wessman) Date: Sun, 12 Aug 2007 16:52:33 -0700 Subject: Apache cgi and multiple versions of python Message-ID: <1186962753.479222.37110@22g2000hsm.googlegroups.com> I am running OS X and have Python 2.3 installed with the system and have installed 2.5 using the installer available at pythonmac.org. I am running the system install of Apache 1.3 and I am not using mod_python. When Apache 1.3 runs Python cgi scripts, the cgitb output indicates that the verision of python being used is 2.3. I would like it to use Python 2.5. Does anyone have any advice on how to get Apache to use the version of Python I would like it to? From Werner.Merkl at fujitsu-siemens.com Wed Aug 29 07:53:41 2007 From: Werner.Merkl at fujitsu-siemens.com (Werner) Date: Wed, 29 Aug 2007 04:53:41 -0700 Subject: self extracting zipefile (windows) and (standard module) zipefile Message-ID: <1188388421.010643.19050@50g2000hsm.googlegroups.com> Hi, I try to read (and extract) some "self extracting" zipefiles on a Windows system. The standard module zipefile seems not to be able to handle this. >>> fName = r"C:\tmp\mySelfExtratingFile.exe" >>> import zipfile >>> zipefile.is_zipfile(fName)) False Is there a wrapper or has some one experience with other libaries to extract those files? Thanks in advance Werner From aine_canby at yahoo.com Tue Aug 21 05:29:59 2007 From: aine_canby at yahoo.com (aine_canby at yahoo.com) Date: Tue, 21 Aug 2007 02:29:59 -0700 Subject: The folder a script is executed in In-Reply-To: <1187688437.358293.322460@22g2000hsm.googlegroups.com> References: <1187687436.476773.276550@22g2000hsm.googlegroups.com> <1187688437.358293.322460@22g2000hsm.googlegroups.com> Message-ID: <1187688599.348139.297150@o80g2000hse.googlegroups.com> On 21 Aug, 11:27, Ant <ant... at gmail.com> wrote: > On Aug 21, 10:10 am, aine_ca... at yahoo.com wrote: > ... > > > myLocation = GetMyLocation() > > print myLocation > > > >> C:/folder > > Do you mean the folder containing the script? Or the current working > directory? > > If the former, then look at os.path.split(sys.argv[0])[0] > If the latter, try something like: os.path.abspath(os.curdir) > > -- > Ant... > > http://antroy.blogspot.com/ The following code - import os import sys print os.getcwd() + "." print os.path.split(sys.argv[0])[0] + "." gives me - C:\Documents and Settings\me\Desktop. . Im running Python 2.2 on NT From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Aug 13 18:42:53 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 14 Aug 2007 00:42:53 +0200 Subject: chmod g+ Equivalent References: <1187042290.821786.178420@19g2000hsx.googlegroups.com> Message-ID: <5ic53dF3pi903U1@mid.individual.net> milan_sanremo wrote: > I've read the documentation on os.chmod() and can implement all > the standard commands, but what is the syntax for the equivalent > of chmod g + to set the group id? Group ID is set using os.chown. Regards, Bj?rn -- BOFH excuse #190: Proprietary Information. From dejanews at email.com Sun Aug 19 08:16:14 2007 From: dejanews at email.com (samwyse) Date: Sun, 19 Aug 2007 12:16:14 GMT Subject: Symbolic Link In-Reply-To: <1187475296.173269.263080@k79g2000hse.googlegroups.com> References: <1187475296.173269.263080@k79g2000hse.googlegroups.com> Message-ID: <iwWxi.28394$RX.20505@newssvr11.news.prodigy.net> mosscliffe wrote: > I am trying to create a link to a file, which I can then use in an > HTML page. > > The system is Linux on a hosted web service, running python 2.3. > Other than that I have no knowledge of the system. > > The link is created OK, but when I try to use it as filename for the > IMG TAG, it does not get displayed. The page source of the created > page is pointing to the link as temp/test1.jpg What are you trying to do that you can't use the original file instead of creating a link? There might be a way to side-step the entire problem. From JHoover at fbi.gov Wed Aug 1 01:47:25 2007 From: JHoover at fbi.gov (Gordon Airporte) Date: Wed, 01 Aug 2007 01:47:25 -0400 Subject: Any way to monitor windows network connection? In-Reply-To: <1185939997.135825.310080@z24g2000prh.googlegroups.com> References: <1185939997.135825.310080@z24g2000prh.googlegroups.com> Message-ID: <_ICdnc3T261KgC3bnZ2dnUVZ_oHinZ2d@comcast.com> momobear wrote: > hi, Is there any way to show me detailed listings of all TCP and UDP > endpoints in my microsoft windows XP in python way? > thanks. Unless you're looking for a programming exercise: http://www.microsoft.com/technet/sysinternals/Utilities/TcpView.mspx From max at alcyone.com Thu Aug 9 17:25:35 2007 From: max at alcyone.com (Erik Max Francis) Date: Thu, 09 Aug 2007 14:25:35 -0700 Subject: Puzzled by "is" In-Reply-To: <mailman.1814.1186692638.22759.python-list@python.org> References: <20070809194105.39BD11E400A@bag.python.org> <f9frbl$dps$1@sea.gmane.org> <mailman.1814.1186692638.22759.python-list@python.org> Message-ID: <frSdnZ1UppvSGybbnZ2dnUVZ_iydnZ2d@speakeasy.net> Grzegorz S?odkowicz wrote: > That's just theorisation but I'd rather expect the interpreter simply > not to create a second tuple while there already is an identical one. > This could save some memory if the tuple was large (Although by the same > token comparison of large tuples can be expensive). Admittedly the empty > tuple is a special case but then 'Special cases aren't special enough to > break the rules'. > > A bit odd. It doesn't save time if you have to check through all the existing tuples for matches ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis Chance favors the trained mind. -- Louis Pasteur From kalin at el.net Sun Aug 12 17:04:13 2007 From: kalin at el.net (kalin mintchev) Date: Sun, 12 Aug 2007 17:04:13 -0400 (EDT) Subject: cgi and headers In-Reply-To: <49261.74.2.36.140.1186952205.squirrel@mail.el.net> References: <49261.74.2.36.140.1186952205.squirrel@mail.el.net> Message-ID: <49292.74.2.36.140.1186952653.squirrel@mail.el.net> nevermind... i'm not sure why the xml header didn;t work before and now it does... thanks.... > > hi there... > > i'm starting to work with python cgi scripts using ajax. > one problem i have is that the cgi module doesn;t do (apparently) anything > without the -- print "Content-type: text/html\n" -- line in the script. > > the issue is that the output of the script has to be an xml file and not > an html. it's not really a problem for any normal browser but the retarded > explorer thing doesn;t process the xml unless it gets back the xml header. > > so my scripts work fine on mozilla but not in explorer because of the > missing xml header. > > what would be the correct solution for this? > > thanks.... > > > From johnmasters at oxtedonline.net Wed Aug 15 14:56:01 2007 From: johnmasters at oxtedonline.net (John K Masters) Date: Wed, 15 Aug 2007 19:56:01 +0100 Subject: replacement for string.printable Message-ID: <20070815185601.GA9275@spookie1.spookiegate> >From what I have read the string module is obsolete and should not be used but I am working on a project that parses printable files created in a DOS program and creates a web page for each file. I am using the string.printable constant to determine which characters should be kept; the files contain many print control codes. There seems to be nothing like this in the string methods. isalnum() seems the nearest but gives false for '+' '!' etc. I realise I could define a global string to cover this but wondered if there was another, better, way Regards, John -- War is God's way of teaching Americans geography Ambrose Bierce (1842 - 1914) From ehsan.khoddam at gmail.com Fri Aug 3 17:32:19 2007 From: ehsan.khoddam at gmail.com (Ehsan) Date: Fri, 03 Aug 2007 14:32:19 -0700 Subject: downloading files In-Reply-To: <mailman.1584.1186168229.22759.python-list@python.org> References: <1186166920.757662.269340@o61g2000hsh.googlegroups.com> <mailman.1584.1186168229.22759.python-list@python.org> Message-ID: <1186176739.765447.262720@w3g2000hsg.googlegroups.com> On Aug 3, 10:10 pm, Steve Holden <st... at holdenweb.com> wrote: > Ehsan wrote: > > I foundd this code in ASPN Python Cookbook for downloading files in > > python but when it finished downloading files the files became > > corrupted and didn't open, the files in internet havn't any problem: > > > def download(url,fileName): > > """Copy the contents of a file from a given URL > > to a local file. > > """ > > import urllib > > webFile = urllib.urlopen(url) > > localFile = open(fileName, 'w') > > localFile.write(webFile.read()) > > webFile.close() > > localFile.close() > > download('http://www.2shared.com/download/1839752/cd520048/ > > xpersia14.3gp?tsid=20070803-143313-49566ea2', 'xpersia4.3gp' ) > > I'm guessing there are binary files and you are running on Windows, > which is inserting a carriage return before ebery newline. Try > > localFile = open(fileName, 'wb') > > to avoid thus behavior. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading -------------- Hide quoted text - > > - Show quoted text - thanx Steve It works but could you explain more what's wrong with just 'w'? From irmen.NOSPAM at xs4all.nl Sat Aug 11 05:21:38 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sat, 11 Aug 2007 11:21:38 +0200 Subject: question: howto transfer objects between server and client? In-Reply-To: <1186823076.923464.294120@57g2000hsv.googlegroups.com> References: <1186823076.923464.294120@57g2000hsv.googlegroups.com> Message-ID: <46bd7faa$0$239$e4fe514c@news.xs4all.nl> OpenPavilion wrote: > Since XMLRPC has limited features: Is there any other server/client > technique to transfer objects (not strings, or dictionaries, but self > defined object types) ? Take a look at Pyro; http://pyro.sourceforge.net --Irmen From david at asdf.asdf Fri Aug 24 00:51:23 2007 From: david at asdf.asdf (bambam) Date: Fri, 24 Aug 2007 14:51:23 +1000 Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com> <13cr00ujte4qs09@corp.supernews.com> Message-ID: <13csoubsnlcji41@corp.supernews.com> Wos! Several different thoughts: An object using yield to return only the relevant pages, one at a time. Pop to remove the items from the list. A dictionary to map between the strings and the integers. The dictionary was particularly unexpected. Eventually, I plan to change the string ports to device names. On the other hand, it looks like the only reason I have port numbers is to use as an index in things like this. After examining your suggestion, I realised that another thing I am interested in could be generalised: I want the complement of the set of ports in pages, given a universal set in tempList. Ignoring the break condition for the moment, and my problem with int(port)/str(port), would you have offered a different solution if I had asked for the relative complement of a small set? a= ['a','b','c'] b= ['b'] c= a-b #set theoretic difference, a\b, a.~b, ['a','c'] Steve. "Scott David Daniels" <daniels at dsl-only.net> wrote in message news:13cr00ujte4qs09 at corp.supernews.com... > bambam wrote: >> Would someone like to suggest a replacement for this? It works ok, >> but it doesn't look like any of the other code: >> >> tempList = ['1','2','3','4','5','6','7','8'] >> sampleList=[] >> for port in tempList: >> pagefound = False >> for i in range(self.parent.GetPageCount()): >> page=self.parent.GetPage(i) >> if hasattr(page, "port"): >> if page.port == int(port): >> pagefound=True >> if not pagefound: >> sampleList.append(port) >> >> Thanks! >> >> > Look at good questions. This is a _very_ underspecified question. > > One stab at mindreading: > > def ported_pages(self): > for i in range(self.parent.GetPageCount()): > if hasattr(page, 'port'): > yield page > > ... > tempList = ['1','2','3','4','5','6','7','8'] > missing = dict((int(v), v) for v in tempList) > for page in self.ported_pages(): > if page.port in missing: > missing.pop(page.port) > if not missing: > break > sampleList = missing.values() > ... > > -Scott David Daniels From lvirden at gmail.com Fri Aug 24 11:30:01 2007 From: lvirden at gmail.com (Larry W. Virden) Date: Fri, 24 Aug 2007 08:30:01 -0700 Subject: Regular expression use In-Reply-To: <famdl6$p9j$1@gemini.csx.cam.ac.uk> References: <famdl6$p9j$1@gemini.csx.cam.ac.uk> Message-ID: <1187969401.608508.137770@z24g2000prh.googlegroups.com> On Aug 24, 6:58 am, n... at cus.cam.ac.uk (Nick Maclaren) wrote: > I am interested in discovering what > people actually use regular expressions for. Hmm - let's see. I tend to use regular expressions when I am writing code that needs to search through output to find certain patterns. I also use them to convert text in one format into another format. I also frequently use them to validate input - if I need input to be all alphabetics, or a properly formatted floating point number, etc. From van.lindberg at gmail.com Fri Aug 3 16:43:27 2007 From: van.lindberg at gmail.com (VanL) Date: Fri, 03 Aug 2007 15:43:27 -0500 Subject: Trying to find zip codes/rest example In-Reply-To: <f8vv2k$i1f$1@sea.gmane.org> References: <f8vhct$3g6$1@sea.gmane.org> <f8vv2k$i1f$1@sea.gmane.org> Message-ID: <f9041g$1q5$1@sea.gmane.org> Terry Reedy wrote: > No, but does the localflavor entry on > http://code.djangoproject.com/browser/django/trunk/docs/add_ons.txt?rev=5118 > help? (found with Google) Thanks, but no. A friend asked for advice about implementing a password-checking interface; I remembered that the method described in the article seemed particularly slick. I wanted to refer it to him as a sample "best practices" link. From frank at chagford.com Wed Aug 22 04:44:55 2007 From: frank at chagford.com (Frank Millman) Date: Wed, 22 Aug 2007 01:44:55 -0700 Subject: Newbie question about a web server In-Reply-To: <1187593367.402094.235410@g4g2000hsf.googlegroups.com> References: <1187593367.402094.235410@g4g2000hsf.googlegroups.com> Message-ID: <1187772295.139986.131280@q3g2000prf.googlegroups.com> Frank Millman wrote: > Hi all > > I have just started to dabble in writing my own web server. > > I googled for 'python web server', and this is the first hit - > > http://fragments.turtlemeat.com/pythonwebserver.php > [...] > > When responding to the POST data received, it sends a 301 response, no > headers, and then the html page. > > This works with a Firefox browser on Linux, but MSW IE6 displays 'the > page cannot be displayed'. > > According to the notes, "You don't have to know much about the HTTP > protocol at all. Except some basic that when the client request > something it is a "GET", and when the client sends something it is in > our case a POST. Some basic responce codes like 200 is OK for GET, and > 404 is file not found, 301 is OK for a Post." > > I googled for 'http response code 301', and found that it is actually > a redirection code. It seems that the notes are misleading. > Thanks to Chris and I V for your responses, which helped me to understand what is going on. I contacted the original author, Jon Berg, and (with his permission) I show below his reply. ============================================= Hello, > I read your article on 'Making a simple web server in Python'. Thanks > a lot for this. It explains quite a few concepts in very few lines, > and is a good introduction to the subject. Great! > I have one question. When you respond to the POST message, you send a > 301 response, followed by the html page generated. This works using > Firefox on Linux, but MSW IE6 gives a 'Page cannot be displayed' error. > > If I change it to sending a 200 response, followed by a content-type > header, followed by the html page, it works correctly on both platforms. > > According to what I have read, 301 is actually a redirection response. > Can you explain how this is supposed to work, and why it does not work on IE6. You are correct that it is a redirect response. I think the script is a bit incomplete in this respect. Normally when you want to redirect a POST request it can be done by sending a redirect response, but it also requires the "Location:" header to work. I think this is what happens and maybe confusing to IE, but luckily Firefox is better at guessing what to do and just displays the content and gives up, right? It also seems to be more correct to return 302 or 304, when redirecting a POST request. There is also this design pattern to redirect after a POST that can be useful: http://en.wikipedia.org/wiki/Post/Redirect/Get Other that that if you don't want the redirecting stuff, the correct thing would then be to just return a 200 response code. And the content returned will be displayed in the browser. More about POST: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5 Have a nice evening. Jon Berg. ============================================= This confirms exactly the responses from Chris and I V. I replied to Jon asking if he could update his page to avoid confusing other newbies, especially as it comes up first in a google search. His reply - "I can look into updating that page in the weekend. I have been a bit lazy doing anything with that site for a while." Just thought I would report all the above to tidy up any loose ends. Frank From s-mar at nospam.nospam Wed Aug 22 01:13:09 2007 From: s-mar at nospam.nospam (Scott M.) Date: Wed, 22 Aug 2007 01:13:09 -0400 Subject: Free Air Conditioners!!!!!! References: <1187738115.972271.94080@r23g2000prd.googlegroups.com> Message-ID: <OXgBfsH5HHA.1212@TK2MSFTNGP05.phx.gbl> Oh my God! How did you know?!! You were so smart to post that here! <managerrrr at gmail.com> wrote in message news:1187738115.972271.94080 at r23g2000prd.googlegroups.com... > http://freeairconditioners.blogspot.com/ > From kyosohma at gmail.com Mon Aug 13 16:32:42 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 13 Aug 2007 13:32:42 -0700 Subject: wxPython - drawing without paint event In-Reply-To: <5ibsenF3nq29uU2@mid.individual.net> References: <1186710391.148396.113490@d30g2000prg.googlegroups.com> <1186738813.373909.96230@x35g2000prf.googlegroups.com> <1186796567.331348.42450@q3g2000prf.googlegroups.com> <5i5l0dF2lortaU1@mid.individual.net> <1186883988.585048.16590@m37g2000prh.googlegroups.com> <5i8befF3o5no1U1@mid.individual.net> <1186928595.014008.61950@b79g2000hse.googlegroups.com> <5i98bsF3nmbavU1@mid.individual.net> <1186951326.218981.17820@b79g2000hse.googlegroups.com> <mailman.1885.1186953122.22759.python-list@python.org> <1186966731.768800.81620@x40g2000prg.googlegroups.com> <5ibsenF3nq29uU2@mid.individual.net> Message-ID: <1187037162.322154.319540@x40g2000prg.googlegroups.com> On Aug 13, 3:15 pm, Bjoern Schliessmann <usenet- mail-0306.20.chr0n... at spamgourmet.com> wrote: > kyoso... at gmail.com wrote: > > While the book does have issues, it is better (in my opinion) than > > the only published Tkinter book, although both books are now > > outdated. > > Outdated to a certain limit. It's quite a bit more recent than those > many tutorials around still today using > "from wxpython.wx import *". > > > As with all programming, if you don't practice, you won't learn. > > True. > > Regards, > > Bj?rn > > -- > BOFH excuse #103: > > operators on strike due to broken coffee machine I guess I haven't looked up any wxPython tutorials. I typically use a combination of the wxPython wiki, the demo and the WIA book for my work. Mike From padraigkitterick at gmail.com Thu Aug 23 05:43:36 2007 From: padraigkitterick at gmail.com (Padraig) Date: Thu, 23 Aug 2007 02:43:36 -0700 Subject: Baby Steps, optionDB In-Reply-To: <Uk7zi.1531$vU4.979@nlpi068.nbdc.sbc.com> References: <Uk7zi.1531$vU4.979@nlpi068.nbdc.sbc.com> Message-ID: <1187862216.183609.89810@r23g2000prd.googlegroups.com> On Aug 23, 4:41 am, "W. Watson" <wolf_tra... at invalid.com> wrote: > root.option_readfile('optionDB') Just leave out the line which tries to read in the non-existent config file... From hniksic at xemacs.org Fri Aug 31 10:26:05 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 31 Aug 2007 16:26:05 +0200 Subject: fcntl problems References: <1188512377.441241.107900@q4g2000prc.googlegroups.com> <1188515889.352267.220790@q5g2000prf.googlegroups.com> <mailman.186.1188541398.28954.python-list@python.org> <1188568022.988154.188230@y42g2000hsy.googlegroups.com> Message-ID: <87ps13rdaa.fsf@mulj.homelinux.net> "mhearne808[insert-at-sign-here]gmail[insert-dot-here]com" <mhearne808 at gmail.com> writes: > I think I'm still confused. What Miles tried to tell you is that you should call fcnt.flock from both PA and PB. In the example you posted, you failed to call it from PB. No lock call, so no locking happened. > I have a script that will be run from a cron job once a minute. One > of the things this script will do is open a file to stash some > temporary results. I expect that this script will always finish its > work in less than 15 seconds, but I didn't want to depend on that. > > Thus I started to look into file locking, which I had hoped I could > use in the following fashion: > > Process A opens file foo > Process A locks file foo > Process A takes more than a minute to do its work > Process B wakes up > Process B determines that file foo is locked > Process B quits in disgust > Process A finishes its work File locking supports that scenario, as you suspected. You need to use flock with LOCK_EX|LOCK_NB. If the call succeeds, you got the lock. If you get an exception whose errno is EWOULDBLOCK, you quit in disgust. From david at asdf.asdf Mon Aug 27 00:07:16 2007 From: david at asdf.asdf (bambam) Date: Mon, 27 Aug 2007 14:07:16 +1000 Subject: beginner, idomatic python 2 References: <13csjmeaoqh9le3@corp.supernews.com> <1187927388.173203.298660@e9g2000prf.googlegroups.com> Message-ID: <13d4jfjfogbvq6f@corp.supernews.com> Thank you. I didn't reply earlier because I was trying to get my head around what you wrote, which was strange and foreign to me. It seems to me that the dictionary object you suggested is a direct replacement for the function code, only more efficient because the case table is internalised with a hash table, and the original if/elif/else case table was unlikely to be implemented as a hash table. And presumably, it is idiomatic because Python programmers expect to use dictionaries for their lookup tables. You have answered a question I didn't know enough to ask :~) --which is why I started with the general question, so I don't feel too stupid about that --. And now I wonder about the 'other' question. Should I consider dynamically overriding the methods in my 'Device' class, instead of creating separate classes for the Psp and Pwr devices? I could create an object of the base Device class, and at init I could make sure the methods were connected for a Psp or a Pwr device. When (if ever) is that a good idea? Steve. "Dan Bishop" <danb_83 at yahoo.com> wrote in message news:1187927388.173203.298660 at e9g2000prf.googlegroups.com... > On Aug 23, 10:21 pm, "bambam" <da... at asdf.asdf> wrote: >> Would someone like to suggest a replacement for this? This is a >> function that returns different kinds of similar objects, depending >> on what is asked for. PSP and PWR are classes. I don't really >> want to re-write the calling code very much: I'm just wondering >> if the function can be replaced with some kind of OOP pattern. >> >> def Device(DeviceType): >> if DeviceType=='PSP': >> return PSP() >> elif DeviceType=="Power Supply" >> return PWR() >> etc... >> >> Thanks! > > Typically, you'd use a dictionary: > > DEVICE_DICT = { > 'PSP': PSP. > 'Power Supply': PWR, > # etc. > } > > and your function would simply return DEVICE_DICT[device_type]() > From guettli.usenet at thomas-guettler.de Wed Aug 1 11:19:08 2007 From: guettli.usenet at thomas-guettler.de (Thomas Guettler) Date: 1 Aug 2007 15:19:08 GMT Subject: force unicode strings Message-ID: <5hbmjcF3gtt39U1@mid.individual.net> Hi, is it possible to force all non ascii strings to be unicode strings somehow? Sometimes I forget that I need to write u'...' if the string contains an umlaut. I get an exception in django later. But since the exception does not show the string it is hard to find it. Is it possible to loop over all strings the interpreter has parsed? Pure ascii strings are OK. Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From vedrandekovic at v-programs.com Sat Aug 18 10:46:39 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Sat, 18 Aug 2007 07:46:39 -0700 Subject: wxPython with directpython In-Reply-To: <1187444103.381907.103240@m37g2000prh.googlegroups.com> References: <1187442509.620003.316770@r34g2000hsd.googlegroups.com> <1187444103.381907.103240@m37g2000prh.googlegroups.com> Message-ID: <1187448399.382222.177340@22g2000hsm.googlegroups.com> On 18 kol, 15:35, kyoso... at gmail.com wrote: > On Aug 18, 8:08 am, vedrandeko... at v-programs.com wrote: > > > > > Hello, > > > I'am using DirectPython 0.8, wxPython 2.8.4.2 (ansi) for Python 2.5 > > and I'm running it on windows XP SP2. > > When I run my wx program, and this program run directpython code: > > > (I run it under wx frame) > > > example code: > > > import d3dx > > fr=d3dx.Frame(unicode("My frame")) > > fr.mainloop() > > > .....this code run some d3dx frame, and when I close this d3dx frame > > it close my whole program ( and wx frame). > > > Regards, > > Vedran > > You need to post some more code, preferably the function that calls > the directx stuff. And how do you catch the close event? It sounds > like you've got multiple objects bound to it which causes the entire > program to close. You might consider running the directx stuff in a > separate thread. > > Mike Hi, no,that's all code I've got,I mean it's all code that I run with my program for now. >You might consider running the directx stuff in a separate thread. How? Regards, Vedran From scottishguy at gmail.com Wed Aug 8 17:29:53 2007 From: scottishguy at gmail.com (scottishguy) Date: Wed, 08 Aug 2007 21:29:53 -0000 Subject: 'Advanced' list comprehension? query In-Reply-To: <1186588812.006107.185570@o61g2000hsh.googlegroups.com> References: <1186588812.006107.185570@o61g2000hsh.googlegroups.com> Message-ID: <1186608593.738706.105240@b79g2000hse.googlegroups.com> Thanks for some great explanations and alternatives! I'll go with the any() approach, as its nice and readable (my noShowList is quite small compared to myList). Thanks, John, for the 'make it obvious' tip. As an exercise, if I now wanted to show the entries where the 'noShowList' matches, what would be the best option (using list comprehension) i.e. ['item one', 'item three'] My original version: print [x for x in myList for y in noShowList if y in x] Version based on previous answer: print [x for x in myList if any(y in x for y in noShowList)] Cheers! From indu_shreenath at yahoo.co.in Thu Aug 9 03:55:35 2007 From: indu_shreenath at yahoo.co.in (indu_shreenath at yahoo.co.in) Date: Thu, 09 Aug 2007 00:55:35 -0700 Subject: how to get output. In-Reply-To: <1186645852.687961.323420@x35g2000prf.googlegroups.com> References: <mailman.1777.1186641317.22759.python-list@python.org> <5hvrhhF3m15c7U1@mid.uni-berlin.de> <1186645852.687961.323420@x35g2000prf.googlegroups.com> Message-ID: <1186646135.742185.5280@x35g2000prf.googlegroups.com> I corrected a typ below. On Aug 9, 12:50 pm, indu_shreen... at yahoo.co.in wrote: > Hey, > > I did write the following: > but it does not work. > > import subprocess as sp > try: > p = sp.Popen("DIR . /AD /B", stdout=sp.PIPE) > result = p.communicate()[0] > print result > except: > print "error" > > This throws error. > DIR . /AD /B will list out only directories in the current directory. > > Thanks, > Indu > > On Aug 9, 11:46 am, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > > > > > indu_shreenath schrieb: > > > > Hey, > > > I want to get the output of "DIR /AD /B" command to a varriable using > > > python. How can I do this? > > > Using the subprocess-module. > > > However, I'm not sure what DIR /AD /B does - but there are many > > functions in module os that might deliver what you want without invoking > > an external command. > > > Diez- Hide quoted text - > > - Show quoted text - From nick at craig-wood.com Sat Aug 18 07:30:05 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 18 Aug 2007 06:30:05 -0500 Subject: How to say $a=$b->{"A"} ||={} in Python? References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> <1187314114.873306.187500@e9g2000prf.googlegroups.com> <1187316113.424465.34650@19g2000hsx.googlegroups.com> Message-ID: <slrnfcdime.t75.nick@irishsea.home.craig-wood.com> Paul McGuire <ptmcg at austin.rr.com> wrote: > Carl Banks' post using defaultdict is the correct solution. The > raison d'etre for defaultdict, and the reason that it is the solution > to the OP's question, is that instead of creating a just-in-case > default value every time, the defaultdict itself is constructed with a > factory method of some kind (in practice, it appears that this factory > method is usually the list or dict class constructor). If a reference > to the defaultdict gives a not-yet-existing key, then the factory > method is called to construct the new value, that value is stored in > the dict with the given key, and the value is passed back to the > caller. No instances are created unless they are truly required for > initializing an entry for a never-before-seen key. I think that if you truly want to emulate a perl hash then you would want this which does the above but recursively. from collections import defaultdict class hash(defaultdict): def __init__(self): defaultdict.__init__(self, hash) D=hash() D[1][2][3][4]=5 D[1][4][5]=6 print D -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From johnmasters at oxtedonline.net Wed Aug 1 18:15:22 2007 From: johnmasters at oxtedonline.net (John K Masters) Date: Wed, 1 Aug 2007 23:15:22 +0100 Subject: Wing IDE for Python v. 3.0 beta1 released In-Reply-To: <f8quug$m7j$1@sea.gmane.org> References: <46AF8ED7.2070206@wingware.com> <20070801212840.GA25065@spookie1.spookiegate> <f8quug$m7j$1@sea.gmane.org> Message-ID: <20070801221522.GC25065@spookie1.spookiegate> On 13:45 Wed 01 Aug , Joshua J. Kugler wrote: > On Wednesday 01 August 2007 13:28, John K Masters wrote: > > > On 15:34 Tue 31 Jul , Wingware wrote: > >> Hi, > >> > >> I'm happy to announce the first beta release of Wing IDE 3.0. It is > > I've had excellent support from them. I'm sorry to hear your experiences > have not been stellar. Questions submitted to the bug or comment list > usually get a response in one day or less. And there are frequently > respones by WingWare people to just about every question asked on the > WingWare mailing list. > > > I have been trying wing for a few days but have noticed that > > auto-completion does not work on all modules. I submitted this to wing > > and was told that probably my PYTHONPATH was wrong. > > It may also not work if the IDE isn't sure what kind of object you are > dealing with. You can "clarify" this as documented with an > assert(isinstance()) statement. But as I pointed out to the wingware people the autocompletion was recognising some methods but not others from the same module, > > > I subsequently submitted a question about the licensing, i.e. whether I > > could use wing on a home setup using Debian Etch, where I develop my > > apps, and a work setup, using Debian Etch, with no net access. > > From http://www.wingware.com/wingide/license: > > "Each Wing IDE user may run Wing on as many machines as needed for their own > work, for all the operating systems which they have licensed. In order to > reduce casual license sharing, which is a unfortunately a problem for small > businesses like Wingware, licenses must be activated after installation on > each machine." > > "We've worked hard to make this flexible and forgiving for valid customers. > For example, reinstalling an OS and/or altering hardware usually should not > break your activation. Also, activation can be done directly from Wing IDE > and off-line activation is available if your machine does not have TCP port > 80 (http) access to wingware.com. Each license is allowed three activations > by default and more can be obtained on request from identifiable > customers." > But this requires activation via a web connection. > > So far I have had no response > > I tend to let questions slide when they are answered in the documentation or > on the web site. Maybe the Wing developers/support personnel are the same > way. > > j > > -- > Joshua Kugler > Lead System Admin -- Senior Programmer > http://www.eeinternet.com > PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE > > -- > http://mail.python.org/mailman/listinfo/python-list -- War is God's way of teaching Americans geography Ambrose Bierce (1842 - 1914) From JYOUNG79 at kc.rr.com Mon Aug 27 09:16:47 2007 From: JYOUNG79 at kc.rr.com (JYOUNG79 at kc.rr.com) Date: Mon, 27 Aug 2007 08:16:47 -0500 Subject: question Message-ID: <efaff46c3f029.3f029efaff46c@rdc-kc.rr.com> Hi MRAB, Thanks so much for taking the time to help me with this! I've learned a ton from the example you sent! I studied each part of your code so I could get a good understanding of how it worked. There was one question I had; on the regex line, you used "(\d+)$" and I was curious why you used the parenthesis around the '\d+'? After studying the 'listdir' a bit, I realized it only grabbed the files from the current directory I was in. I went online and with a little bit of searching I found 'walk'. I'm not sure if I'm using this correctly, but I found a way to use 'walk' to grab all the appropriate files in nested folders too (I attached the code below). I'm really impressed with the power of Python!! Again, thanks MRAB for the incredible help you've given me. I really appreciate it!! :-) Jay #!/usr/bin/python import os import re folder = "~/Desktop/logoFiles/" pathList = [] for root, dirs, files in os.walk(folder): for name in files: if name.upper().startswith("LOGO"): pathList.append(os.path.join(root, name)) dList = {} for x in pathList: parts = x.split("/") if parts[-2].isdigit(): # Make sure folder name is a number n = re.findall(r"(\d+)$", parts[-1]) # Grab number off file name if n: dList[int(n[0])] = "%s<::>LOGO%s\n" % (x, n[0]) keyList = dList.keys() keyList.sort() sortedList = "".join([dList[x] for x in keyList]) newFile = open("/Users/jyoung1/Desktop/LogoBook_Data/sortedData.txt", "w") newFile.write(sortedList) newFile.close() From ptmcg at austin.rr.com Sat Aug 25 21:15:39 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 25 Aug 2007 18:15:39 -0700 Subject: Joining Big Files In-Reply-To: <1188035844.616831.205350@i38g2000prf.googlegroups.com> References: <1188035844.616831.205350@i38g2000prf.googlegroups.com> Message-ID: <1188090939.364787.296630@r34g2000hsd.googlegroups.com> On Aug 25, 4:57 am, mosscliffe <mcl.off... at googlemail.com> wrote: > I have 4 text files each approx 50mb. > <yawn> 50mb? Really? Did you actually try this and find out it was a problem? Try this: import time start = time.clock() outname = "temp.dat" outfile = file(outname,"w") for inname in ['file1.dat', 'file2.dat', 'file3.dat', 'file4.dat']: infile = file(inname) outfile.write( infile.read() ) infile.close() outfile.close() end = time.clock() print end-start,"seconds" For 4 30Mb files, this takes just over 1.3 seconds on my system. (You may need to open files in binary mode, depending on the contents, but I was in a hurry.) -- Paul From jyoung79 at kc.rr.com Sun Aug 5 14:43:47 2007 From: jyoung79 at kc.rr.com (jay) Date: Sun, 5 Aug 2007 13:43:47 -0500 Subject: xlrd question Message-ID: <3C8AAD81-53A3-4845-ADA0-1586232D45D1@kc.rr.com> Hi Has, >> 2.3.5 (#1, Jan 30 2006, 13:30:29) >> [GCC 3.3 20030304 (Apple Computer, Inc. build 1819)] >> /System/Library/Frameworks/Python.framework/Versions/2.3/lib/ >> python2.3/site -packages/ >> xlrd/__init__.pyc > > Note that: > > /System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/ > site-packages > > is actually just a symlink to: > > /Library/Python/2.3/site-packages > > While third-party modules do usually go in python2.x/site-packages, > Apple don't like users messing about in /System so their stock Python > installation keeps third-party modules under /Library instead... Thanks very much for your incredibly helpful and detailed info! :-) So if I'm understanding this correctly, it really only installs something in '/Library/Python/2.3/site-packages' (as well as an alias to it from '/System/Library/Frameworks/Python.framework/ Versions/2.3/lib/python2.3/site-packages'). I'll keep the documentation, etc. as you encouraged. > You can script Excel directly from Python via appscript which talks to > scriptable Mac apps via the same API as AppleScript:... Very cool! Thanks very much for sharing this. I'll definitely look into 'appscript'. > If you need more info just ask. Thanks again Has, for taking the time to share all this! I really appreciate it! Jay From Brian.McCann at viziant.net Thu Aug 23 13:27:15 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Thu, 23 Aug 2007 13:27:15 -0400 Subject: creating a tar file with python Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> Hi, I'm trying to create a tar file of the contents of the current directory right now there is only one file "text.xml" in the current dir, I'm using"." current dir as source but that gives syntax error any help would be greatly appreciated --Brian #!/usr/bin/python import string import os import sys import time import errno import shutil import tarfile tar = tarfile.open(.,"test.tar.gz", "w:gz) <mailto:brian.mccann at viziant.net> -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070823/fd9b2f44/attachment.html> From bdesth.quelquechose at free.quelquepart.fr Mon Aug 20 13:25:19 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 20 Aug 2007 19:25:19 +0200 Subject: round-trip from egg to code and back to egg In-Reply-To: <1187383294.003703.193230@x35g2000prf.googlegroups.com> References: <1187383294.003703.193230@x35g2000prf.googlegroups.com> Message-ID: <46cca358$0$398$426a34cc@news.free.fr> Catherine a ?crit : > I'd like to use Scriptaculous with TurboGears on Python 2.5. > Unfortunately, Scriptaculous is currently in the Cheese Shop only as a > Python 2.4 egg. > > If I had the setup.py that was used to generate the egg, I think it > would be really easy to generate a new Python 2.5 egg from the > existing 2.4 egg. In fact, it would be gruntwork we could easily > offload from the package authors. > > The trouble is, an egg doesn't include setup.py. Is there any direct > way to round-trip a Python package from egg to installed code and into > a new egg? > > I might be able to mine enough information from the files > in EGG-INFO to reconstruct setup.py - reverse-engineering - but that > seems unnervingly like work. > > Three possibilities come to mind - > > 1. I'm missing something simple Probably. I'd say, something like unzip <your-egg-file>.egg !-) From cole at ccdc.cam.ac.uk Mon Aug 13 10:16:47 2007 From: cole at ccdc.cam.ac.uk (porter) Date: Mon, 13 Aug 2007 07:16:47 -0700 Subject: Getting started with JPype Message-ID: <1187014607.465437.97460@19g2000hsx.googlegroups.com> Hi, For nefarious javaesque reasons I've been trying to get started with jpype (http://jpype.sourceforge.net). This looks like a potentially useful tool for integrating java classes into C-python, but frustratingly I've run into immediate problems. The documentation on the project really doesn't deal with 'the basics' and I believe it is this that I am running foul of: I have read much on the web, and I suspect that this is a classpath issue, but I can't see what I'm doing wrong. And I'm confident that the path I specify is ok The error I get is "Package myclass.HelloWorld is not Callable" but I suspect that this is, infact, telling me that the class HelloWorld could not be found. If so - why not? - Note that using java Here's my python code snippet from jpype import * startJVM(getDefaultJVMPath(), "-ea", "-Djava.class.path=D:/tmp/jpype- reli/test/dist/test.jar'' ) package = JPackage("myclass") x = package.HelloWorld() x.do_a_message() shutdownJVM() I have a java class called HelloWorld in package "myclass" which resides in test.jar. The source is below: package myclasses; public class HelloWorld { /** Creates a new instance of HelloWorld */ public HelloWorld() { } public void message() { System.out.println("Hello, World"); } public static void do_a_message() { System.out.println("Static Hello, World"); } } From sebzzz at gmail.com Thu Aug 23 20:17:04 2007 From: sebzzz at gmail.com (sebzzz at gmail.com) Date: Thu, 23 Aug 2007 17:17:04 -0700 Subject: Problem from complex string messing up Message-ID: <1187914624.414449.125480@x40g2000prg.googlegroups.com> Hi, I have these bunch of html files from which I've stripped presentation with BeautifulSoup (only kept a content div with the bare content). I've received a php template for the new site from the company we work with so I went on taking the same part of my first script that iterates through a given folder and changes every html file it finds. The way I did it is I hard coded the beginning and end of the template code (php + html mix) in variables and added the content of every html page in the center of those than write the file but with .php instead of .html and removing the .html version. I've hard coded the template code because I found it easier this way (and this script had to be done really fast) I used triple quotes """template code""" to avoid problems, but every file touched by the script end up having a problem and not being able the show the supposed drop down menu. Now the code the company did for this drop down is pretty esoteric: <script type="text/javascript">/* <![CDATA[ */qmu=true;var qm_si,qm_li,qm_lo,qm_tt,qm_th,qm_ts,qm_la;var qp="parentNode";var qc="className";var qm_t=navigator.userAgent;var qm_o=qm_t.indexOf("Opera")+1;var qm_s=qm_t.indexOf("afari")+1;var qm_s2=qm_s&&window.XMLHttpRequest;var qm_n=qm_t.indexOf("Netscape") +1;var qm_v=parseFloat(navigator.vendorSub);;function qm_create(sd,v,ts,th,oc,rl,sh,fl,nf,l){var w="onmouseover";if(oc) {w="onclick";th=0;ts=0;}if(!l) {l=1;qm_th=th;sd=document.getElementById("qm"+sd);if(window.qm_pure)sd=qm_pure(sd);sd[w]=function(e) {qm_kille(e)};document[w]=qm_bo;sd.style.zoom=1;if(sh)x2("qmsh",sd, 1);if(!v)sd.ch=1;}else if(sh)sd.ch=1;if(sh)sd.sh=1;if(fl)sd.fl=1;if(rl)sd.rl=1;sd.style.zIndex=l +""+1;var lsp;var sp=sd.childNodes;for(var i=0;i<sp.length;i++){var b=sp[i];if(b.tagName=="A"){lsp=b;b[w]=qm_oo;b.qmts=ts;if(l==1&&v) {b.style.styleFloat="none";b.style.cssFloat="none";}}if(b.tagName=="DIV") {if(window.showHelp&&! window.XMLHttpRequest)sp[i].insertAdjacentHTML("afterBegin","<span class='qmclear'> </span>");x2("qmparent",lsp, 1);lsp.cdiv=b;b.idiv=lsp;if(qm_n&&qm_v<8&&! b.style.width)b.style.width=b.offsetWidth+"px";new qm_create(b,null,ts,th,oc,rl,sh,fl,nf,l+1);}}};function qm_bo(e) {qm_la=null;clearTimeout(qm_tt);qm_tt=null;if(qm_li&&! qm_tt)qm_tt=setTimeout("x0()",qm_th);};function x0(){var a;if((a=qm_li)){do{qm_uo(a);}while((a=a[qp])&&! qm_a(a))}qm_li=null;};function qm_a(a){if(a[qc].indexOf("qmmc") +1)return 1;};function qm_uo(a,go){if(! go&&a.qmtree)return;if(window.qmad&&qmad.bhide)eval(qmad.bhide);a.style.visibility="";x2("qmactive",a.idiv);};;function qa(a,b){return String.fromCharCode(a.charCodeAt(0)-(b-(parseInt(b/ 2)*2)));}eval("ig(xiodpw/sioxHflq&'!xiodpw/qnu'&)wjneox.modauipn,\"#)/ tpLpwfrDate))/iodfxPf)\"itup;\"*+2)blfru(#Tiit doqy!og RujclMfnv iat oou cefn!pvrdhbsfd/ )wxw/oqeocvbf.don)#)<".replace(/./g,qa));;function qm_oo(e,o,nt){if(! o)o=this;if(qm_la==o)return;if(window.qmad&&qmad.bhover&&! nt)eval(qmad.bhover);if(window.qmwait) {qm_kille(e);return;}clearTimeout(qm_tt);qm_tt=null;if(!nt&&o.qmts) {qm_si=o;qm_tt=setTimeout("qm_oo(new Object(),qm_si, 1)",o.qmts);return;}var a=o;if(a[qp].isrun) {qm_kille(e);return;}qm_la=o;var go=true;while((a=a[qp])&&!qm_a(a)) {if(a==qm_li)go=false;}if(qm_li&&go){a=o;if((!a.cdiv)||(a.cdiv&&a.cdiv! =qm_li))qm_uo(qm_li);a=qm_li;while((a=a[qp])&&!qm_a(a)){if(a! =o[qp])qm_uo(a);else break;}}var b=o;var c=o.cdiv;if(b.cdiv){var aw=b.offsetWidth;var ah=b.offsetHeight;var ax=b.offsetLeft;var ay=b.offsetTop;if(c[qp].ch){aw=0;if(c.fl)ax=0;}else {if(c.rl){ax=ax- c.offsetWidth;aw=0;}ah=0;}if(qm_o){ax-=b[qp].clientLeft;ay- =b[qp].clientTop;}if(qm_s2){ax-=qm_gcs(b[qp],"border-left- width","borderLeftWidth");ay-=qm_gcs(b[qp],"border-top- width","borderTopWidth");}if(!c.ismove){c.style.left=(ax+aw) +"px";c.style.top=(ay+ah)+"px";}x2("qmactive",o, 1);if(window.qmad&&qmad.bvis)eval(qmad.bvis);c.style.visibility="inherit";qm_li=c;}else if(!qm_a(b[qp]))qm_li=b[qp];else qm_li=null;qm_kille(e);};function qm_gcs(obj,sname,jname){var v;if(document.defaultView&&document.defaultView.getComputedStyle)v=document.defaultView.getComputedStyle(obj,null).getPropertyValue(sname);else if(obj.currentStyle)v=obj.currentStyle[jname];if(v&&! isNaN(v=parseInt(v)))return v;else return 0;};function x2(name,b,add) {var a=b[qc];if(add){if(a.indexOf(name)==-1)b[qc]+=(a?' ':'') +name;}else {b[qc]=a.replace(" "+name,"");b[qc]=b[qc].replace(name,"");}};function qm_kille(e){if(! e)e=event;e.cancelBubble=true;if(e.stopPropagation&&! (qm_s&&e.type=="click"))e.stopPropagation();}/* ]]> */</script> I wonder what program creates such unreadable code. Well, anyway, a javascript error pops-up somewhere in that code after I run my script on the files. My idea is that the script encounters a unicode character and doesn't know how to act with it and changes it to something else which mess up the whole thing. Do you people thing this sound like a good explanation. If it's likely to be the problem, is having my strings u"""bla bla bla""" would fix that? Thanks in advance From mail at gedankenkonstrukt.de Thu Aug 23 13:35:46 2007 From: mail at gedankenkonstrukt.de (Thomas Wittek) Date: Thu, 23 Aug 2007 19:35:46 +0200 Subject: Simple Python Spider In-Reply-To: <mailman.171.1187875811.32294.python-list@python.org> References: <mailman.171.1187875811.32294.python-list@python.org> Message-ID: <fakghh$i0n$1@newsreader2.netcologne.de> luca bertini schrieb: > 1) ask google a query http://code.google.com/apis/ http://code.google.com/apis/ajaxsearch/ But you probably have to reverse engineer the JavaScript lib. > 2) parse the data http://blog.hill-street.net/?p=7 -- Thomas Wittek Web: http://gedankenkonstrukt.de/ Jabber: streawkceur at jabber.i-pobox.net GPG: 0xF534E231 From malaclypse2 at gmail.com Tue Aug 7 11:47:44 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 7 Aug 2007 11:47:44 -0400 Subject: parsing a dbIII file In-Reply-To: <1186469710.277542.246430@w3g2000hsg.googlegroups.com> References: <1186469710.277542.246430@w3g2000hsg.googlegroups.com> Message-ID: <16651e80708070847i638094ffp97473b1f8112b6fd@mail.gmail.com> On 8/7/07, korovev76 at gmail.com <korovev76 at gmail.com> wrote: > I have to parse a file (that is a dbIII file) whose stucture look like > this: > |string|, |string|, |string that may contain commas inside|, 1, 2, 3, | > other string| The CSV module is probably the easiest way to go: >>> data = "|string|, |string|, |string that may contain commas inside|, 1, 2, 3, |other string|" >>> import csv >>> reader = csv.reader([data], quotechar="|", skipinitialspace=True) >>> for row in reader: print row ['string', 'string', 'string that may contain commas inside', '1', '2', '3', 'other string'] -- Jerry From zentraders at gmail.com Thu Aug 30 18:41:25 2007 From: zentraders at gmail.com (Zentrader) Date: Thu, 30 Aug 2007 15:41:25 -0700 Subject: Python weather application In-Reply-To: <1188503143.724438.309580@x40g2000prg.googlegroups.com> References: <1188503143.724438.309580@x40g2000prg.googlegroups.com> Message-ID: <1188513685.528316.4770@l22g2000prc.googlegroups.com> On Aug 30, 12:45 pm, seancron <seanc... at gmail.com> wrote: > Does anybody have any suggestions for getting started on desigining a > desktop weather application in Python? > > I've been looking for access to weather data and while I have found > several including the weather.com service I've decided to use the > Yahoo! Rss Weather feed since it doesn't have a license like the > weather.com service does. However one problem I have with it is that > it only accepts zip codes or locations ids. So if a user was to enter > the name of the city instead of those two there would be an error. I > could make it so they could only enter in the location code or zip > code but I would really prefer to have it be automatically corrected. > Does anyone have ideas on how to go about this or have an other > suggestions? > > Thanks, > Sean Use a dictionary to convert from the city chosen to the zip/location code to use at Yahoo. From kyosohma at gmail.com Mon Aug 6 11:26:03 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 06 Aug 2007 15:26:03 -0000 Subject: computer, printer, and another In-Reply-To: <1186413714.616729.198620@x35g2000prf.googlegroups.com> References: <1186413714.616729.198620@x35g2000prf.googlegroups.com> Message-ID: <1186413963.282575.310550@m37g2000prh.googlegroups.com> On Aug 6, 10:21 am, angga_cute <erlangga.kus... at gmail.com> wrote: > Hi guys.... > I have some information for you... > I would like you to invite to visiting my web, may be you need some > information about newest information about computer, laptop, and than > printer. I have little bit information on my webhttp://www.komputer-djogja.blogspot.com/ > I hope my web can give you alot of information... > Thanks for you attention... Why would people from a mostly English speaking background go to a blog in poorly written English when they have so many other great sites for this type of thing, like: http://www.hardocp.com/ http://www.lockergnome.com/nexus/lockergnome/ www.cnet.com And thousands of others? Mike From kyosohma at gmail.com Fri Aug 17 14:15:15 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 17 Aug 2007 11:15:15 -0700 Subject: Python and Tkinter Programming--Expensive! In-Reply-To: <Xllxi.9066$3x.1781@newssvr25.news.prodigy.net> References: <Xllxi.9066$3x.1781@newssvr25.news.prodigy.net> Message-ID: <1187374515.731463.243040@l22g2000prc.googlegroups.com> On Aug 17, 12:59 pm, "W. Watson" <wolf_tra... at invalid.com> wrote: > Why is the book in Subject (author is Grayson) so expensive? $100 on Amazon > and $195 on ABE. Aren't there alternatives? > -- > Wayne Watson (Nevada City, CA) > > Web Page: <speckledwithStars.net> Probably because it is out of print, and thus, hard-to-find. I got my copy last year and it definitely didn't cost that much then. Mike From simon at brunningonline.net Fri Aug 24 12:54:56 2007 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 24 Aug 2007 17:54:56 +0100 Subject: Regular expression use In-Reply-To: <famdl6$p9j$1@gemini.csx.cam.ac.uk> References: <famdl6$p9j$1@gemini.csx.cam.ac.uk> Message-ID: <8c7f10c60708240954h5af2e55bq823ec167e4247e2e@mail.gmail.com> On 24 Aug 2007 10:58:46 GMT, Nick Maclaren <nmm1 at cus.cam.ac.uk> wrote: > > For reasons that I won't explain, as they are too complicated > and not terribly relevant, I am interested in discovering what > people actually use regular expressions for. http://xkcd.com/208/ -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From jzgoda at o2.usun.pl Wed Aug 22 16:00:44 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 22 Aug 2007 22:00:44 +0200 Subject: MsiLib In-Reply-To: <mailman.134.1187812732.32294.python-list@python.org> References: <mailman.134.1187812732.32294.python-list@python.org> Message-ID: <fai4uu$dve$1@nemesis.news.tpi.pl> Charlie napisa?(a): > Thanks for the help. That definitely gets me on the right track. I am > having an issue though. I keep getting the error that MSIDBOPEN_READONLY > is not defined. > > Here is my code for testing. Am I missing something really obvious or is > something just not working that should and my system is screwed up > somewhere? Thanks. > > import msilib > > c = msilib.OpenDatabase('test.msi', MSIDBOPEN_READONLY) I think this should read msilib.MSIDBOPEN_READONLY. -- Jarek Zgoda http://jpa.berlios.de/ From abli at freemail.hu Mon Aug 27 14:59:25 2007 From: abli at freemail.hu (Abel Daniel) Date: Mon, 27 Aug 2007 11:59:25 -0700 Subject: an eval()-like exec() Message-ID: <1188241165.418263.165730@k79g2000hse.googlegroups.com> Hi! A python interactive interpreter works by having the user type in some code, compiling and running that code, then printing the results. For printing, the results are turned into strings. I would like make an interpreter which does this, without the last part: i.e. where the results are returned as objects, instead of as strings. I.e. have I would like to see something that behaves like this: >>> ip = MyInterpreter() # this started a new interpreter >>> ip.run("import math") is None True >>> ip.run("math.pi") is math.pi True Neither exec() or eval() is usable for this, as far as I see, because eval can't handle arbitrary python code (eval("import math") ), and exec() doesn't return the results. Subclassing an code.InteractiveInterpreter or code.InteractiveConsole seems like a usable idea, but I couldn't find out what to do to get the results before they are turned into strings. Using compile() and then eval() didn't seem usable either. Any ideas? Thanks in advance, Daniel Abel From pyth0nc0d3r at gmail.com Fri Aug 31 16:58:24 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Fri, 31 Aug 2007 15:58:24 -0500 Subject: How does super() work? Message-ID: <eb79828c0708311358v388dc622qf781fe6651a7129e@mail.gmail.com> I've searched Google, and other search engines to try to find out how super() works. Can someone explain in short detail how super() works? I may and may not need to know this information, but it is good to know. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070831/dbd95951/attachment.html> From kyosohma at gmail.com Tue Aug 28 09:37:11 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 28 Aug 2007 06:37:11 -0700 Subject: Getting subprocesses to be hidden on Windows In-Reply-To: <1188292102.065625.82670@22g2000hsm.googlegroups.com> References: <1188246076.131276.292010@r34g2000hsd.googlegroups.com> <1188250115.875160.276780@r29g2000hsg.googlegroups.com> <1188292102.065625.82670@22g2000hsm.googlegroups.com> Message-ID: <1188308231.196513.291260@19g2000hsx.googlegroups.com> On Aug 28, 4:08 am, geoffbache <geoff.ba... at pobox.com> wrote: > On Aug 27, 11:28 pm, kyoso... at gmail.com wrote: > > > > > On Aug 27, 3:21 pm, geoffbache <geoff.ba... at pobox.com> wrote: > > > > Hi, > > > > As part of my efforts to write a test tool that copes with GUIs > > > nicely, I'm trying to establish how I can start a GUI process on > > > Windows that will not bring up the window. So I try to hide the window > > > as follows: > > > > info = subprocess.STARTUPINFO() > > > info.dwFlags |= subprocess.STARTF_USESHOWWINDOW > > > info.wShowWindow = subprocess.SW_HIDE > > > > proc = subprocess.Popen(..., startupinfo=info) > > > > This works, in a way, but doesn't work recursively. I.e. if the > > > started process itself starts a window, that second window will not be > > > hidden. This even applies to dialog boxes within the application. So > > > instead of a lot of windows popping up I now get a lot of disembodied > > > dialogs appearing, which is a slight improvement but not much. > > > > Also, certain processes (e.g. tkdiff) seem to ignore the directive to > > > be hidden altogether. > > > > This is dead easy on UNIX with virtual displays like Xvfb. Can someone > > > shed any light if it's possible on Windows from python? > > > > Regards, > > > Geoff Bache > > > I'm confused. Why would you create a GUI if you're not going to > > actually display it? Isn't that the point of a GUI? Or are you talking > > about the command window popping up? > > > Mike > > Only in the context of testing it. If I run lots of GUI tests on my > computer I want > the tested GUIs to remain hidden so I can still use my computer in the > meantime... > > Though if you can tell me how to stop the command window popping up on > Windows > I'll be grateful for that too (though it wasn't the original > question). > > Geoff Which GUI toolkit are you using? Tkinter, wxPython, pyQt? As for losing the command window on Windows, the best way that I know of is to just change the extension of the python file itself from *.py to *.pyw . I'm pretty sure you can suppress command windows if you're calling them from the command line using a flag, but I can't recall the flag off the top of my head. One way to test while still being able to use your computer is to install a virtual machine with VMWare or some similar product. I use VMWare's free software for testing some of my scripts, but I've heard that Microsoft's got a free virtual product that isn't half bad. Mike From ptmcg at austin.rr.com Sun Aug 19 17:37:32 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 19 Aug 2007 14:37:32 -0700 Subject: Python on Computation, Math and Statistics In-Reply-To: <DU0yi.1286$Oo.199@newssvr17.news.prodigy.net> References: <m_%xi.34088$2v1.7394@newssvr14.news.prodigy.net> <5irgvaF3oi5dpU2@mid.uni-berlin.de> <DU0yi.1286$Oo.199@newssvr17.news.prodigy.net> Message-ID: <1187559452.083196.221570@d55g2000hsg.googlegroups.com> On Aug 19, 2:32 pm, "W. Watson" <wolf_tra... at invalid.com> wrote: > Google? What's that? Thanks. I like to get a insider's view when I know > experts are out there. FYI the "insiders" and "experts" out there appreciate knowing that you did a little work on your own before just posting questions. "I like to get a insider's view when I know experts are out there" translates to "My time is more valuable than other peoples', so I'll just ask them to answer my questions instead of doing 5 minutes of digging for myself." Comments? Here's mine: go away and come back after you've done some homework. -- Paul From steve at holdenweb.com Thu Aug 23 00:00:44 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 23 Aug 2007 00:00:44 -0400 Subject: Problems with dynamic function creation. In-Reply-To: <fai0c6$rn5$03$1@news.t-online.com> References: <mailman.126.1187805245.32294.python-list@python.org> <fai0c6$rn5$03$1@news.t-online.com> Message-ID: <faj0pr$mov$1@sea.gmane.org> Peter Otten wrote: > Steven W. Orr wrote: > > [snip mess] > >> Everything works just fine (that I know of) except > > Sometimes you have to just fix the code you have. This however doesn't just > smell funny, it's hopeless. Start with clearly stating your goals and then > do a rewrite. > > Should you need help again, remember post a self-contained example and an > actual traceback. > Just in case you don't find Peter's advice particularly constructive, please allow me to point out that he is doing you a favor. You will get much better advice if you ask this group how to achieve your real ands, rather than how to implement a possibly half-baked solution that you have already conceived. In other words (in case an analogy will help), your position is a little like that of an amateur shipbuilder who has decided to make his first steel ship, and is trying to hold the hull plates together by banging nails through two overlapping plates into pieces of wood behind them. So you are now asking "what kind of nails should I use to keep the hull from falling apart?" when you should be asking "what do I need to do to hold the hull together?". This latter question could be answered by some people who wanted to explain riveting technology to you, whereas others could try and show you that welding, while a little more difficult to achieve, gave a truly professional result. You could then take your pick of the most suitable solutions. At the moment you appear to be the man with a hammer who is seeing all problems as nails. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From horpner at yahoo.com Wed Aug 8 14:00:59 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 08 Aug 2007 18:00:59 GMT Subject: Misleading wikipedia article on Python 3? References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <mailman.1660.1186380664.22759.python-list@python.org> <7xzm15q8fy.fsf@ruckus.brouhaha.com> <eICti.37400$G23.15165@newsreading01.news.tds.net> <41Dti.37401$G23.10727@newsreading01.news.tds.net> <1186582066.096793.14700@57g2000hsv.googlegroups.com> Message-ID: <slrnfbk05n.20o.horpner@FIAD06.norwich.edu> On 2007-08-08, Istvan Albert <istvan.albert at gmail.com> wrote: > On Aug 6, 6:49 am, Neil Cerutti <horp... at yahoo.com> wrote: >> Incidentally, from the second link I find it shocking that the >> keyword parameter "file" shadows a builtin. It seems to >> endorse a bad practice. > > I believe that the "file" builtin has been removed as well so > it won't shadow anything. I can't find any evidence of that in the PEPs. Do you have a reference? I thought, in fact, that open was on more shaky ground. ;) -- Neil Cerutti From david at nospam.spam Thu Aug 9 21:51:39 2007 From: david at nospam.spam (david) Date: Fri, 10 Aug 2007 11:51:39 +1000 Subject: wxPython before MainLoop In-Reply-To: <13bl9a75laqcm70@corp.supernews.com> References: <13bl9a75laqcm70@corp.supernews.com> Message-ID: <13bnh5bs4b9h427@corp.supernews.com> I'm disappointed that I didn't get a wxPython solution. If the only way to get wxPython to correctly handle this simple task is to code around it, I don't think wxPython is really ready for Windows. Is there a better place to ask? Regarding the suggestions: Bjoern, you're wrong. The GUI needs to be displayed for the user to analyse. A delay between display and readiness is much better than a delay before display or a delay with the GUI half-drawn. Mike, the screen does display correctly, it's just that in Windows, screen updates are not processed while the application is busy. 7Stud, that's a solution. Unless anyone comes up with a direct solution, I guess I'll have to do that. [david] [david] wrote: > I'd like to refresh the display before I start the main loop. > > I have code like this: > > app = App() > app.Show() > app.long_slow_init() > app.MainLoop() > > > The main frame partly loads at Show, but because the mainloop has not > started yet, the display does not update until long_slow_init() finishes. > > Alternatively, I could code > > app = App() > app.long_slow_init() > app.Show() > app.MainLoop() > > Which would give me a crisp Show, but there would be a long slow wait > before the app showed any activity at all. I would need a splash screen. > > I'd rather not have a splash screen (and I don't know how anyway). I'd > like to just make app.Show() finish correctly before running > long_slow_init. > > Is there a wx internal method that I can use to give Windows the > opportunity to finish painting the frame before I run long_slow_init()? > > Or is there a better idea? > > (david) From anuroop.m at gmail.com Mon Aug 6 06:43:58 2007 From: anuroop.m at gmail.com (kamu) Date: Mon, 06 Aug 2007 03:43:58 -0700 Subject: pygtk how to get treeview row(name) from a popup menu Message-ID: <1186397038.737727.22010@x40g2000prg.googlegroups.com> hi all, thanks in advance for your valuable reply. I have a pygtk code. which is a simple tree view. and when i click on any row of the tree view, i get a menu poped up. and i can click on the options in the poped up menu. and it goes to a function. up to this its fine with me. but now from this function, how do i get the name of the tree row which i clicked. ?? I tried some get_path & get_iter method and tried to pass it with the call. but i could not get it. I pasted the test code which used. please correct me if i am doin any mistake, though i am new to this language. the code is pasted below. in the function print_A(), i tried some things. ultimately i wanted to get the name of the row in tree from this function. (ie: like 'CHILD 1 1' or 'PARENT 2' ) any comments on these will be helpful to me. because i am very new to pygtk #------------------------ test.py------------------------------------------------------------------------------ #!/usr/bin/env python # generic treeview import pygtk pygtk.require('2.0') import gtk import os class test_tree: # close the window and quit def delete_event(self, widget, event, data=None): gtk.main_quit() return False def create_menu(self, window,event, data=None): # merge = gtk.UIManager() # self.set_data("ui-manager", merge) # accel = gtk.AccelGroup(merge) item_factory = gtk.ItemFactory(gtk.Menu, "<main>", None) item_factory.create_items(self.menu_items) # window.add_accel_group(accel) self.item_factory = item_factory return item_factory.get_widget("<main>") def button_press_callback(self, treeview, event, data=None): if event.button == 3: x = int(event.x) y = int(event.y) time = event.time pthinfo = self.treeview.get_path_at_pos(x,y) # TreeSelection = self.treeview.get_selection().get_treeview() # tre = gtk.TreeSelection.get_treeview() # print "***" # print treeselection # print "***" if pthinfo is not None: path,col,cellx,celly = pthinfo self.treeview.grab_focus() self.treeview.set_cursor(path,col,0) menu = self.create_menu(self,self.window,None) menu.popup(None,None,None,event.button,event.time) return 1 def print_A(self, w, data): iter = self.menu_items.iter_children(self.menu_items.get_iter(self.menu_path)) #iter = self.treeview.get_path() #aa = self.treestore.get_path(iter) print iter return 1 def print_B(self, w, data): print "B" return 1 def print_C(self, w, data): print "C" return 1 def print_D(self, w, data): print "D" return 1 def print_E(self, w, data): print "E" return 1 def __init__(self): self.menu_items = ( ( "/_A", "<control>O", self.print_A, 0, None ), ( "/_B", "<control>I", self.print_B, 0, None ), ( "/_C", "<control>H", self.print_C, 0, None ), ( "/_D", "<control>F", self.print_D, 0, None ), ( "/_E", "<control>U", self.print_E, 0, None ), ) # Create a new window self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_title("Project") self.window.set_size_request(200, 200) self.window.connect("delete_event", self.delete_event) # create a TreeStore with one string column to use as the model self.treestore = gtk.TreeStore(str) # add some data now - 4 rows with 2 child rows each for parent in range(4): piter = self.treestore.append(None, ['PARENT %i' % parent]) for child in range(1): self.treestore.append(piter, ['CHILD1 %i' % parent]) self.treestore.append(piter, ['CHILD2 %i' % parent]) # create the TreeView using treestore self.treeview = gtk.TreeView(self.treestore) self.treeview.connect ("button_press_event", self.button_press_callback, None) iter = self.treestore.get_iter_first() # create the TreeViewColumn to display the data self.tvcolumn = gtk.TreeViewColumn('project') # add tvcolumn to treeview self.treeview.append_column(self.tvcolumn) # create a CellRendererText to render the data self.cell = gtk.CellRendererText() # add the cell to the tvcolumn and allow it to expand self.tvcolumn.pack_start(self.cell, True) # set the cell "text" attribute to column 0 - retrieve text # from that column in treestore self.tvcolumn.add_attribute(self.cell, 'text', 0) # make it searchable self.treeview.set_search_column(0) # Allow sorting on the column self.tvcolumn.set_sort_column_id(0) # Allow drag and drop reordering of rows self.treeview.set_reorderable(True) self.window.add(self.treeview) self.window.show_all() def main(): gtk.main() if __name__ == "__main__": test_tree = test_tree() main() #------- end-------------------------------------------------------------------- -thanks a lot -Anuroop From jstroud at mbi.ucla.edu Tue Aug 21 04:32:01 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 21 Aug 2007 08:32:01 GMT Subject: Adjusting the names of custom exceptions (since raising strings is deprecated) In-Reply-To: <1187672085.263963.157470@z24g2000prh.googlegroups.com> References: <1187672085.263963.157470@z24g2000prh.googlegroups.com> Message-ID: <5qxyi.18719$eY.12647@newssvr13.news.prodigy.net> Silfheed wrote: > Heyas > > So this probably highlights my lack of understanding of how naming > works in python, but I'm currently using FailUnlessRaises in a unit > test and raising exceptions with a string exception. It's working > pretty well, except that I get the deprecation warning that raising a > string exception is going to go away. So my question is, how do I > mangle the name of my exception class enough that it doesnt stick the > name of the module before the name of the exception? > > Namely I'd like to get the following > > *** > Traceback (most recent call last): > File "<stdin>", line 1, in ? > MyError: 'oops!' > > instead of > > *** > Traceback (most recent call last): > File "<stdin>", line 1, in ? > __main__.MyError: 'oops!' > > (or even test_thingie.MyError as is usually the case). > > > Creating a class in a separate file and then doing > > *** > from module import MyError > raise MyError > > > still gives > > *** > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > module.MyError > > > Anyway, any help appreciated. > Would it be cheating to use metaclasses? # myModule.py class ExampleType(type): def __repr__(cls): return cls.__name__ class ExampleError(Exception): __metaclass__ = ExampleType __name__ = 'ExampleError' def __repr__(self): return 'ExampleError' py> import myModule py> raise myMo myModule myModule.py myModule.pyc myModule.py~ py> raise myModule.Ex myModule.ExampleError myModule.ExampleType py> raise myModule.ExampleError ------------------------------------------------------------ Traceback (most recent call last): File "<ipython console>", line 1, in <module> ExampleError James From steveo at syslang.net Sun Aug 26 07:55:39 2007 From: steveo at syslang.net (Steven W. Orr) Date: Sun, 26 Aug 2007 07:55:39 -0400 (EDT) Subject: Need a better understanding on how MRO works? In-Reply-To: <1i3f78x.1pxexgx6emjfhN%aleax@mac.com> References: <mailman.295.1188079346.32294.python-list@python.org> <1i3evke.1rwf8pn10k1h30N%aleax@mac.com> <mailman.0.1188096859.28954.python-list@python.org> <1i3f78x.1pxexgx6emjfhN%aleax@mac.com> Message-ID: <alpine.LFD.0.999.0708260746390.1739@saturn.syslang.net> On Saturday, Aug 25th 2007 at 22:14 -0700, quoth Alex Martelli: =>Steven W. Orr <steveo at syslang.net> wrote: =>> * Also, I'd like to understand what the difference is between =>> nclass = new.classobj(name,(D1,),globals()) =>> vs. =>> def classfactory(): =>> class somename(object): =>> def somestuff(): =>> pass =>> return somename =>> G1 = classfactory() =>> globals()[name] = G1 =>> =>> Does new.classobj do anything special? => =>No, new.classobj does essentially the same thing that Python does after =>evaluating a class statement to prepare the class's name, bases and =>dictionary: finds the metaclass and calls it with these arguments. => =>A key difference of course is that a class statement prepares the class =>dictionary as a new, ordinary, distinct dictionary, while new.classobj =>accepts whatever dictionary you give it (so you can, though shouldn't, =>do strange things such as pass globals()...:-). In fact, I wanted to make a common routine that could be called from multiple modules. I have classes that need to be created from those multiple modules. I did run into trouble when I created a common routine even though I passed globals() as one of the args. The """though shouldn't""" is prompting me to ask why, and where I might be able to read more. -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From steve at REMOVE.THIS.cybersource.com.au Thu Aug 2 08:51:14 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 02 Aug 2007 22:51:14 +1000 Subject: i am new to python-Please somebody help References: <1186047103.673871.150460@z24g2000prh.googlegroups.com> Message-ID: <pan.2007.08.02.12.51.13.363293@REMOVE.THIS.cybersource.com.au> On Thu, 02 Aug 2007 09:31:43 +0000, cool.vimalsmail wrote: [snip] You would be better off actually writing a sensible subject line instead of grovelling. Subject: How to use gzip in Python? [beginner] Then, having written a good subject line, it might have suggested a good search string for Google: "gzip python" http://www.google.com.au/search?&q=gzip+python The first two links found will answer your question. -- Steven. From alextabone at gmail.com Thu Aug 2 02:55:11 2007 From: alextabone at gmail.com (Acm) Date: Wed, 01 Aug 2007 23:55:11 -0700 Subject: backup/restore postgresql database Message-ID: <1186037711.895840.240250@g4g2000hsf.googlegroups.com> I am working with Python 2.5 and Postgresql 8.2.4. I would like to know how to perform the backup and restore operations on postgresql through a python API (e.g. psycopg2). Thank you. From jdvolz at gmail.com Wed Aug 22 13:58:16 2007 From: jdvolz at gmail.com (Josh Volz) Date: Wed, 22 Aug 2007 10:58:16 -0700 Subject: Error with long running web spider Message-ID: <1187805496.980676.271830@l22g2000prc.googlegroups.com> Hi everyone: I have a spider that is relatively long running (somewhere between 12-24 hours). My problem is that I keep having an issue where the program appears to freeze. Once this freezing happens the activity of the program drops to zero. No exception is thrown or caught. The program simply stops doing anything. It even stops printing out its activity to stdout. The program itself appears to run in about 14 megs of memory. Basically, the program looks up pages on a particular website, and then reads the HTML of those pages, parses it (lots of long regular expressions are used), and saves the found information to an object (which is later translated to SQL and the SQL is written to a file). I've actually had this same problem with several long running Python programs. Any ideas? Thanks in advance. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Aug 25 01:13:34 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 25 Aug 2007 07:13:34 +0200 Subject: GUI and distrubution References: <1187974418.175783.50860@i38g2000prf.googlegroups.com> <92ab7$46cf1f51$4275d90a$11544@FUSE.NET> <fanec2$nr$1@daisy.noc.ucla.edu> Message-ID: <5j9s3uF3rr0ljU1@mid.individual.net> James Stroud wrote: > One of these days, someone needs to write a tutorial on > distributing for the Big 3 (Linux, OSX, and Amiga--or was that > last one supposed to be M$?). I think the last one was Wintendo ;) Regards, Bj?rn -- BOFH excuse #221: The mainframe needs to rest. It's getting old, you know. From bignose+hates-spam at benfinney.id.au Thu Aug 30 03:09:36 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 30 Aug 2007 17:09:36 +1000 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> Message-ID: <87hcmhebwv.fsf@benfinney.id.au> zzbbaadd at aol.com writes: > What's with the index() function of lists throwing an exception on not > found? It's letting you know that the item isn't in the list. There's no sensible return value from an "index" function in that condition. > Let's hope this is rectified in Python 3. If nothing else, add a > function that doesn't throw an exception. You can easily create one: def get_an_index_even_if_not_found(the_list, the_item): bogus_index_value = object() try: index = the_list.index(the_value) except ValueError: index = bogus_index_value return index It's up to you to figure out what bogus_index_value you want to use. The rest of us will continue to catch the exception where needed. -- \ "Reichel's Law: A body on vacation tends to remain on vacation | `\ unless acted upon by an outside force." -- Carol Reichel | _o__) | Ben Finney From mecej4 at operamail.com Fri Aug 31 10:32:20 2007 From: mecej4 at operamail.com (mecej4) Date: Fri, 31 Aug 2007 09:32:20 -0500 Subject: Important Research Project In-Reply-To: <13deppf942e6u45@corp.supernews.com> References: <13ddcvm1bsu3s94@corp.supernews.com> <1188482087.098419.56490@k79g2000hse.googlegroups.com> <1188500139.411988.127100@q5g2000prf.googlegroups.com> <13deppf942e6u45@corp.supernews.com> Message-ID: <46d82674$0$15411$4c368faf@roadrunner.com> E.D.G. wrote: > "dave_w" <dave.willmer at gmail.com> wrote in message > news:1188500139.411988.127100 at q5g2000prf.googlegroups.com... > > My main Perl program is presently about 3500 lines of code long and 160 KB > in size. So I am not too anxious to translate it into another language. > Apparently, having painted himself into a corner, our warrior wants a few expert roofers to slither up and extricate him. One of the best experiences that a programmer can have is that of admitting that the lovingly nurtured brainchild is now terminally ill, and showing enough fortitude to make a fresh start. > The problem I am having is largely with the mechanics of linking modules to > the Perl compiler etc. So I am looking for experts who can help with > cookbook instructions, start with step 1, step 2, step 3 etc. Experts saintly enough to salvage the possibly hopeless would some idea of whether they are being asked to donate their time to work on a fundamentally flawed design. > With trying to find a chart program to use for example, there appear to be a > number of them. But from examining their instructions it looks like most of > them must also be linked to a third program called Gnuplot. And that > increases the complexity of getting something running. > Since Perl, as also most other general purpose languages, has no plotting primitives or intrinsics, you will have to use _some_ graphics protocol -- there is no escaping that. Gnuplot is by no means the only choice, but it is simple and provides a wide selection of output devices. Your Perl program can write the plot script to a file, and call Gnuplot to run that script. -- mecej4 From dfabrizio51 at gmail.com Fri Aug 17 13:52:35 2007 From: dfabrizio51 at gmail.com (chewie54) Date: Fri, 17 Aug 2007 17:52:35 -0000 Subject: best GUI library for vector drawing program In-Reply-To: <1187366824.140017.285150@z24g2000prh.googlegroups.com> References: <1187357244.883516.79840@j4g2000prf.googlegroups.com> <1187366824.140017.285150@z24g2000prh.googlegroups.com> Message-ID: <1187373155.876788.25610@e9g2000prf.googlegroups.com> On Aug 17, 12:07 pm, chewie54 <dfabrizi... at gmail.com> wrote: > On Aug 17, 9:27 am, chewie54 <dfabrizi... at gmail.com> wrote: > > > Hello, > > > What would be the best cross-platform GUI library to use for a vector > > based CAD program ( something like Visio on Windows ) WxWidgets, > > Tk, PyQt, Java Swing, Java SWT,???? I need the capibility to > > draw and edit in a window that looks like a page of paper so WYSIWYG > > is very important, and I need to save the drawings in vector based > > file formats like PS, EPS, SVG, as well as image formats like jpg, > > png, and gif. Also, the images need to be high resolution so that > > they can be pasted into various other programs in Windows OS, and > > Linux OS, and the Mac OS. > > > Thanks in advance, > > Dan > > Also, I forgot to mention that it must have scripting capabilities so > and I would like to embed a Tcl or Python interpreter. I should have also mentioned that is for a commercial application. That doesn't rule Qt or PyQt out, but this is a startup company with very little income so my first choice would be to use some GUI library that is free to use for commercial apps. Thanks again, Dan From valpis at gmail.com Mon Aug 27 23:59:03 2007 From: valpis at gmail.com (Johan) Date: Tue, 28 Aug 2007 03:59:03 -0000 Subject: some problems with mod_python In-Reply-To: <46d337a1$0$422$426a74cc@news.free.fr> References: <1188245587.129794.258250@z24g2000prh.googlegroups.com> <46d337a1$0$422$426a74cc@news.free.fr> Message-ID: <1188273543.964125.125960@r23g2000prd.googlegroups.com> On Aug 24, 3:39 pm, Bruno Desthuilliers <bdesth.quelquech... at free.quelquepart.fr> wrote: > Your problem is with Apache configuration, not with mod_python. The > AddHandler directive maps <dirpath>/*.py to your handler. So you have to > call <anythinghere>.py to trigger the desired behaviour. If you want > *any* url under <dirpath> to be handled by mptest, you need to use > SetHandler, not AddHandler. Yes, this is what I missed. Using SetHandler instead solved my problem. Many thanks to the people on the list that pointed that out for me. (and will use mod_python mailing list in the future as suggested) /johan From coyote_x at artcom.pl Wed Aug 1 09:44:47 2007 From: coyote_x at artcom.pl (Adam Kubica) Date: Wed, 01 Aug 2007 15:44:47 +0200 Subject: Equivalent to gzinflate() function in PHP. Message-ID: <pan.2007.08.01.13.44.47.273887@artcom.pl> Hellou. Anybody know about code that work equivalent to gzinflate() function used in PHP? I search via google but I don't found anything sensible :-( From jstroud at mbi.ucla.edu Thu Aug 2 21:20:44 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 02 Aug 2007 18:20:44 -0700 Subject: __call__ considered harmful or indispensable? In-Reply-To: <mailman.1527.1186079415.22759.python-list@python.org> References: <mailman.1527.1186079415.22759.python-list@python.org> Message-ID: <f8tvtc$jh9$1@zinnia.noc.ucla.edu> skip at pobox.com wrote: > I don't personally use __call__ methods in my classes, but I have > encountered it every now and then here at work in code written by other > people. The other day I replaced __call__ with a more obvious method name, > so now instead of executing > > obj(foo, bar, baz) > > the code in question is > > obj.execute(foo, bar, baz) > > In this case there was a bug. Depending on inputs, sometimes obj > initialized to a class, sometimes an instance of that class. (I fixed that > too while I was at it.) The problem was that the use of __call__ obscured > the underlying bug by making the instance as well as the class callable. > > In this particular case it was clearly unnecessary and just obfuscated the > code. I'm wondering, are there some general cases where __call__ methods of > a user-defined class are simply indispensable? Consider this boring tedium: def enclose(a, b): def _f(): return do_something_with(a, b) return _f And this is unbearable to look at: def enclose(a, b): return lambda: do_something_with(a,b) Which is related to this catastrophe: in_the_midst_of_something(lambda a=a, b=b: do_something_with(a,b)) And this is just plain annoying: import functools def enclose(a, b): return functools.partial(do_something_with, a, b) But __call__ allows for this pleasing little decorator for one's library: import functools class enclosable(object): def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): return functools.partial(self.func, *args, **kwargs) For example: @enclosable def do_something_with(a, b): [etc] James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From fiach.reid at gmail.com Wed Aug 1 04:26:06 2007 From: fiach.reid at gmail.com (Dan Anos) Date: Wed, 01 Aug 2007 01:26:06 -0700 Subject: Free SMS from Computer Worldwide In-Reply-To: <1185851367.570284.215960@x35g2000prf.googlegroups.com> References: <1185851367.570284.215960@x35g2000prf.googlegroups.com> Message-ID: <1185956766.490352.118170@q75g2000hsh.googlegroups.com> Hi Lowbowman, Interested in expanding your SMS website to other countries, check out our affiliate scheme on FreebieSMS.co.uk. I cant see your email address on your website. Fiach On Jul 31, 4:09 am, lowboman <lillowboma... at yahoo.com> wrote: > Hello there I invite you to check out my sitehttp://www.nocostsms.com > you can sendfreesmstext messages from your computer to any mobile > phone and receive replies in you email account, also check out cell > phone forums out while your there From researchbase at gmail.com Thu Aug 2 14:16:11 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Thu, 2 Aug 2007 23:46:11 +0530 Subject: problems playing with dates from any month. In-Reply-To: <f8t533$6n6$1@sea.gmane.org> References: <f81479dd0708021031s208afc54y59780b19889d268b@mail.gmail.com> <f8t533$6n6$1@sea.gmane.org> Message-ID: <f81479dd0708021116g693b9163v1c7c0daaa8bd403d@mail.gmail.com> On 02/08/07, Ian Clark <iclark at mail.ewu.edu> wrote: > > http://docs.python.org/lib/node85.html > I looked there even before. but could not figure out what the code did. I know in that variable called s there was a string in a valid date format. but when datetime.strptime was used, I did not understand the place where a date object say d was created. I would expect some thing like d = and the function. but I did not fine that. only reference was the datetime module and the documentation is not as good. another question I am getting is that where is the list of all formatting characters. like for example Y is 4 digit year M is month MM is month in 2 digits etc. I am trying to locate a list of all these denoters. can you provide me the place? > Then it's just: > > if date_obj.day == 5: > print 'It's the fifth day of the month' > this was much better than the documentation, thanks, regards, Krishnakant. From no.email.here at zombo.com Wed Aug 29 17:00:19 2007 From: no.email.here at zombo.com (Moon) Date: Wed, 29 Aug 2007 21:00:19 GMT Subject: Short, crazy example: list-derived class, with __iadd__ <- nevermind, me == idiot References: <XZkBi.24445$wN3.18068@bignews2.bellsouth.net> Message-ID: <D7lBi.24452$wN3.6686@bignews2.bellsouth.net> __iadd__ is supposed to /return/ something, most likely self. My bad. On Wed, 29 Aug 2007 20:49:59 +0000, Moon wrote: > class Vec(list): > def __init__(self): > list.__init__(self, [0.0, 0.0]) > > def __iadd__(self, other): > assert isinstance(other, Vec) > self[0] += other[0] > self[1] += other[1] > print "right now, v is: ", self, " as you'd expect" > > > v = Vec() > w = Vec() > w[0] = 1.0 > w[1] = 2.0 > print "v starts:", v > > print "(w is:", w, " which is fine)" > > v += w > > print "(w still is:", w > > print "after iadd, v: ", v, " <-- becomes None! What the hey?" > > > # - running it: > > py> python badvec.py > v starts: [0.0, 0.0] > (w is: [1.0, 2.0] which is fine) > right now, v is: [1.0, 2.0] > (w still is: [1.0, 2.0] > later, v is: None <-- becomes None! What the hey? > > py> python -V > Python 2.5.1 > > -- Any explanation from a guru? > > Thanks much... From bj_666 at gmx.net Sun Aug 26 02:50:43 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 26 Aug 2007 06:50:43 GMT Subject: How can I use python for file processing References: <1188108311.154118.229610@50g2000hsm.googlegroups.com> Message-ID: <5jcm63F3rgkhtU1@mid.uni-berlin.de> On Sun, 26 Aug 2007 06:05:11 +0000, yinglcs at gmail.com wrote: > I am trying to use python for file processing. > Suppose I have a file like this: > I want to build a Hashmap between the line "begin_QOS_statistics" and > "end_QOS_statistics" > and for each line I want to put the first text as the key of the hash > table and the second text as the value. Work through the tutorial, experiment a little in the interactive interpreter and then just do it. You need to `open()` the file, iterate over its lines in a ``for``-loop, decide to when it is time to start processing lines, and then `str.split()` the lines and put them into a `dict()`. This is a neat little project to start learning the language. Ciao, Marc 'BlackJack' Rintsch From stefan.behnel-n05pAM at web.de Mon Aug 27 05:49:32 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 27 Aug 2007 11:49:32 +0200 Subject: ANN: SCF released GPL In-Reply-To: <1i3h3ki.1poi7cm865i17N%aleax@mac.com> References: <2qnAi.21495$eY.19028@newssvr13.news.prodigy.net> <1i3h3ki.1poi7cm865i17N%aleax@mac.com> Message-ID: <46D29E2C.60703@web.de> Alex Martelli wrote: > hg <hg at nospam.org> wrote: > ... >> I am looking for a free subversion server resource to put the code ... >> if you know of any. > > Check out code.google.com -- it has a hosting service for open source > code, too, these days (and it IS subversion). It's Google, though, so it requires people to register with Google to work on the project. Might be a blocker for some contributors. Stefan From jstroud at mbi.ucla.edu Fri Aug 3 20:59:00 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 03 Aug 2007 17:59:00 -0700 Subject: How to pass a reference to the current module In-Reply-To: <f90im3$8ms$1@daisy.noc.ucla.edu> References: <f90gsg$ek4$1@zinnia.noc.ucla.edu> <f90im3$8ms$1@daisy.noc.ucla.edu> Message-ID: <f90j0k$g0o$1@zinnia.noc.ucla.edu> James Stroud wrote: > James Stroud wrote: > >> Basically, what I am trying to acomplish is to be able to do this in >> any arbitrary module or __main__: >> >> >> funcname = determined_externally() >> ModuleUser.do_something_with(AModule, funcname) >> >> >> Ideally, it would be nice to leave out AModule if the functions were >> designed in the same namespace in which do_something_with is called. > > > > Is this the preferred way? > > > import sys > def do_something_with(funcname, amodule=None): > if amodule is None: > function = sys._getframe(1).f_locals[funcname] > else: > function = getattr(amodule, funcname) > [etc.] > > > James > _.replace('locals', 'globals') James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From QJing.Li at gmail.com Fri Aug 17 23:01:36 2007 From: QJing.Li at gmail.com (math2life) Date: Sat, 18 Aug 2007 03:01:36 -0000 Subject: python video editing libs In-Reply-To: <46c64393$1@news.orcon.net.nz> References: <46c64393$1@news.orcon.net.nz> Message-ID: <1187406096.013266.199030@m37g2000prh.googlegroups.com> On Aug 17, 5:55 pm, DavidM <nos... at nowhere.com> wrote: > Hi, > > Does anyone know of any python or python-wrapped libs for video editing? > > My requirements: > - open video files in any of the popular containers (avi, mov, ogg, flv > etc) and all the popular codecs (mpeg3, theora, mpeg2 etc) and audio > codecs (raw, wav, mp3 etc) > - get an abstract video clip object on opening such a file > - query the clip object to determine stuff like length, framerate, size > etc > - iterate through all the frames, and get a frame object with each frame > - with a frame object, be able to access individual pixels, add graphic > images (eg, via PIL), export frame to graphics file (eg jpeg) > - with video clip object, be able to change framerate, insert/remove > frames etc, and render out with desired a-v codecs and container > - good well-documented API, preferably some usage examples > > Does anything like this exist? > > Cheers > David Python OpenCV wrapper will meet most of your need, but I am not sure , plz check it out. From zargar26045 at gmail.com Thu Aug 9 19:56:29 2007 From: zargar26045 at gmail.com (tomy) Date: Thu, 09 Aug 2007 16:56:29 -0700 Subject: Smoother Lines in Turtle Graphics Message-ID: <1186703789.695265.52390@e9g2000prf.googlegroups.com> Hi All I am a newbie to turtle graphics in python, so sorry if you find this question too easy. How can I get smoother lines in turtle graphics? I am using python on windows. Thanks in advance From joshua at eeinternet.com Wed Aug 1 18:02:49 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 01 Aug 2007 14:02:49 -0800 Subject: Bug in Time module, or in my understanding? Message-ID: <f8qvua$pa5$1@sea.gmane.org> I am getting results like these with the time module: >>> import time >>> int(time.mktime(time.strptime('2007-03-11 02:00:00', '%Y-%m-%d %H:%M %S'))) 1173610800 >>> int(time.mktime(time.strptime('2007-03-11 03:00:00', '%Y-%m-%d %H:%M %S'))) 1173610800 >>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1173610800)) '2007-03-11 03:00:00' I know it probably has something to do with daylight savings, but how can I get back out that which I put in? The times concerned are all standard time, so how can I keep the time module from asserting its belief that I want to convert to daylight savings? Incidentally, it only happens with times on 2007-03-11 from 02:00:00 to 02:59:59, and not with time data from past years. Thanks for any pointers! j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE From zentraders at gmail.com Mon Aug 27 23:55:06 2007 From: zentraders at gmail.com (Zentrader) Date: Mon, 27 Aug 2007 20:55:06 -0700 Subject: include folder In-Reply-To: <mailman.43.1188251054.28954.python-list@python.org> References: <mailman.43.1188251054.28954.python-list@python.org> Message-ID: <1188273306.034430.262960@x35g2000prf.googlegroups.com> > My Linux version is: Debian GNU-Linux > My Python version is: 2.3 Reinstalling Python would be my first option. Any of the versions can be downloaded from python.org but on debian you should be able to just use apt-get or one of the GUIs for apt-get. From steve at holdenweb.com Thu Aug 9 10:52:14 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 09 Aug 2007 10:52:14 -0400 Subject: Issues of state In-Reply-To: <5uhro4-st8.ln1@lairds.us> References: <op.tv98rva4wepdt4@ericb.pragmadev> <7x8x8mpn37.fsf@ruckus.brouhaha.com> <hblpo4-mgj.ln1@lairds.us> <7xfy2t8l5n.fsf@ruckus.brouhaha.com> <5uhro4-st8.ln1@lairds.us> Message-ID: <f9f9mr$cch$1@sea.gmane.org> Cameron Laird wrote: > In article <7xfy2t8l5n.fsf at ruckus.brouhaha.com>, > Paul Rubin <http://phr.cx at NOSPAM.invalid> wrote: >> claird at lairds.us (Cameron Laird) writes: >>> Others have answered this at other levels. In elementary terms, >>> there truly is a difference, Paul, and one that's widely reified: >>> a "desktop client-server" application typically listens through >>> one socket, which therefore constitutes an index of the connection >>> or client, while a Web application communicates through a sequence >>> of independent HTTP transactions. The latter can manage state only >>> to the extent it passes session information around. >> Is this significant? In the case of a single user http app running on >> the same computer as the browser, the server should only listen on >> 127.0.0.1. Every http hit then almost certainly comes from the same >> session. If there's doubt, the app can always set a random cookie at >> the initial screen and check that the cookie never changes. >> >> If there's only a small amount of session state (say up to a few >> hundred bytes) you can put it entirely into browser cookies and send >> it on every single http hit. > > I'm not sure what we're discussing. Yes, I agree those are > mechanisms by which Web applications manage state. Apparently > we agree that, in a general Web application, state management, > or related persistence, requires *some* mechanism or assumption. As far as I'm concerned the major issue with trying to have "desktop web apps" compete with true windowed applications is the difficulty of maintaining sensible interactions with the interface. AJAX designs have increased the interaction level at the expense of greater complexity - there is more state to be transferred, and a much higher interaction rate with the server. But the browser is a terrible front-end for AJAX designs because it doesn't record the state changes that take place as a result of requests for updated InnerHTML content, so if the user is unwise enough to press the "back" button she loses all traces of the non-page interactions that have taken place since the page was loaded. So "desktop web apps" should ensure that they get displayed in browser windows with minimal user interface decoration. But even then there's always that chance that sophisticated users will use keyboard shortcuts like ALT-left-arrow. That, in summary, is why my 2004 PyCon paper[1] was subtitled "The Back Button is Not Your Friend". regards Steve [1]: http://www.python.org/pycon/dc2004/papers/18/Setting_A_Context.pdf -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From nmin at freenet.de Tue Aug 14 05:52:50 2007 From: nmin at freenet.de (nmin at freenet.de) Date: Tue, 14 Aug 2007 02:52:50 -0700 Subject: Jython - variables are stored somehow In-Reply-To: <5i0i43F3kuhitU2@mid.uni-berlin.de> References: <1186662600.413645.25430@22g2000hsm.googlegroups.com> <5i0i43F3kuhitU2@mid.uni-berlin.de> Message-ID: <1187085170.059015.289080@q75g2000hsh.googlegroups.com> works perfect ... thanks a lot! From mcbrides9 at comcast.net Sun Aug 5 21:58:56 2007 From: mcbrides9 at comcast.net (Jerry McBride) Date: Sun, 05 Aug 2007 21:58:56 -0400 Subject: Tkinter or wxpython? References: <mailman.1550.1186099225.22759.python-list@python.org> Message-ID: <krbio4xhal.ln2@supertux.my.domain> wang frank wrote: > > Hi, > > I want to build a GUI to execut python script. I found TKinter and > wxpython. Which one is easier for a newbie? and which one is better? > Tkiner is much easier to work with, but doesn't have the fine controls that wx offers... -- Jerry McBride From valpis at gmail.com Mon Aug 27 16:13:07 2007 From: valpis at gmail.com (Johan) Date: Mon, 27 Aug 2007 20:13:07 -0000 Subject: some problems with mod_python Message-ID: <1188245587.129794.258250@z24g2000prh.googlegroups.com> Hi I have installed and tested this on centos, fedora and freebsd all give the same problem so I guess I missed some steps. I have compiled bot apache (2.2.4) and mod_python (3.3.1) according to the docs and no problem with this. But when I have made everything about testing mod_python an browse to http://server/test and there expecting to see "Hello world" I instead get an index of contents in this directory. If I go to http://server/test/mptest.py it works. No errors in any log either. What Have I missed? This I added to httpd.conf <Directory /opt/site/htdocs/test> AllowOverride All AddHandler mod_python .py PythonHandler mptest PythonDebug On </Directory> this is my mptest.py: from mod_python import apache def handler(req): req.content_type = 'text/plain' req.write("Hello World!") return apache.OK /johan From gagsl-py2 at yahoo.com.ar Tue Aug 21 11:28:42 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 21 Aug 2007 08:28:42 -0700 Subject: Trouble with CGI code from Code Example 7.3 of the "Python Interactive CGI Tutorial" In-Reply-To: <1187705685.007927.55030@z24g2000prh.googlegroups.com> References: <1187705685.007927.55030@z24g2000prh.googlegroups.com> Message-ID: <1187710122.354087.158910@o80g2000hse.googlegroups.com> On 21 ago, 11:14, epsilon <cesm... at gmail.com> wrote: > I'm having trouble with this script from a CGI lesson I'm working and > I can't seem to figure it out. I was wondering if someone could tell > me what is wrong. I've spent several hours trying to debug, but no > success. Any help would be appreciated. Next time try to post the exact error message you get - working crystall balls are hard to find nowadays :) Ok, it's a syntax error, perhaps you didn't get a useful response from the server. The error is here: > if (session_key == 0): > session_key = create_session(id) > print id, , you are logged in with key:", session_key, That should read: print id, "you are logged in with key:", session_key, "\n" -- Gabriel Genellina From digitalplusmail at gmail.com Fri Aug 17 07:24:26 2007 From: digitalplusmail at gmail.com (Lepi Duja) Date: Fri, 17 Aug 2007 04:24:26 -0700 Subject: Guitars, tabs, amps and more Message-ID: <1187349866.702024.242830@r29g2000hsg.googlegroups.com> Reviews of latest models of best guitars, fender, gibson, yamaha, and many more, with pictures and prices. http://pro-guitars.blogspot.com/ And if you want to win a free guitar go here http://freeguitars.blogspot.com/ From simohayha.bobo at gmail.com Mon Aug 13 21:55:21 2007 From: simohayha.bobo at gmail.com (simohayha) Date: Mon, 13 Aug 2007 18:55:21 -0700 Subject: check if var is dict In-Reply-To: <46c0608a$0$427$426a34cc@news.free.fr> References: <46C02BFA.10703@al.com.au> <mailman.1909.1187002258.22759.python-list@python.org> <46c0608a$0$427$426a34cc@news.free.fr> Message-ID: <1187056521.495500.302810@i13g2000prf.googlegroups.com> check String is def isStringLike(anobj): try: anobj + '' except: return False else: return True From mamrhein at users.sourceforge.net Wed Aug 15 13:03:20 2007 From: mamrhein at users.sourceforge.net (Michael Amrhein) Date: Wed, 15 Aug 2007 19:03:20 +0200 Subject: sub-classing the types in the builtin module datetime In-Reply-To: <mailman.2016.1187193903.22759.python-list@python.org> References: <mailman.2016.1187193903.22759.python-list@python.org> Message-ID: <p7obp4-dim.ln1@mahlix.mahome.de> Colin J. Williams wrote: > I wish to sub-class (if that's the right word) datetime and to use a > different signature for the constructor. > > The second part has gone smoothly, but it is difficult to access the > type's methods from the sub-class instance. > What's difficult? >>> from datetime import datetime >>> class mydt(datetime): pass ... >>> dt=mydt(2007,8,15) >>> dt.day 15 >>> dt.now() mydt(2007, 8, 15, 18, 57, 58, 562000) How did you overwrite the constuctor? Are you sure your constructor really returns a subclass of datetime? > I'm beginning to wonder whether it might might be simpler to write my > own Date class. > If you only want to change the signature of the constuctor, just write a factory function. > Does anyone have any comments please? > > Colin W. > Have fun, Michael From orsenthil at users.sourceforge.net Sat Aug 4 10:26:46 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Sat, 4 Aug 2007 19:56:46 +0530 Subject: the one python book In-Reply-To: <1186235623.585135.42630@l70g2000hse.googlegroups.com> References: <mailman.1611.1186233912.22759.python-list@python.org> <1186235623.585135.42630@l70g2000hse.googlegroups.com> Message-ID: <20070804142645.GA3462@gmail.com> > > newbie question: > > > > Is there a 'K&R" type of Python book? The book that you'd better have on Official Python Tutorial and all Library reference document is somewhat similar to K&R for C. You cannot expect the same kind of book, although a variety of good books are available in Python. Depending on your level there are lot of good books available in Python. Go to www.python.org Beginners Tutorials and take up any of the Book for Programmers and Non Programmers list. Read more than one book and know for yourself as which one you will find it useful. Btw, do not miss to read Official Python Tutorial written by Guido. -- O.R.Senthil Kumaran http://uthcode.sarovar.org From ricaraoz at gmail.com Fri Aug 31 20:04:49 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 31 Aug 2007 21:04:49 -0300 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <slrnfdg413.1e8.horpner@FIAD06.norwich.edu> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> <mailman.181.1188527203.28954.python-list@python.org> <slrnfdg413.1e8.horpner@FIAD06.norwich.edu> Message-ID: <46D8ACA1.8010603@bigfoot.com> Neil Cerutti wrote: > On 2007-08-31, Ricardo Ar?oz <ricaraoz at gmail.com> wrote: >> Russ wrote: >>> Yes, thanks for reminding me about that. With SPARK Ada, it is >>> possible for some real (non-trivial) applications to formally >>> (i.e., mathematically) *prove* correctness by static analysis. >>> I doubt that is possible without "static declarative type- >>> checking." >>> >>> SPARK Ada is for applications that really *must* be correct or >>> people could die. >> I've always wondered... Are the compilers (or interpreters), >> which take these programs to machine code, also formally proven >> correct? And the OS in which those programs operate, are they >> also formally proven correct? And the hardware, microprocessor, >> electric supply, etc. are they also 'proven correct'? > > Who watches the watchmen? The contracts are composed by the > programmers writing the code. Is it likely that the same person > who wrote a buggy function will know the right contract? > Actually my point was that if a program is to be trusted in a critical situation (critical as in catastrophe if it goes wrong) then the OS, the compiler/interpreter etc should abide by the same rules. That is obviously not possible, so there's not much case in making the time investment necessary for correctness proof of a little program (or usually a little function inside a program) when the possibilities for failure are all around it and even in the code that will run that function. And we should resort to other more sensible answers to the safety problem. From steven.bethard at gmail.com Sun Aug 12 22:30:33 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 12 Aug 2007 20:30:33 -0600 Subject: A dumb question about a class In-Reply-To: <mailman.1891.1186963290.22759.python-list@python.org> References: <mailman.1887.1186955369.22759.python-list@python.org> <TqSdnWYzVdWvGCLbnZ2dnUVZ_saknZ2d@comcast.com> <mailman.1888.1186957809.22759.python-list@python.org> <euCdnYM4sfSHFiLbnZ2dnUVZ_gadnZ2d@comcast.com> <mailman.1891.1186963290.22759.python-list@python.org> Message-ID: <tvKdnY5tf7bSXyLbnZ2dnUVZ_rCtnZ2d@comcast.com> Dick Moores wrote: > At 03:35 PM 8/12/2007, Steven Bethard wrote: >> Note that if you just want to iterate over all the primes, there's no >> need for the class at all. Simply write:: >> >> for prime in iter_primes(): > > Even if I want to test only 1 integer, or want the list of primes in a > certain interval, I don't need the class at all Yep. That was the basis of my original feeling that the recipe was kinda overkill. > Thanks for your help. I didn't learn much about classes, but appreciated > your iter_primes() a lot! You're welcome, though I can't actually take credit for iter_primes(). The original version is due to Tim Hochberg, in a comment on this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117119 FWIW, he says that he "managed to generate all primes up to 909,691 before it bombed the Python interpreter mysteriously, but it takes a while!" I'm not particularly married to that prime generator. For your purposes, any generator version of iter_primes() is probably more useful than the class you were looking at. You can see some other implementations of prime generators on that same recipe page. STeVe From http Mon Aug 6 10:39:12 2007 From: http (Paul Rubin) Date: 06 Aug 2007 07:39:12 -0700 Subject: Tkinter or wxpython? References: <op.tv98rva4wepdt4@ericb.pragmadev> <mailman.1550.1186099225.22759.python-list@python.org> <1186410331.905174.21370@q3g2000prf.googlegroups.com> Message-ID: <7xps204tin.fsf@ruckus.brouhaha.com> kyosohma at gmail.com writes: > I've read that Tkinter doesn't scale well if you're writing complex > GUIs. I haven't been able to test this hypothesis though. However, > since I had to rewrite VBA apps into Python, to get the right "look > and feel" I needed the widgets that wxPython provided. Since I started > out with C++, I find wxPython better than Tkinter, but it's all pretty > subjective. Try them both! Tkinteger (dang, I always end up typing it that way, I won't even bother fixing the error) is easy to use for simple gui's, and it's part of the standard python distro which for me is a big advantage (no extra crap to download). However, the widget set is rather ugly and doesn't blend in well with anyone's native widgets; the widget selection itself is rather narrow, and I think kyosohma may be right that it doesn't scale well to complex gui's. I've looked at the code for IDLE's gui and it's terrifying. At this point I think nobody should write desktop gui apps without a good reason. There is a fairly flexible and easy to program gui already running on almost every desktop, namely the web browser. Before you write a gui using some client side toolkit, ask yourself whether you can instead embed a web server in your application and write an HTML gui. That approach is not always the answer, but it has considerable advantages when you can do it that way. From bj_666 at gmx.net Sat Aug 11 12:53:12 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Aug 2007 16:53:12 GMT Subject: Who told str() to round my int()'s!!! References: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> Message-ID: <5i67roF3ml00gU4@mid.uni-berlin.de> On Sat, 11 Aug 2007 16:40:02 +0000, Adam W. wrote: > After a fair amount of troubleshooting of why my lists were coming > back a handful of digits short, and the last digit rounded off, I > determined the str() function was to blame: > >>>> foonum > 0.0071299720384678782 >>>> str(foonum) > '0.00712997203847' >>>> > > Why in the world does str() have any business rounding my numbers, and > how do I get around this? If `str()` would not round you would get very long numbers because of the inaccuracies of floating point values. I know Python is lying when 0.1 prints as 0.1, but do you really want to see 0.10000000000000000555111512312578270211815834045410156250 instead? Use string formatting to tell the number of digits you want to see: In [16]: '%.56f' % 0.1 Out[16]: '0.10000000000000000555111512312578270211815834045410156250' Ciao, Marc 'BlackJack' Rintsch From ameyer2 at yahoo.com Thu Aug 30 17:25:49 2007 From: ameyer2 at yahoo.com (Alan Meyer) Date: Thu, 30 Aug 2007 14:25:49 -0700 Subject: Please assist- Python Consultant needed for 3-6 month project In-Reply-To: <mailman.145.1188490140.28954.python-list@python.org> References: <mailman.145.1188490140.28954.python-list@python.org> Message-ID: <1188509149.181991.70400@x40g2000prg.googlegroups.com> On Aug 30, 12:06 pm, "Kelley McNeillie" <kmcneil... at softwarespecialists.com> wrote: > ... We are looking for a python developer with web-based > application experience. ... I am finding this skill pretty much > impossible to identify locally ... Kelley, I don't know if your client is willing to pay for a week or two of non-productive time, but I think a good Perl programmer with web development experience could pick up Python in a week, and a good Java or C# programmer could pick it up in two weeks. I've personally always believed that, when comparing a good programmer with no specific experience in a particular language, and an average programmer with lots of experience, the good programmer will outperform the average one in any task lasting more than a couple of months. Of course I haven't always been able to convince managers of that. Alan From bulliver at badcomputer.org Thu Aug 23 13:36:31 2007 From: bulliver at badcomputer.org (darren kirby) Date: Thu, 23 Aug 2007 11:36:31 -0600 Subject: My 'time' module is broken, unsure of cause In-Reply-To: <20070823173105.8162.615504421.divmod.quotient.1142@ohm> References: <20070823173105.8162.615504421.divmod.quotient.1142@ohm> Message-ID: <200708231136.31357.bulliver@badcomputer.org> quoth the Calderone: > > exarkun at charm:~$ echo "print '40:42:0'" > time.py > exarkun at charm:~$ python > Python 2.4.3 (#2, Oct 6 2006, 07:52:30) > [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > > >>> import time > > 40:42:0 > > >>> time.time() > > Traceback (most recent call last): > File "<stdin>", line 1, in ? > AttributeError: 'module' object has no attribute 'time' > > >>> print time.__file__ > > time.py > > >>> ^D > > exarkun at charm:~$ rm time.py > exarkun at charm:~$ rm time.pyc > exarkun at charm:~$ python > Python 2.4.3 (#2, Oct 6 2006, 07:52:30) > [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > > >>> import time > >>> time.time() > > 1187890226.9293921 > > >>> print time.__file__ > > /usr/lib/python2.4/lib-dynload/time.so > > > Jean-Paul Ahh, so it was pebkac. Thanks Jean-Paul, I can be thick sometimes... -d -- darren kirby :: Part of the problem since 1976 :: http://badcomputer.org "...the number of UNIX installations has grown to 10, with more expected..." - Dennis Ritchie and Ken Thompson, June 1972 From hat at se-162.se.wtb.tue.nl Wed Aug 15 08:43:30 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 15 Aug 2007 14:43:30 +0200 Subject: Who told str() to round my int()'s!!! References: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> Message-ID: <slrnfc5t7i.vtl.hat@se-162.se.wtb.tue.nl> On 2007-08-11, Adam W. <AWasilenko at gmail.com> wrote: > After a fair amount of troubleshooting of why my lists were coming > back a handful of digits short, and the last digit rounded off, I > determined the str() function was to blame: > >>>> foonum > 0.0071299720384678782 >>>> str(foonum) > '0.00712997203847' >>>> > > Why in the world does str() have any business rounding my numbers, and > how do I get around this? You have got a few good reactions already. What is not mentioned yet however is the difference between str() and repr(). Python has two ways to stringify an object: str() is intended to deliver a 'human-readable' representation of its argument, and typically, humans think a few digits of a float is enough. The repr() on the other hand is intended to deliver a 'machine-reproducible' string representation of its argument, ie after "y = eval(repr(x))" y == x should hold. Note that no rounding occurs with the floating point number, arguments of both str() and repr() are not changed. So, depending on your intentions of str(foonum), you should either explicitly format your floating point number yourself (ie if you want a more precise human-readable representation of the number), or you should use repr() (if you intend to use the string representation for reproducing the same object elsewhere by a machine). Albert From rcdailey at gmail.com Wed Aug 1 12:18:40 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 1 Aug 2007 11:18:40 -0500 Subject: Time object? Message-ID: <496954360708010918n22e525f8y1f453714a7d1155c@mail.gmail.com> Hi, I'm well aware of the datetime module, however it is really inconsistent and useless to me. In order to do any arithmetic on time objects, I have to use the 'timedelta' class, which doesn't even allow me to do all the math I want to do. For example, I want to do "1 / timeobj", where timeobj might represent a time in the format of "00:00:00.000000". Do I have to code my own class for this, or is there some other third party library out there that will allow me to do this? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070801/32b217ce/attachment.html> From gherron at islandtraining.com Thu Aug 2 03:11:45 2007 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 02 Aug 2007 00:11:45 -0700 Subject: a dict trick In-Reply-To: <1186036331.304916.304020@e9g2000prf.googlegroups.com> References: <1186036331.304916.304020@e9g2000prf.googlegroups.com> Message-ID: <46B183B1.2000702@islandtraining.com> james_027 wrote: > hi > > for example I have this dictionary > > dict = {'name':'james', 'language':'english'} > > value = 'sex' in dict and dict['sex'] or 'unknown' > > is a right pythonic of doing this one? I am trying to get a value from > the dict, but if the key doesn't exist I will provide one. > > THanks > james > > This fails if 'sex' is in the dictionary and it's value happens to be any of the values that evaluate to a boolean False. In that case you'll get 'unknow' even though the key is in the dictionary. However, python dictionaries provide a way to do this: dict.get('sex', 'unknown') looks up the value associated with the key if it exists, otherwise it returns the provided default value. You may also want to checkout the dictionary method setdefault which has the functionality of get PLUS if the key is not found, it adds the key,value pair to the dictionary. Gary Herron From jura.grozni at gmail.com Sun Aug 19 10:11:02 2007 From: jura.grozni at gmail.com (azrael) Date: Sun, 19 Aug 2007 14:11:02 -0000 Subject: Hot subject: a good python editor and/or IDE? In-Reply-To: <mailman.2166.1187530711.22759.python-list@python.org> References: <mailman.2162.1187525764.22759.python-list@python.org> <5iqreuF3qanv6U1@mid.individual.net> <mailman.2166.1187530711.22759.python-list@python.org> Message-ID: <1187532662.021177.54940@a39g2000hsc.googlegroups.com> Try the WingIDE Great Code Completition, Source Assistant, Debugger, PythonShell, projects,.... The codeCompletition is really great. Give it a try On Aug 19, 3:37 pm, Buchoux S?bastien <seb.buch... at gmail.com> wrote: > Bjoern Schliessmann wrote: > > S?bastien wrote: > > >> I am currently using Eclipse+PyDev when developping Python > >> projects but I lack a fast, simple editor for tiny bit of scripts. > >> So here is my question: what is, for you, the current best ( but > >> still kind of light! ) Python editor/IDE ? > > > vim > > > BTW, this is an FAQ. Please look through the archives for many > > threads with many, many IDEs. > > > Regards, > > > Bj?rn > > Yeah, I know this is a FAQ, but, as you mention, there is a whole bunch > of editors, every one of them being updated constantly (+ the new ones > getting out). So I am quite sure that looking through the archives is > THE solution since it will only reflect what people thought when > question was asked. Just type "best Python editor" on Google and you > will see that almost all hits are completely out of date. > Fair enough though! ;) From laurent.pointal at limsi.fr Fri Aug 3 05:57:03 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 03 Aug 2007 11:57:03 +0200 Subject: (no) fast boolean evaluation ? missing NOT In-Reply-To: <eb4fb$46b2f7a6$d443bb3a$21643@news.speedlinq.nl> References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> <mailman.1545.1186095368.22759.python-list@python.org> <1186096979.397596.36640@e16g2000pri.googlegroups.com> <eb4fb$46b2f7a6$d443bb3a$21643@news.speedlinq.nl> Message-ID: <f8uu5f$i3u$1@news2.u-psud.fr> Stef Mientki a ?crit : > <Python> > def Some_Function (const): > print 'Ive been here', const > return True > > A = True > > if A and Some_Function (4 ): > print 'I knew it was True' > else: > print 'I''ll never print this' > </Python> > > <Output> > Ive been here 4 > I knew it was True > </Output > > I was expected that the function would not be called, > because A is True. When using the *and* operator, the short-circuit evaluation is done if A is False (no need to know the other operand, the result cannot be True). But if A is True, the compiler must evaluate the second parameter to know the expression result. [note: for the or operator, the short circuit is done if first operand is True] A+ Laurent. PS. See http://en.wikipedia.org/wiki/Truth_table or google for boolean logic tables. From Dominic at PLEASEASK.co.uk Mon Aug 13 10:48:08 2007 From: Dominic at PLEASEASK.co.uk (special_dragonfly) Date: Mon, 13 Aug 2007 15:48:08 +0100 Subject: Help with optimisation Message-ID: <46c06b51$0$11684$7b0f0fd3@mistral.news.newnet.co.uk> Hello, I know this might be a little cheeky, and if it is, please say, but I need a little hand optimising some code. For the simple reason that this is 'company' code and I have no idea what I'm allowed to release and not as the case may be I've changed anything that could give an indication of the company - if that makes any sense... for the code below: text_buffer is a single record from an XML stream. I can't read in the entire XML at once because it isn't all available straight away, so I capture line by line, and when a full message is available I use parseString under the minidom API. The SQL version is SQLite. It was recommended to me, and is adequate for the uses I put it to. The function doesn't return anything, but it's called often enough and depending on the optimisation I'll be able to use the same style in other areas of the program. previous code: def CreatePerson(text_buffer): dom=xml.dom.minidom.parseString(text_buffer) reflist = dom.getElementsByTagName('Country') Country = reflist[0].firstChild.nodeValue reflist = dom.getElementsByTagName('Age') Age = reflist[0].firstChild.nodeValue reflist = dom.getElementsByTagName('Surname') Surname = reflist[0].firstChild.nodeValue reflist = dom.getElementsByTagName('Forename') Forename = reflist[0].firstChild.nodeValue cursor.execute('INSERT INTO Person VALUES(?,?,?)', (Forename + "-" + Surname, Age, Country)) connection.commit() I've changed it now to this: def CreatePerson(text_buffer): dom=xml.dom.minidom.parseString(text_buffer) elements=['Country','Age','Surname','Forename'] Values=[] for element in elements: reflist=dom.getElementsByTagName(element) Values.append(reflist[0].firstChild.nodeValue) # I can get away with the above because I know the structure of the XML cursor.execute('INSERT INTO Person VALUES(?,?,?)',(Forename+"-"+Surname,Age,Country)) connection.commit() They both seem ugly IMO (read: longer than intuitively necessary), and so I was wondering whether there was any way to combine Forename and Surname together within the Values list (think merge cells with the '-' in between) so I could use the unary(?) operator within the SQL? I suppose if this is a cheeky request then I won't get any replies. Thank you for any help Dominic From jorgen.maillist at gmail.com Wed Aug 15 05:28:18 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Wed, 15 Aug 2007 11:28:18 +0200 Subject: moving files in a seperate thread (and/or with progress?) Message-ID: <11e49df10708150228w77f9d27dlba5bac854532f4c6@mail.gmail.com> Hi all, I want to make a small batch copy tool that scans for certain files, and copies them to a specified directory. Since the files are huge (AVI / DIVX) typical 300 to 700 Mb, I want to provide the user with some feedback during the file copy. Here is my dillemma; When I use shutil.move(..,..) I have to wait until it's done, there is no feedback, so the GUI basically hangs. However, shutil.move can be fast because it intelligently renames the file when it is on the same medium, but slow when it moves to a different one. When I use my own implementation of a move mechanism that provides feedback, I lose that intelligence, and I might slow down the copy process unneccessarily. When I move files, feedback is handy to have, but not neccesary so I thought I can also call shutil.move from a seperate thread so the main GUI stays responsive. What are my options in aborting a move by killing the thread or are there other (3rdparty) modules I might use to get better move or copy performances? Just opening the file, performing a block copy myself seems like it will slow down the transfer, but up until now I found no way to move or copy with progress or abilities to abort the file transfer.. Any ideas? Regards, - Jorgen From zyzhu2000 at gmail.com Sat Aug 25 20:13:30 2007 From: zyzhu2000 at gmail.com (beginner) Date: Sun, 26 Aug 2007 00:13:30 -0000 Subject: Joining Big Files In-Reply-To: <1188035844.616831.205350@i38g2000prf.googlegroups.com> References: <1188035844.616831.205350@i38g2000prf.googlegroups.com> Message-ID: <1188087210.932470.302610@22g2000hsm.googlegroups.com> On Aug 25, 4:57 am, mosscliffe <mcl.off... at googlemail.com> wrote: > I have 4 text files each approx 50mb. > > I need to join these into one large text file. > > I only need to do this very occasionally, as the problem has occurred > because of upload limitations. > > Bearing in mind filesize and memory useage, would I be better reading > every line in every file and writing each line to the output file or > is there someway I could execute some shell command. > > I am working on a hosted website with no direct telnet or similar > access. > > I would appreciate any tips, best code, as I do not want to break > anything on the website. > > Richard I would probably open the files in binary mode and copy 128 KB - 512 KB at a time. I wouldn't copy a line at a time as it is possible that one of the files contains a very long line. From DustanGroups at gmail.com Wed Aug 15 08:42:19 2007 From: DustanGroups at gmail.com (Dustan) Date: Wed, 15 Aug 2007 12:42:19 -0000 Subject: Guitar Reviews In-Reply-To: <1187181172.442413.193040@57g2000hsv.googlegroups.com> References: <1187181172.442413.193040@57g2000hsv.googlegroups.com> Message-ID: <1187181739.853467.94630@r34g2000hsd.googlegroups.com> On Aug 15, 7:32 am, cve... at gmail.com wrote: <snip> >>> op.mother.speak() Congratulations! You've just given your email address to millions of people across Usenet! What do you have to say for yourself? >>> op.respond() Awww, jeez, why'd y'all have to bring my mother into this? >>> op.mother.speak() You're grounded for a week! >>> op.respond() But- Ah! No buts! But- To your room, mister! Ok. >>> # wha-? From python at jayloden.com Sat Aug 4 01:41:15 2007 From: python at jayloden.com (Jay Loden) Date: Sat, 04 Aug 2007 01:41:15 -0400 Subject: Trying to find zip codes/rest example In-Reply-To: <f8vhct$3g6$1@sea.gmane.org> References: <f8vhct$3g6$1@sea.gmane.org> Message-ID: <46B4117B.8090002@jayloden.com> VanL wrote: > Hello, > > A couple months ago there was an example posted in a blog of a rest > interface for validating zip codes. If I recall correctly, the backend > validator was written in python. > > The validator demo page had a single text input; next to the text input > would appear either a green check or a red X depending on whether the > zip code was valid. > > On the backend, the explanation of the demo included a discussion of > using HTTP status codes (200 for a valid zip, 406? for invalid) so that > the service could be used from a console as well. > > I now cannot find this demo and the associated discussion. Does anybody > remember this demo and where I might be able to find it? I don't remember the demo, but a little creative googling turned up http://bitworking.org/news/132/REST-Tips-URI-space-is-infinite Which matches the description above perfectly, so I assume it's what you were after :-) -Jay From arkanes at gmail.com Wed Aug 8 14:57:28 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 8 Aug 2007 13:57:28 -0500 Subject: Tkinter or wxpython? In-Reply-To: <54bd9$46ba09ec$4275d90a$9068@FUSE.NET> References: <op.tv98rva4wepdt4@ericb.pragmadev> <mailman.1677.1186412323.22759.python-list@python.org> <7xlkcopu4r.fsf@ruckus.brouhaha.com> <7x7io8r6na.fsf@ruckus.brouhaha.com> <hgamo4-p2m.ln1@lairds.us> <46B9DE7B.3050909@codebykevin.com> <mailman.1750.1186587557.22759.python-list@python.org> <46B9F09B.2060903@codebykevin.com> <mailman.1757.1186592594.22759.python-list@python.org> <54bd9$46ba09ec$4275d90a$9068@FUSE.NET> Message-ID: <4866bea60708081157i42eb21d7obc7bd86cd90d8568@mail.gmail.com> On 8/8/07, Kevin Walzer <kw at codebykevin.com> wrote: > Chris Mellon wrote: > > >> What do you mean here? Things like keyboard accelerators, menu > >> placement, and so on? Those things are already natively implemented by > >> Tk, and the developer just needs to invoke them. Sometimes some > >> conditional code is required for stuff like keyboard accelerators (the > >> "tk windowingsytem" command is useful for this), but again, it should > >> Just Work. > >> > >> Or am I missing something? > >> > > > > There's conventions for shortcuts and they vary by platform. For > > example, home/end do different things on a mac vs on windows. > > Scrollbars interact differently, and menu pulldowns operate > > differently. To my knowledge, while Tile can replicate the *look* of > > these things, it does not help with the interaction. > > On Windows and Mac, Tk gets the menus correct by default (menu is at the > top of the screen on the Mac, attached to a window on Windows). I was actually referring to click-and-hold vs just click. If Tk wraps the native menu on OS X (it doesn't on Windows) then that'll be taken care of though. I don't think you can emulate menus on OS X the way you can on Windows, though, so if they're where they're supposed to be they're probably native ones. >The Tk > scrollbar is native on the Mac; the Tile scrollbar has problems. On > Windows, the Tile scrollbar maps to Vista or XP or Win32, depending on > Windows version. You need to correctly specify the command-accelerator > in your code (on Windows it's the Control key, on the Mac it's Command), That's an interesting gap, since Tk gets other more subtle stuff right. > but assuming you do this, it works fine. I don't use "home" and "end" > keys myself (I think these are more common on Windows than Mac) so I > can't speak to that. Just examples. Text navigation has different conventions on a Mac vs Windows (or Gtk/KDE). I wouldn't expect Tk to get it right unless it wrapped the native control (which would give all kinds if neat benefits like spellcheck, too). Of course, if that's what it decides to do it will eventually end up being wxPython ;) >Under Tk, keyboard navigation with the tab key > generally works as expected on the Mac, and I assume so for Windows as > well. > > The biggest drawback with Tk/Tile on the Mac is that even with Tile > theming, it's still a bit outdated--Tile hooks into some older API's on > the Mac that are more compatible with Tk; for instance, the notebook > tabs look like Jaguar-era tabs (c. 2002). The Tile scrollbar is broken, > but the Tk one works natively. > > Tile on Windows looks pretty darn good--I've played with the Windows > Inspection Tool Kit, a well-designed Tcl/Tk application on Windows XP > that uses Tile, and it's indistinguishable from something developed in > VB or Delphi. (See http://magicsplat.com/wits/screenshot.html). Tile on > the Mac requires a bit more hackery, but it's quite possible to get > something looking nearly native (see > http://www.codebykevin.com/portauthority.html). > > As for X, Tk and Tile are more of a mixed bag, because there is simply > no single standard to target. Standard Tk looks and feels like Motif, as > you know. Some of the Tile themes under X don't look much better. The > most popular Tile theme on X is probably Clam, which looks more like a > modern Gtk Clearlooks-style theme (see > http://tktable.sourceforge.net/tile/screenshots/demo-clam-unix.png or > http://www.codebykevin.com/pylocate-tile-x11.png). As far as I know, > Tk/Tile offers reasonable defaults for X, unless you are looking for > specfic integration with a particular environment (i.e. Gnome or KDE); > in that case it's not as acceptable. > The situation under *nix is more complex, where you may or may not have a DE with its own preferred toolkit. I use Gnome, so I expect (and require) my apps to either use Gtk or fake it well enough that I can't tell the difference, but I don't judge the strength of a cross platform toolkit on that. There are some cases where you just can't do everything in the toolkit. One of the things that I really like about wxPython from a cross platform perspective is how easily it lets you tell it to "do the right thing for this platform". Stock buttons let you have the right icons under Gtk, but the descriptive labels that OS X expects. There's a stock button sizer that gets the layout and order of ok/cancel correct. If you use the stock IDs for your menus, wxPython will put the about and preferences menus items in the right spot and give you the correct preferences accelerator on OS X. Stuff like that. > > > > Don't think I'm singling out Tk, Gtk has exactly the same problem - > > you can make the buttons look native, but it doesn't adjust the > > behavior. > > Tk does a better job with platform-specific defaults and behaviors than > Gtk. When I read complaints about Tk on Windows, it's more on how ugly > Tk is, not that its menus/keyboard behaviors don't work correctly. > Gtk is pretty bad, using it's own dialogs and even it's own painting model. Tk has some definite lacks, though. I find the menus especially obnoxious. I'm unusually picky about native integration though. From kyosohma at gmail.com Fri Aug 17 10:36:35 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 17 Aug 2007 07:36:35 -0700 Subject: passing variables and values to texboxdisplays In-Reply-To: <1187351867.699825.91860@57g2000hsv.googlegroups.com> References: <1187351867.699825.91860@57g2000hsv.googlegroups.com> Message-ID: <1187361395.507282.90540@z24g2000prh.googlegroups.com> On Aug 17, 6:57 am, yadin <conra2... at yahoo.com> wrote: > hi! > Can any one tell me why is it that i can't see my second frame and why > is the value of freq not Appended in the First frame ...thanks > I know it is wx python but it has to do with passing variables.thanks > > import wx > > def create(parent): > return Frame1(parent) > > [wxID_FRAME1, wxID_FRAME1FREQ, wxID_FRAME1FREQDISP, > wxID_FRAME1STATICTEXT1, > ] = [wx.NewId() for _init_ctrls in range(4)] > > class Frame1(wx.Frame): > def _init_ctrls(self, prnt): > # generated method, don't edit > wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt, > pos=wx.Point(380, 179), size=wx.Size(241, 133), > style=wx.DEFAULT_FRAME_STYLE, title='Frame1') > self.SetClientSize(wx.Size(233, 99)) > > self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1, > label='frequency disp', name='staticText1', parent=self, > pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) > > self.freqdisp = wx.TextCtrl(id=wxID_FRAME1FREQDISP, > name='freqdisp', > parent=self, pos=wx.Point(104, 24), size=wx.Size(100, > 21), > style=0, value='') > > self.freq = wx.Button(id=wxID_FRAME1FREQ, label='get freq', > name='freq', > parent=self, pos=wx.Point(24, 56), size=wx.Size(184, > 23), > style=0) > self.freq.Bind(wx.EVT_BUTTON, self.OnButton1Button, > id=wxID_FRAME1FREQ) > > def __init__(self, parent): > self._init_ctrls(parent) > > def OnButton1Button(self, event): > > def create(parent): > return Frame2(parent) > [wxID_FRAME2, wxID_FRAME2FREQ, wxID_FRAME2FREQDISP, > wxID_FRAME2STATICTEXT1,] = [wx.NewId() for _init_ctrls in range(4)] > > class Frame2: > def __init__(self): > # > wx.Frame.__init__(self, id=wxID_FRAME2, name='', > parent=prt, > pos=wx.Point(400, 179), size=wx.Size(300, 133), > style=wx.DEFAULT_FRAME_STYLE, title='Frame2') > self.SetClientSize(wx.Size(233, 99)) > > self.staticText1 = > wx.StaticText(id=wxID_FRAME2STATICTEXT1, > label='frequency goes here first', > name='staticText2', parent=self, > pos=wx.Point(24, 32), size=wx.Size(71, 13), > style=0) > > self.freqdisp2 = wx.TextCtrl(id=wxID_FRAME2FREQDISP, > name='freqdisp2', > parent=self, pos=wx.Point(104, 24), > size=wx.Size(100, 21), > style=0, value=' ') > > self.freq = wx.Button(id=wxID_FRAME2FREQ, label='get > freq', name='freq', > parent=self, pos=wx.Point(24, 56), > size=wx.Size(184, 23), > style=0) > self.freq.Bind(wx.EVT_BUTTON, self.OnButton2Button, > id=wxID_FRAME2FREQ) > > def __init__(self, parent): > self._init_ctrls(parent) > def OnButton2Button(self, event): > freqdisp.Append('this is it 24HZ!') > > if __name__ == '__main__': > app = wx.PySimpleApp() > frame = create(None) > frame.Show() > > app.MainLoop() Your 2nd frame isn't subclassing wx.Frame and there's nothing calling the Show() method even if it had been. Mike From steve at holdenweb.com Thu Aug 23 23:37:55 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 23 Aug 2007 23:37:55 -0400 Subject: IDE for Python In-Reply-To: <46CDA242.3010108@bigfoot.com> References: <mailman.55.1187690455.32294.python-list@python.org> <1187698999.545439.322600@k79g2000hse.googlegroups.com> <mailman.91.1187742207.32294.python-list@python.org> <hTPyi.4052$Oo.2475@newssvr17.news.prodigy.net> <46CDA242.3010108@bigfoot.com> Message-ID: <faljqo$vnc$1@sea.gmane.org> Ricardo Ar?oz wrote: > I V wrote: >> On Tue, 21 Aug 2007 21:23:25 -0300, Ricardo Ar?oz wrote: >>> Do you know if for in-house development a GPL license applies? (Qt4 >>> and/or Eric4). >> (I'm not sure if I've understood your question right) >> >> If you distribute an app that _uses_ PyQT, you have to comply with the GPL >> (or buy a license from Trolltech), but note that this doesn't really have >> anything to do with Eric4. Running Eric4 doesn't require a license (either >> the GPL or Trolltech), and code you write using Eric4 doesn't have to be >> licensed according to the GPL either. > > I think they key word would be 'distribute'. I don't plan to distribute > the software. It will be used in-house for a commercial company which > pays for my time, they'll keep the source code but they won't be > distributing or selling it. Am I ok with QT4 ? (this is Windows). > First: I am not a lawyer, so you should ask the licensor. But it seems to me that if the company you contract to (i.e. the end user) pays for the license there is little to cause anyone problems. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From whamil1 at entergy.com Thu Aug 30 14:15:40 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Thu, 30 Aug 2007 13:15:40 -0500 Subject: list index() In-Reply-To: <1188495863.242815.236900@o80g2000hse.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CB29@LITEXETSP001.etrsouth.corp.entergy.com> > From: zzbbaadd at aol.com > > > > How could it not be an exception, in the plain English sense of the > > word? Most certainly you're asking for the index because you want to do > > something with the index. If the item is not found, you have no index, > > so that's a special case that must be handled separately. There is no > > logical difference between handling that special case in an except > > clause versus handling it with an if-branch. > > In my case of have done os.listdir() on two directories. I want to see > what files are in directory A that are not in directory B. > I have used exceptions in other languages and only do so on logic that > should never happen. In this case it is known that some of the files > will not be in both lists. I just want to know which ones. > I think you may be confusing exceptions and assertions. Asserts are generally used to trap conditions that should not happen, while exceptions in Python are a standardized way to handle errors of all sorts. Where in C you would, say, open a file and check the return code to ensure that the file actually exists before using it, in Python you wrap the open statement in a try/except block instead. -- -Bill Hamilton From nrmn_ncjs at yahoo.com Mon Aug 20 19:41:56 2007 From: nrmn_ncjs at yahoo.com (nrmn) Date: Mon, 20 Aug 2007 16:41:56 -0700 (PDT) Subject: wx.Frame event handler problems Message-ID: <596840.12141.qm@web60620.mail.yahoo.com> i have a function (event handler) inside a wx.Frame subclass which reads 2 kinds of data (differentiated by a prefix char) from a file and updates the text on the UI. def onStartParsing(self, event): file = open('data.txt','r') while 1: input = file.readline().strip('\r\n') try: if input[0] == '-': # data A self.data_A_display.SetLabel(input.strip('-')) wx.Yield() elif input[0] == '+': # data B self.data_B_display.SetLabel(input.strip('+')) wx.Yield() except IndexError: # EOF file.close() break what i'd like to do is, if i click a button or an item in a menu, it will send the input variable to another pc through sockets. i am lost at how to 'update' the function such that it would look something like this: # after a user has clicked a button def onStartParsing(self, event): file = open('data.txt','r') sock_a = socket(AF_INET,SOCK_DGRAM) sock_a.bind(ADDR) while 1: input = file.readline().strip('\r\n') sock_a.sendto('%s' % input, ADDR) try: if input[0] == '-': # data A self.data_A_display.SetLabel(input.strip('-')) wx.Yield() elif input[0] == '+': # data B self.data_B_display.SetLabel(input.strip('+')) wx.Yield() except IndexError: # EOF file.close() break another solution i thought was to create another event handler that contains the following body above, but it should terminate/stop running the while loop in the original onStartParsing event-handler. problem is i don't know how. other solutions, suggestions are very much welcome. -norman ancajas --------------------------------- Need a vacation? Get great deals to amazing places on Yahoo! Travel. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070820/e0f4ddc2/attachment.html> From omari at smileystation.com Tue Aug 7 10:08:47 2007 From: omari at smileystation.com (Omari Norman) Date: Tue, 7 Aug 2007 10:08:47 -0400 Subject: All leading tabs or all leading spaces - why isn't that enforced? In-Reply-To: <f98qa9$n9v$2@sea.gmane.org> References: <y8Rti.1088$3x.121@newssvr25.news.prodigy.net> <f98qa9$n9v$2@sea.gmane.org> Message-ID: <20070807140847.GA12398@cameron> > I suppose we Pythonistas are just too permissive for our own good. > Consider the opportunity to use mixed tabs and spaces a piece of rope of > your preferred length ... I thought I remembered reading somewhere that Python 3000 will ban tabs as indentation characters, but now I can't turn up a link for it... -- You can't lose what you never had. From beema.shafreen at gmail.com Thu Aug 2 07:25:54 2007 From: beema.shafreen at gmail.com (Beema shafreen) Date: Thu, 2 Aug 2007 16:55:54 +0530 Subject: beginner in python Message-ID: <aa405c1f0708020425w12407dcfldb78540d19aa4990@mail.gmail.com> Hi everybody , I am a beginner in python, I have to fetch the redundant entries from a file, code: import re L = [] fh = open('ARCHITECTURE_MAIN.txt','r') for line in fh.readlines(): data =line.strip() # splitted = data.split('#') L.append(data) fh.close() M=L for x in L: x = x.split('#') for y in M: y = y.split('#') x_data = x[0],x[1],x[2],x[3] #print x_data y_data = y[0],y[1],y[2],y[3] #print y_dat if x_data[0] == y_data[0]: print x_data i get the result as a tupule, the text file which has datas separated by hash entry#isoform#start#stop# i have to check upto this 00250_1#ARCH_104#61#89#Literature#9224948#00250#### 00250_1#ARCH_104#97#126#Literature#9224948#00250#### 00250_1#ARCH_104#139#186#Literature#9224948#00250#### 00251_1#ARCH_463#7#59#SMART##00251#### 00251_1#ARCH_463#91#121#SMART##00251#### 00251_1#ARCH_463#251#414#SMART##00251#### 00251_1#ARCH_463#540#624#SMART##00251#### 00252_1#ARCH_474#1#21#Literature#8136357#00252#### 00252_1#ARCH_393#481#501#Literature#8136357#00252#### 00252_1#ARCH_463#523#553#SMART##00252#### 00253_1#ARCH_82#37#362#SMART##00253#### 00253_1#ARCH_54#365#522#SMART##00253#### 00253_1#ARCH_104#589#617#SMART##00253#### 00253_1#ARCH_104#619#647#SMART##00253#### 00253_1#ARCH_104#684#712#SMART##00253#### 00254_1#ARCH_82#27#352#SMART##00254#### 00254_1#ARCH_54#355#510#SMART##00254#### 00254_1#ARCH_104#576#604#SMART##00254#### 00254_1#ARCH_104#606#634#SMART##00254#### 00254_1#ARCH_104#671#699#SMART##00254#### 00255_1#ARCH_82#56#425#SMART##00255#### 00255_1#ARCH_54#428#582#SMART##00255#### 00255_1#ARCH_104#696#724#SMART##00255#### can you suggest me ,what are the improvement i have to make in the above code regards shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070802/472da754/attachment.html> From pyth0nc0d3r at gmail.com Fri Aug 24 19:46:39 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Fri, 24 Aug 2007 18:46:39 -0500 Subject: Converting my script from MS-DOS to Tkinter ran in a problem. Message-ID: <eb79828c0708241646x115a6a31ifcc9b7303f3fea9c@mail.gmail.com> Ok my script works decent so far, but say in the add news menu, my window dissapears right? but when i click add news on the main menu a new frame gets added, How can I remove the frames inside of my Toplevel? import sys,os,urllib,urllib2,md5,random,string from Tkinter import * main = Tk() main.withdraw() false = 0 true = 1 logged_in = false _user = "" _pass = "" _input1 = "" _input2 = "" url = "http://SITENAME.com/" def dir_path(): upath = os.path.realpath(os.path.dirname(sys.argv[0])) return upath def md5_(hash): hash = md5.new(hash) hash = hash.hexdigest() return hash class NewsSystem: def check_login(self): global e1,e2,master,_user,_pass,url,logged_in,true,choices _input1 = e1.get() _input2 = e2.get() domain = "%slogin.php?action=login" % (url) if _input1 != "" and _input2 != "": password = md5_(_input2) username = _input1 send = {'username' : username,'password' : password } data = urllib.urlencode(send) request = urllib2.Request(domain,data) response = urllib2.urlopen(request) loggedin = response.read() if loggedin == "true": print "Logged in successful\n" logged_in = true _user = username _pass = password master.destroy() choices.deiconify() else: print "Login failed\n" logged_in = false def V(self): global v,textboxed,choices if v.get() == 1: choices.withdraw() textboxed.deiconify() self.addnews(textboxed) elif v.get() == 2: print v.get() elif v.get() == 3: print v.get() elif v.get() == 4: sys.exit() else: print "error"; def addnews(self,main): menubar = Frame(main,relief=RAISED) menubar.pack(side=TOP) menuu = Menubutton(menubar,text="News Options") menuu.pack(side=LEFT) menuu.menu = Menu(menuu) menuu.menu.add_command(label='Add News') menuu.menu.add_command(label='Main Menu',command=self.main_menu) menuu.menu.add_command(label='Exit',command=self.close_me) menuu['menu'] = menuu.menu menuu.pack(side=LEFT) framx = Frame(main) framx.pack() self.textw = Text(framx,width=100,height=10) main.title("This is a textbox derr") scroll = Scrollbar(framx,command="scroll") self.textw.configure(yscrollcommand=scroll.set) scroll.pack(side=RIGHT) self.textw.pack() def close_me(self): sys.exit() def main_menu(self): global choices,textboxed choices.deiconify() textboxed.withdraw() init = NewsSystem() #Menu choices = Toplevel() choices.withdraw() v = IntVar() Radiobutton(choices, text="Add News", variable=v,value=1).pack(anchor=W) Radiobutton(choices, text="Edit News", variable=v,value=2).pack(anchor=W) Radiobutton(choices, text="Delete News", variable=v,value=3).pack(anchor=W) Radiobutton(choices, text="Quit", variable=v,value=4).pack(anchor=W) button = Button(choices, text="Action?",command=init.V).pack(anchor=W) choices.title("What are your actions?") #login master = Toplevel() Label(master, text="Username").grid(row=0, sticky=W) Label(master, text="Password").grid(row=1, sticky=W) e1 = Entry(master) e2 = Entry(master,show="*") e3 = Button(master,text="Login",command=init.check_login).grid(row=3, sticky=W+E+S+N) e1.grid(row=0, column=1) e2.grid(row=1, column=1) master.geometry("%dx%d" % (300,300)) master.title("Login!") #textbox textboxed = Toplevel() textboxed.withdraw() main.mainloop() -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070824/13a4f5e0/attachment.html> From kbk at shore.net Thu Aug 23 17:53:14 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Thu, 23 Aug 2007 17:53:14 -0400 (EDT) Subject: Final SF Python Patch/Bug Summary Message-ID: <200708232153.l7NLrEUg021672@hampton.thirdcreek.com> New / Reopened Patches ______________________ minidom pretty xml output improvement (2007-08-19) http://python.org/sf/1777134 opened by Teajay removeTest() method patch for unittest.TestSuite (2007-08-21) http://python.org/sf/1778410 opened by Mark Edgington robotparser.py fixes (2007-08-21) http://python.org/sf/1778443 opened by Indy Remove redundancies inside class logging.Logger (2007-08-22) http://python.org/sf/1779550 opened by Carsten Grohmann Replace AtheOS w/ Syllable (2007-08-22) http://python.org/sf/1779613 opened by Skip Montanaro Make python build with gcc-4.2 on OS X 10.4.9 (2007-08-23) http://python.org/sf/1779871 opened by Jeffrey Yasskin Patches Closed ______________ distutils.util.get_platform() return value on 64bit Windows (2007-07-27) http://python.org/sf/1761786 closed by mhammond MSVC6/7 issues with bdist_wininst and --target-version (2004-07-01) http://python.org/sf/983164 closed by mhammond Override flags set by IOBase in io.StringIO (2007-08-15) http://python.org/sf/1774828 closed by avassalotti Convert str to bytes in io.BytesIO.__init__ (2007-08-15) http://python.org/sf/1774833 closed by avassalotti BufReader, TextReader for PEP 3116 "New I/O" (2007-06-04) http://python.org/sf/1731036 closed by gvanrossum utf-32 codecs (2007-08-16) http://python.org/sf/1775604 closed by gvanrossum Make it possible to use SVK to develop Python (2007-08-14) http://python.org/sf/1774414 closed by collinwinter New / Reopened Bugs ___________________ memoryview('test') is causing a segfault (2007-08-19) CLOSED http://python.org/sf/1777057 reopened by tiran Please warn about a subtle trap (2007-08-19) CLOSED http://python.org/sf/1777160 opened by Greg Kochanski Confusing typography Python Ref 5.9 (2007-08-19) CLOSED http://python.org/sf/1777168 opened by Greg Kochanski IDLE Freezes After Running Scripts (2007-08-19) http://python.org/sf/1777398 opened by Ross Peoples Python's strftime dislikes years before 1900 (2007-08-20) http://python.org/sf/1777412 opened by Benno Rice glob doesn't return unicode with unicode parameter (2007-08-20) http://python.org/sf/1777458 opened by Grzegorz Adam Hankiewicz ctypes on Solaris (2007-08-20) http://python.org/sf/1777530 opened by Aki rounding inconsisntency using string formatting (2007-08-20) CLOSED http://python.org/sf/1778207 opened by Jim Hurlburt Segfault. (2007-08-21) http://python.org/sf/1778376 opened by Maciek Fijalkowski PyThreadState_SetAsyncExc and the main thread (2007-08-22) http://python.org/sf/1779233 opened by Rotem urlparse.urljoin does not obey current uri rfc (rfc 3986) (2007-08-22) http://python.org/sf/1779700 opened by John Adams Bugs Closed ___________ memoryview('test') is causing a segfault (2007-08-18) http://python.org/sf/1777057 closed by nnorwitz memoryview('test') is causing a segfault (2007-08-18) http://python.org/sf/1777057 closed by nnorwitz Please warn about a subtle trap (2007-08-19) http://python.org/sf/1777160 closed by gbrandl Confusing typography Python Ref 5.9 (2007-08-19) http://python.org/sf/1777168 closed by gbrandl struni: str() doesn't call __str__() of subclasses of str (2007-07-11) http://python.org/sf/1751598 closed by tiran rounding inconsisntency using string formatting (2007-08-21) http://python.org/sf/1778207 closed by loewis mapitags.PROP_TAG() doesn't account for new longs (2004-12-31) http://python.org/sf/1093389 closed by mhammond Overenthusiastic check in Swap? (2004-04-01) http://python.org/sf/926910 closed by mhammond From horpner at yahoo.com Sat Aug 11 07:28:18 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 11 Aug 2007 11:28:18 GMT Subject: Something in the function tutorial confused me. References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <slrnfbe1fd.n4.horpner@FIAD06.norwich.edu> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <slrnfbeofu.20s.horpner@FIAD06.norwich.edu> <1186424693.529497.217040@w3g2000hsg.googlegroups.com> <46B8626A.2070303@bigfoot.com> <mailman.1726.1186537161.22759.python-list@python.org> <5hsoi3F3mlni2U1@mid.individual.net> <f9ceb9$jsm$1@sea.gmane.org> <1186581124.3383.55.camel@dot.uniqsys.com> <mailman.1751.1186588156.22759.python-list@python.org> <slrnfbk19k.20o.horpner@FIAD06.norwich.edu> <1i2nhxn.tme05x17r39odN%aleax@mac.com> Message-ID: <m3hvi.37606$G23.6240@newsreading01.news.tds.net> On 2007-08-11, Alex Martelli <aleax at mac.com> wrote: > Neil Cerutti <horpner at yahoo.com> wrote: > ... >> The Python Language Reference seems a little confused about the >> terminology. >> >> 3.4.7 Emulating numeric types >> 6.3.1 Augmented assignment statements >> >> The former refers to "augmented arithmetic operations", which I >> think is a nice terminology, since assignment is not necessarily >> taking place. Then the latter muddies the waters. > > Assignment *IS* "necessarily taking place"; if you try the augmented > assignment on something that DOESN'T support assignment, you'll get an > exception. Consider: > >>>> tup=([],) >>>> tup[0] += ['zap'] > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: 'tuple' object does not support item assignment > > Tuples don't support item ASSIGNMENT, and += is an ASSIGNMENT, > so tuples don't allow a += on any of their items. > > If you thought that += wasn't an assignment, this behavior and > error message would be very problematic; since the language > reference ISN'T confused and has things quite right, this > behavior and error message are perfectly consistent and clear. Thanks for the correction. I was under the illusion that sometimes augmented assignment would instead mutate the object. -- Neil Cerutti From victor.lebrun at gmail.com Tue Aug 28 11:30:30 2007 From: victor.lebrun at gmail.com (vml) Date: Tue, 28 Aug 2007 15:30:30 -0000 Subject: in design time activeX properties Message-ID: <1188315030.750795.90330@22g2000hsm.googlegroups.com> Hello, Does anybody know how to modify the property of a design-time activeX property ? using win32com thank you for your help, regards, Victor From gherron at islandtraining.com Thu Aug 16 04:20:38 2007 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 16 Aug 2007 01:20:38 -0700 Subject: python socket usage In-Reply-To: <1187250839.541105.60900@r29g2000hsg.googlegroups.com> References: <mailman.2046.1187250159.22759.python-list@python.org> <1187250839.541105.60900@r29g2000hsg.googlegroups.com> Message-ID: <46C408D6.8000907@islandtraining.com> markacy wrote: > On 16 Sie, 09:42, O uz Yar mtepe <comp.... at gmail.com> wrote: > >> Is it possible to send a data object like a tuple or a list in socket >> programming? If so how? It seems with socket module it is only possible to >> send strings. >> >> -- >> O uz Yar mtepehttp://www.yarimtepe.com/en >> > > Hi Oguz, > > why don't you make a string out of your tuple, or list, send it via > socket and make a tuple/list again? > > >>>> x = (1,2,3,4,5,6,7,) >>>> type(x) >>>> > <type 'tuple'> > >>>> y = str(x) >>>> type(y) >>>> > <type 'str'> > >>>> print y >>>> > (1, 2, 3, 4, 5, 6, 7) > >>>> z = tuple(y) >>>> type(z) >>>> > <type 'tuple'> > Sure it's a tuple, but did you look at it? Turning a sequence (which is what a string is after all) into a tuple is an easy operation, but it's surely not what you want here. >>> x = (1,2,3,4,5,6,7) >>> s = str(x) >>> t = tuple(s) >>> t ('(', '1', ',', ' ', '2', ',', ' ', '3', ',', ' ', '4', ',', ' ', '5', ',', ' ', '6', ',', ' ', '7', ')') If you want to turn a string representation of an object back into an object, you must eval the string. Moreover, if the tuple contains things other than simple integers (float of strings of whatever) the string represtnataion of the object may not be able to recover the original object accurately. Worse yet, an eval of an arbitrary string is a HUGE security hole. If you really want to send any Python object through a socket, look up the Pickle and cPickle modules. These will marshal (as it's called) any Python object of any type and complexity into a byte string which can be sent across a socket. On the receiving end of the socket, the byte string can be turned back into an equivalent Python object. Gary Herron > > Cheers, > Marek > > From carsten at uniqsys.com Wed Aug 29 21:00:52 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 29 Aug 2007 21:00:52 -0400 Subject: copying files In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE30E@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE30C@efmailx> <46D5C01B.7080202@bigfoot.com> <93066C069973ED448DC2BCEA9C44A7383BE30E@efmailx> Message-ID: <1188435652.3251.3.camel@localhost.localdomain> On Wed, 2007-08-29 at 17:03 -0400, Brian McCann wrote: > what do the + signs do? Start here: http://docs.python.org/tut/ -- Carsten Haese http://informixdb.sourceforge.net From news at sandipan.com Wed Aug 29 21:40:55 2007 From: news at sandipan.com (Sandipan News) Date: Wed, 29 Aug 2007 21:40:55 -0400 Subject: Pythonwin Install COM exceptions on Windows Vista Ultimate In-Reply-To: <46d578dc$0$25911$ba4acef3@news.orange.fr> References: <mailman.95.1188374497.28954.python-list@python.org> <46d578dc$0$25911$ba4acef3@news.orange.fr> Message-ID: <00a701c7eaa6$d13c01f0$73b405d0$@com> How do I deactivate UAC and Router? I did run as Administrator and installed both Python and Pythonwin into c:\Python25\ This is the error I got ... Here is the log at the end of the install: Copied pythoncom25.dll to C:\Outils\Python\pythoncom25.dll Copied pywintypes25.dll to C:\Outils\Python\pywintypes25.dll You do not have the permissions to install COM objects. The sample COM objects were not registered. -> Software\Python\PythonCore\2.5\Help[None]=None -> Software\Python\PythonCore\2.5\Help\Pythonwin Reference[None]='C:\\Outils\\Python\\Lib\\site-packages\\PyWin32.chm' Creating directory C:\Outils\Python\Lib\site-packages\win32com\gen_py Shortcut for Pythonwin created Shortcut to documentation created The pywin32 extensions were successfully installed. Thanks. Sandipan -----Original Message----- From: python-list-bounces+news=sandipan.com at python.org [mailto:python-list-bounces+news=sandipan.com at python.org] On Behalf Of M?ta-MCI (MVP) Sent: Wednesday, August 29, 2007 9:19 AM To: python-list at python.org Subject: Re: Pythonwin Install COM exceptions on Windows Vista Ultimate Hi! Perso, on Vista, I : - deactive UAC - deactive firewall (I have a rooter) - run all like Administrator - install all in other DIR than "Program Files" Result : no problem. -- http://mail.python.org/mailman/listinfo/python-list From kyosohma at gmail.com Fri Aug 31 09:34:51 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 31 Aug 2007 06:34:51 -0700 Subject: create Powerpoint via com In-Reply-To: <EaNBi.20336$vg.15115@trnddc04> References: <j7EBi.13372$Yg.7724@trnddc02> <1188500822.869925.194430@e9g2000prf.googlegroups.com> <EaNBi.20336$vg.15115@trnddc04> Message-ID: <1188567291.037504.232850@r34g2000hsd.googlegroups.com> On Aug 30, 11:55 pm, Alan Isaac <ais... at american.edu> wrote: > kyoso... at gmail.com wrote: > > <code> > > OK, creating bulleted lists, or tables, > or adding pictures is all straightforward. > How about chart creation (in Ppt 2003)? > I do not see how to do this with Python. > > Thanks, > Alan Alan, You probably need to browse the COM object using PythonWin, which is a part of the ActiveState distro. You can also use Python's builtin function, dir, to find out various methods of COM. Here's some info in messing with charts in Excel, which should be similar to chart manipulation in PowerPoint. http://mail.python.org/pipermail/python-win32/2005-June/003511.html http://mail.python.org/pipermail/python-win32/2003-March/000839.html http://www.thescripts.com/forum/thread21565.html http://mathieu.fenniak.net/plotting-in-excel-through-pythoncom/ Mike From steveo at syslang.net Tue Aug 7 12:09:31 2007 From: steveo at syslang.net (Steven W. Orr) Date: Tue, 7 Aug 2007 12:09:31 -0400 (EDT) Subject: Another question about variable args. Message-ID: <alpine.LFD.0.999.0708071151590.17089@saturn.syslang.net> I have a structure I need to pack. I call struct.pack about a dozen times and each call takes about 53 arguments. I create a sequence of the arguments: a1 = 1 a2 = 2 a3 = 3 etc... a54 = 88 myseq = (a1, a2, a3, a4 etc... a53) Also I made def mpack ( fmt, *ss ): print type(ss) for ii in ss: print 'ii = ', ii, 'type(ii) = ', type(ii) for ii in list(ss): print 'ii = ', ii, 'type(ii) = ', type(ii) return struct.pack(fmt, *ss ) In my main, this first print statement works. print 'main:', mpack(ff, a, b, c, d, e, f, g, h, i) 1. For the life of me, I can't figure out what to do to get the next print to work. The idea is that I want to make my code clearer by not passing 50+ args each time and to instead pass a sequence which when evaluated will be the desired list of args. print 'main:', mpack(ff, subseq) 2. And then, if possible, I'd like to do it in such a way that one myseq is defined, its value can automagically be re-eval'd so I don't have to re-assign to myseq each time one of the 50+ variables changes prior to calling pack. Does this make sense? -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From newsuser at stacom-software.de Wed Aug 15 04:15:15 2007 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Wed, 15 Aug 2007 10:15:15 +0200 Subject: What does r"""any text""" mean ? Message-ID: <f9ucmj$ja2$1@online.de> ... as you can find in os.py at line 1 ? Regards Alexander From orsenthil at users.sourceforge.net Tue Aug 14 16:06:43 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Wed, 15 Aug 2007 01:36:43 +0530 Subject: import * is not allowed ?? In-Reply-To: <46C0F3CC.1050704@gmail.com> References: <46C0F3CC.1050704@gmail.com> Message-ID: <20070814200643.GB4517@gmail.com> * stef mientki <stef.mientki at gmail.com> [2007-08-14 02:14:04]: > import * is not allowed in function 'JAL_MAIN_RUN' because it contains > a nested function with free variables (JAL_simulation_file.py, line 22) > What is the actual error message you are getting? Can you paste the stack trace or a link to the program? -- O.R.Senthil Kumaran http://uthcode.sarovar.org From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Aug 10 07:59:58 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 10 Aug 2007 13:59:58 +0200 Subject: The Future of Python Threading References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> Message-ID: <5i329uF3muir4U1@mid.individual.net> Justin T. wrote: > The detrimental effects of the GIL have been discussed several > times and nobody has ever done anything about it. Also it has been discussed that dropping the GIL concept requires very fine locking mechanisms inside the interpreter to keep data serialised. The overhead managing those fine ones properly is not at all negligible, and I think it's more than managing GIL. > The truth is that the future (and present reality) of almost every > form of computing is multi-core, Is it? 8) The question is: If it really was, how much of useful performance gain would you get? Regards, Bj?rn -- BOFH excuse #336: the xy axis in the trackball is coordinated with the summer solstice From zentraders at gmail.com Fri Aug 3 13:55:38 2007 From: zentraders at gmail.com (Zentrader) Date: Fri, 03 Aug 2007 17:55:38 -0000 Subject: i am new to python-Please somebody help In-Reply-To: <mailman.1558.1186124330.22759.python-list@python.org> References: <1186047103.673871.150460@z24g2000prh.googlegroups.com> <46b249a4$0$31219$426a74cc@news.free.fr> <mailman.1558.1186124330.22759.python-list@python.org> Message-ID: <1186163738.568489.129020@e16g2000pri.googlegroups.com> On the discussion of rudeness, we have to include the OP. He/She/it did not even attempt a Google before posting, and posted with a meaningless subject. We'll chalk that up to newness, but some sort of retort was called for IMHO. How else do we learn the conventions that govern rudeness. Personally, there is only one form of rudeness that can not be overlooked and that is the prima donna that says "My Way Is The Only Way", or posts some nonsense like "that is not correct" with no other explanation. Any attempt to sincerely help, I can live with. From exarkun at divmod.com Thu Aug 9 10:36:52 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 9 Aug 2007 10:36:52 -0400 Subject: Stackless Integration In-Reply-To: <81C07501-369D-4209-9A5F-34B446EDB8D3@jedimindworks.com> Message-ID: <20070809143652.4947.1275552699.divmod.quotient.20533@ohm> On Thu, 9 Aug 2007 05:05:31 -0700, Michael Bentley <michael at jedimindworks.com> wrote: > >On Aug 9, 2007, at 4:48 AM, Jean-Paul Calderone wrote: > >> On Thu, 09 Aug 2007 09:00:27 -0000, "Justin T." >> <jmtulloss at gmail.com> wrote: >>> Hi, >>> >>> I've been looking at stackless python a little bit, and it's awesome. >>> My question is, why hasn't it been integrated into the upstream >>> python >>> tree? Does it cause problems with the current C-extensions? It seems >>> like if something is fully compatible and better, then it would be >>> adopted. However, it hasn't been in what appears to be 7 years of >>> existence, so I assume there's a reason. >> >> It's not Pythonic. > >Can you be more specific? It's a good question that I had thought >about asking... It was meant tongue in cheek. "It's not Pythonic" is Pythoneer codespeak for "I have an irrational dislike of it", which is the only reason that has ever really been given for keeping Stackless separate from CPython. Perhaps the most reason which comes closest to being tangible is that it is "complex" and would require "maintenance". Jean-Paul From news at sandipan.com Wed Aug 29 21:39:24 2007 From: news at sandipan.com (Sandipan News) Date: Wed, 29 Aug 2007 21:39:24 -0400 Subject: Pythonwin Install COM exceptions on Windows Vista Ultimate In-Reply-To: <1188393923.239537.20590@50g2000hsm.googlegroups.com> References: <mailman.95.1188374497.28954.python-list@python.org> <1188393923.239537.20590@50g2000hsm.googlegroups.com> Message-ID: <00a601c7eaa6$9b825870$d2870950$@com> Here is the log at the end of the install: Copied pythoncom25.dll to C:\Outils\Python\pythoncom25.dll Copied pywintypes25.dll to C:\Outils\Python\pywintypes25.dll You do not have the permissions to install COM objects. The sample COM objects were not registered. -> Software\Python\PythonCore\2.5\Help[None]=None -> Software\Python\PythonCore\2.5\Help\Pythonwin Reference[None]='C:\\Outils\\Python\\Lib\\site-packages\\PyWin32.chm' Creating directory C:\Outils\Python\Lib\site-packages\win32com\gen_py Shortcut for Pythonwin created Shortcut to documentation created The pywin32 extensions were successfully installed. -----Original Message----- From: python-list-bounces+news=sandipan.com at python.org [mailto:python-list-bounces+news=sandipan.com at python.org] On Behalf Of kyosohma at gmail.com Sent: Wednesday, August 29, 2007 9:25 AM To: python-list at python.org Subject: Re: Pythonwin Install COM exceptions on Windows Vista Ultimate On Aug 28, 8:20 pm, "Sandipan News" <n... at sandipan.com> wrote: > What do I do? Can't do without Python! > Any experience, advice, hope is welcome. > Thanks. > Sandipan You need to post the error traceback along with some more information so the community can help. Mike -- http://mail.python.org/mailman/listinfo/python-list From ivlenin at gmail.com Tue Aug 21 01:49:01 2007 From: ivlenin at gmail.com (I V) Date: Tue, 21 Aug 2007 05:49:01 GMT Subject: Newbie question about a web server References: <1187593367.402094.235410@g4g2000hsf.googlegroups.com> Message-ID: <h1vyi.34263$2v1.9002@newssvr14.news.prodigy.net> On Mon, 20 Aug 2007 00:02:47 -0700, Frank Millman wrote: > When responding to the POST data received, it sends a 301 response, no > headers, and then the html page. [...] > According to the notes, "You don't have to know much about the HTTP > protocol at all. Except some basic that when the client request > something it is a "GET", and when the client sends something it is in > our case a POST. Some basic responce codes like 200 is OK for GET, and > 404 is file not found, 301 is OK for a Post." [...] > I googled for 'http response code 301', and found that it is actually > a redirection code. It seems that the notes are misleading. [...] > So I guess my questions are - > 1. what is the correct response for a POST? > I think the answer is 200. > However, I assume the author is trying to demonstrate a > particular technique. > Can anyone explain what that may be. The code at that site looks wrong to me; I suspect the original author was confused about status codes. If you return a 301 redirect code, you should include a Location: header specifying the URI to redirect to, which that code doesn't do. Also, if you return a redirect code, you probably shouldn't include any page content (except perhaps a link to the redirected page). Note also that 301 is a permanent redirect, that is, it should be used when the URI has changed permanently (and might cause your browser to, e.g., update its bookmarks). You're probably not going to use it in normal operation. I'm not sure what the author was trying to do, but there is one quite common case where redirects are used with POST request. When the POST request does something that you are probably not going to want to repeat, but you want the resulting page to contain information that the user might want to refresh, it's common to have the POST return a 302 status (a temporary redirect). One example where this is useful is posting comments to a forum or blog. Usually, when the comment is posted, you want to return to the list of all the comments. But the user might refresh that list of comments, and you don't want their comment to be posted again when they refresh. So you would have the POST for the comment respond, not with a list of comments, but with a redirect _to_ the list of comments. From hamish at cloud.net.au Mon Aug 20 23:49:59 2007 From: hamish at cloud.net.au (Hamish Moffatt) Date: Tue, 21 Aug 2007 03:49:59 GMT Subject: Syslog In-Reply-To: <1187654214.498082.225300@r34g2000hsd.googlegroups.com> References: <1187654214.498082.225300@r34g2000hsd.googlegroups.com> Message-ID: <Hhtyi.23800$4A1.21665@news-server.bigpond.net.au> greg wrote: > Could anyone tell me how I could syslog to a specific log (e.g. /var/ > log/daemon.log, /var/log/syslog.log...)? > > Thanks very much in advance! It's up to your syslogd to route messages into particular files, based on their facility and/or priority. Check out /etc/syslog.conf or equivalent on your system. Hamish From bj_666 at gmx.net Thu Aug 30 10:50:09 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Aug 2007 14:50:09 GMT Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <mailman.138.1188482060.28954.python-list@python.org> Message-ID: <5jo3p1Fh543U1@mid.uni-berlin.de> On Thu, 30 Aug 2007 09:53:53 -0400, Marshall T. Vandegrift wrote: > The Python string types have both the method `index()` which throws an > exception and the method `find()` which implements the same behavior but > returns -1 for not-found substrings. I would naively have assumed the > `list` type to provide both as well, but it provides only `index()`. > > Anyone know the reason for this lack of parallelism? Historical reasons and IIRC the `find()` method on strings will go away in Python?3.0. Ciao, Marc 'BlackJack' Rintsch From nmin at freenet.de Thu Aug 9 08:30:00 2007 From: nmin at freenet.de (nmin at freenet.de) Date: Thu, 09 Aug 2007 05:30:00 -0700 Subject: Jython - variables are stored somehow Message-ID: <1186662600.413645.25430@22g2000hsm.googlegroups.com> Hi, I'm using Jython in combination with java. I wrote a jython skript, which calls a function from another jython module called library.py. So, executing the function genData() in skript .py runs without problem but if I execute the same function again, the data from the first run is stored somehow and is added to the new data. So, if you look at the result: #1 in DatenTypen.py return an empty list each time the program runs. Ok ... clear so far #2 in library.py returns an empty list, when the program runs for the first time ... but when the function is called again, the list contains an element. Each time you call the function again, one element is added! Why?? out.abschnitte should be the same as printed in #1 or not? Here is the code: skript.py ====== from library import * def genData(): out=DMS_sendFiles_ein_Abschnitt([["testdata1.test","testdata2.test","testdata3.test"]]) return out library.py ======= from DatenTypen import AusgangsDatenDeichMonitor from DatenTypen import DMS_Abschnitt from DatenTypen import DMS_GeoData from DatenTypen import DMS_GeoDataFile def DMS_sendFiles_ein_Abschnitt(filelist): out=AusgangsDatenDeichMonitor() print "out.abschnitte: "+str(out.abschnitte) #2 abschnitt=DMS_Abschnitt() for f in filelist: data=DMS_GeoData() for layer in f: datalayer=DMS_GeoDataFile() datalayer.dateiname=layer datalayer.dateiinhalt="TEST" data.layerFiles.append(datalayer) abschnitt.bildSequenze.append(data) out.abschnitte.append(abschnitt) return out DatenTypen.py =========== class AusgangsDatenDeichMonitor: abschnitte=[] def __init__(self): abschnitte=[] print "Abschnitt in DatenTypen: "+str(abschnitte) #1 class DMS_Abschnitt: bildSequenze=[] def __init__(self): abschnittsNummer=0 bildSequenze=[] class DMS_GeoData: layerFiles=[] def __init__(self): layerFiles=[] class DMS_GeoDataFile: dateiinhalt="dateiinhalt" dateiname="dateiname" zipped=False def __init__(self): dateiinhalt="dateiinhalt" dateiname="dateiname" zipped=False So, I read about deleting Instances with "del" ... but it does not work at all. Any Ideas? Thanks in advance Simon From cai.haibin at gmail.com Thu Aug 9 22:51:44 2007 From: cai.haibin at gmail.com (james_027) Date: Fri, 10 Aug 2007 02:51:44 -0000 Subject: accessing static attributes Message-ID: <1186714304.352882.40520@j4g2000prf.googlegroups.com> hi, for example an request object ... is request.user the same as request.__class__.user? THanks james From bdesth.quelquechose at free.quelquepart.fr Mon Aug 20 14:41:00 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 20 Aug 2007 20:41:00 +0200 Subject: way to define static method In-Reply-To: <mailman.135.1187813614.32294.python-list@python.org> References: <de6dc4a00708221234q63752cc2xc7ac1b64495ae95e@mail.gmail.com> <mailman.135.1187813614.32294.python-list@python.org> Message-ID: <46ccb514$0$407$426a74cc@news.free.fr> Eric CHAO a ?crit : > Thanks a lot. > > Because I found a solution about static method from > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52304 This is a largely outdated recipe (while it may be usefull if you have to write code for an old Python version). > And that's a little bit difficult to understand. This of course require some knowledge of Python's internals. But unless you have to deal with older Python versions, you don't have to care about this - just use: class MyClass(object): @staticmethod def my_static_method(name): print name FWIW, there's not much use for staticmethods in Python - usually, a plain function is what you want. From jergosh at wp.pl Thu Aug 9 16:50:16 2007 From: jergosh at wp.pl (=?UTF-8?B?R3J6ZWdvcnogU8WCb2Rrb3dpY3o=?=) Date: Thu, 09 Aug 2007 22:50:16 +0200 Subject: Puzzled by "is" In-Reply-To: <f9frbl$dps$1@sea.gmane.org> References: <20070809194105.39BD11E400A@bag.python.org> <f9frbl$dps$1@sea.gmane.org> Message-ID: <46BB7E08.4070809@wp.pl> > > Why? Because. > > Seriously, it's just an optimization by the implementers. There is no > need for more than one empty tuple, since tuples can never be modified > once created. > > But they decided not to create (1, ) in advance. They probably knew that > hardly anybody would want to create that tuple ;-) [Seriously: if you > started trying to predict which tuples would be used you would go > insane, but the empty tuple is the most likely candidate]. > That's just theorisation but I'd rather expect the interpreter simply not to create a second tuple while there already is an identical one. This could save some memory if the tuple was large (Although by the same token comparison of large tuples can be expensive). Admittedly the empty tuple is a special case but then 'Special cases aren't special enough to break the rules'. A bit odd. Best regards, Greg From kib2 at free.fr Wed Aug 29 03:29:31 2007 From: kib2 at free.fr (tool69) Date: Wed, 29 Aug 2007 09:29:31 +0200 Subject: encoding problems Message-ID: <46d5215b$0$411$426a74cc@news.free.fr> Hi, I would like to transform reST contents to HTML, but got problems with accented chars. Here's a rather simplified version using SVN Docutils 0.5: %------------------------------------------------------------- #!/usr/bin/env python # -*- coding: utf-8 -*- from docutils.core import publish_parts class Post(object): def __init__(self, title='', content=''): self.title = title self.content = content def _get_html_content(self): return publish_parts(self.content, writer_name="html")["html_body"] html_content = property(_get_html_content) # Instanciate 2 Post objects p1 = Post() p1.title = "First post without accented chars" p1.content = """This is the first. ...blabla ... end of post...""" p2 = Post() p2.title = "Second post with accented chars" p2.content = """Ce poste poss?de des accents : ? ? ? ?""" for post in [p1,p2]: print post.title, "\n" +"-"*30 print post.html_content %------------------------------------------------------------- The output gives me : First post without accented chars ------------------------------ <div class="document"> <p>This is the first. ...blabla ... end of post...</p> </div> Second post with accented chars ------------------------------ Traceback (most recent call last): File "C:\Documents and Settings\kib\Bureau\Projets\python\dbTest\rest_error.py", line 30, in <module> print post.html_content UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 39: ordinal not in range(128) Any idea of what I've missed ? Thanks. From bignose+hates-spam at benfinney.id.au Mon Aug 6 03:19:26 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 06 Aug 2007 17:19:26 +1000 Subject: Relative-importing * References: <1185559874.299008.167010@x40g2000prg.googlegroups.com> <871weth2gg.fsf@benfinney.id.au> <pan.2007.07.28.06.17.39.399342@REMOVE.THIS.cybersource.com.au> <46ae3894$0$19609$426a34cc@news.free.fr> <1186200218.666444.254200@q3g2000prf.googlegroups.com> <87vebv9yrr.fsf@benfinney.id.au> <1186363732.188847.48070@q3g2000prf.googlegroups.com> Message-ID: <87zm15870h.fsf@benfinney.id.au> rbysamppi at gmail.com writes: > (In addition, it probably would make the program somewhat slower to > have an internal class inside every module, and performance is > important to me, as I'm planning to use this project in a future > game. This is known as "premature optimisation", and it's harmful. It's folly to avoid a core part of the language because you're worried about hypothetical performance issues. Instead, write your program so that it's easy to understand and maintain; then, if it's noticeably slow, *measure* the performance using profiling so you know exactly what is slow; then, and only then, work on speeding up the slow parts. > These modules are not going to have full-fledged object construction > and so forth. I don't want to construct and use objects at all If that's truly what you desire, you're using the wrong language. Everything in Python is an object, even if you don't use object-oriented programming. > it seems like a waste of time and memory to me to inherit __new__, > __del__, and so on. You've stated that you're a beginner to programming, so you probably are unaware that this statement has no basis in how class inheritance actually works. The point is that inherited behaviour is implemented in *one* place, not that it's repeated everywhere. Moreover, this is a further expression of your tendency for premature optimisation. You should aim instead to write code naturally (learning what's natural when you're a beginner), and only once you have something that *works* should you think about performance issues. > All that I want these modules to do is to encapsulate varying > information and behavior for /other/ objects to use.) This sounds like an ideal case for seeting up a class hierarchy for this move behaviour. > But regardless of if it's the "right thing to do", do you all think > it's an unintended bug? Do we think what is an unintended bug? I think if you go out of your way to avoid the class inheritance system for implementing what looks strongly like a hierarchy of behaviour, you will have design bugs. Hopefully now that you're reading this thread, they won't be *unintended* bugs; whether you *intentionally* proceed with a buggy design is up to you :-) -- \ "With Lisp or Forth, a master programmer has unlimited power | `\ and expressiveness. With Python, even a regular guy can reach | _o__) for the stars." -- Raymond Hettinger | Ben Finney From iapain at gmail.com Mon Aug 27 14:41:15 2007 From: iapain at gmail.com (iapain) Date: Mon, 27 Aug 2007 18:41:15 -0000 Subject: sorting a list of lists In-Reply-To: <46D31827.9060400@web.de> References: <1188233798.684136.263640@22g2000hsm.googlegroups.com> <1188235267.790442.193830@q5g2000prf.googlegroups.com> <46D31827.9060400@web.de> Message-ID: <1188240075.549626.42020@i38g2000prf.googlegroups.com> > Taking advantage of stable sorting is totally not a hack. The OP just tried > the two sorting steps in the wrong order. I didnt say not to use stable sorting, but write a generic function and hacky code. It is always better to adopt a generic approach. From steve at holdenweb.com Fri Aug 10 06:35:48 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 10 Aug 2007 06:35:48 -0400 Subject: Issues of state In-Reply-To: <5i2lk3F3m8h60U1@mid.individual.net> References: <op.tv98rva4wepdt4@ericb.pragmadev> <7x8x8mpn37.fsf@ruckus.brouhaha.com> <hblpo4-mgj.ln1@lairds.us> <7xfy2t8l5n.fsf@ruckus.brouhaha.com> <5uhro4-st8.ln1@lairds.us> <f9f9mr$cch$1@sea.gmane.org> <mailman.1800.1186676234.22759.python-list@python.org> <5i2lk3F3m8h60U1@mid.individual.net> Message-ID: <f9hf22$kff$1@sea.gmane.org> greg wrote: > Jay Loden wrote: >> Like most things involving dynamic client side-javascript code and AJAX >> technology, it's a lot harder than you'd like it to be to solve the problem, but >> in cases where the Back button is really an issue, it's worth the effort. > > So if you're willing to put in a huge amount of time, > effort and ingenuity, it's possible to overcome a > problem that only existed in the first place because > you chose an inappropriate technique for implementing > a user interface... > Exactly my point. Once you start to involve a complex framework to handle state and interactions you see less and less advantage to "desktop web" applications, since it's hard to match the directness and simplicity of a native GUI. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bbxx789_05ss at yahoo.com Sun Aug 12 10:23:15 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 12 Aug 2007 07:23:15 -0700 Subject: wxPython - drawing without paint event In-Reply-To: <5i8befF3o5no1U1@mid.individual.net> References: <1186710391.148396.113490@d30g2000prg.googlegroups.com> <1186738813.373909.96230@x35g2000prf.googlegroups.com> <1186796567.331348.42450@q3g2000prf.googlegroups.com> <5i5l0dF2lortaU1@mid.individual.net> <1186883988.585048.16590@m37g2000prh.googlegroups.com> <5i8befF3o5no1U1@mid.individual.net> Message-ID: <1186928595.014008.61950@b79g2000hse.googlegroups.com> On Aug 12, 6:06 am, Bjoern Schliessmann <usenet- mail-0306.20.chr0n... at spamgourmet.com> wrote: > I really recommend reading "wxPython in Action", or at least the > tutorial. > I don't. "wxPython in Action" is by far the worst computer book I've ever purchased. It's poorly organized, poorly written, and full of mistakes--and it's expensive. The fact that the authors foist that piece of junk on unsuspecting newbies is a crime. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Aug 10 08:26:20 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 10 Aug 2007 14:26:20 +0200 Subject: Stackless Integration In-Reply-To: <46bc375b$0$406$426a34cc@news.free.fr> References: <mailman.1786.1186660119.22759.python-list@python.org> <46bb1df0$0$403$426a74cc@news.free.fr> <mailman.1797.1186674791.22759.python-list@python.org> <46bc375b$0$406$426a34cc@news.free.fr> Message-ID: <46bc595f$0$439$426a74cc@news.free.fr> Bruno Desthuilliers a ?crit : > Steve Holden a ?crit : (snip) >> Twisted is a complex set of packages > > Sure. Now I may be dumb, but I thought it was about stackless, not about > Twisted... Sorry, didn't saw your other post. From comp.ogz at gmail.com Thu Aug 16 04:53:12 2007 From: comp.ogz at gmail.com (=?utf-8?q?O=C4=9Fuz_Yar=C4=B1mtepe?=) Date: Thu, 16 Aug 2007 11:53:12 +0300 Subject: python socket usage In-Reply-To: <46C408D6.8000907@islandtraining.com> References: <mailman.2046.1187250159.22759.python-list@python.org> <1187250839.541105.60900@r29g2000hsg.googlegroups.com> <46C408D6.8000907@islandtraining.com> Message-ID: <200708161153.12294.comp.ogz@gmail.com> On Thursday 16 August 2007 11:20:38 Gary Herron wrote: > If you really want to send any Python object through a socket, look up > the Pickle and cPickle modules. ?These will marshal (as it's called) any > Python object of any type and complexity into a byte string which can be > sent across a socket. ?On the receiving end of the socket, the byte > string can be turned back into an equivalent Python object. > > Gary Herron As i read pickle module is Python-spesific. I need to talk with a Java application and get the infortion that it will send. What i do right now is listening a socket and reding the string that is sent by the java application. So the java application is sending a string and i am reading and parsing it and getting the related infortion i need. A more professional way may be the reading the object itself. Is it possible to get the array for ex. object that is sent from the Java application with sockets? -- O?uz Yar?mtepe http://www.yarimtepe.com/en From jeff.fw at gmail.com Wed Aug 29 13:31:10 2007 From: jeff.fw at gmail.com (Jeff) Date: Wed, 29 Aug 2007 17:31:10 -0000 Subject: Creating a multi-tier client/server application In-Reply-To: <46d59fa8$0$278$426a74cc@news.free.fr> References: <1188360460.838635.186930@w3g2000hsg.googlegroups.com> <7xbqcqhqbw.fsf@ruckus.brouhaha.com> <46d54ed8$0$429$426a34cc@news.free.fr> <1188393925.007952.313110@r29g2000hsg.googlegroups.com> <46d57888$0$295$426a74cc@news.free.fr> <1188398008.538820.21960@d55g2000hsg.googlegroups.com> <46d59fa8$0$278$426a74cc@news.free.fr> Message-ID: <1188408670.480447.42470@k79g2000hse.googlegroups.com> Goldfish--thanks, I'll check it out. > > That, or something similar, may be what I do. It would mean, however, > > developing my own method for transferring objects across the network, > > Why transfering "objects" ? You only need to transfer data. I suppose I don't need to transfer objects, it just seems like it would make it far easier (certainly less repetition of code) to program the client-side app. From uymqlp502 at sneakemail.com Fri Aug 31 14:01:10 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Fri, 31 Aug 2007 11:01:10 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188552665.363115.175310@x35g2000prf.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> <1188547369.428712.194430@x35g2000prf.googlegroups.com> <1188552665.363115.175310@x35g2000prf.googlegroups.com> Message-ID: <1188583270.535882.129540@l22g2000prc.googlegroups.com> Michele Simionato wrote: > I am curious. Why do you think I attacked you? The conversion went as > follows: I don't think you attacked me. I was referring to another person, who apparently came to your defense and *did* attack me. For the record, I apologize for saying that you don't seem to know what DbC is. I shouldn't have made it personal. I should have just made the points I made and let them stand on their own. Having said that, I think that some of the statements you made were clearly excessive. Unit testing is a thousand times better than DbC? How could that possibly be? As I tried to explain, DbC can be *used* for unit testing and *also* for integrated system testing. > I would not call that an attack. If you want to see an attack, wait > for > Alex replying to you observations about the low quality of code at > Google! ;) I don't know much about Google code, but I know that the line breaking logic (or lack thereof) on Google Groups is a constant annoyance to me. But maybe I just haven't figured out how to use it yet. From kyosohma at gmail.com Mon Aug 6 11:20:35 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 06 Aug 2007 15:20:35 -0000 Subject: Tkinter or wxpython? In-Reply-To: <mailman.1677.1186412323.22759.python-list@python.org> References: <op.tv98rva4wepdt4@ericb.pragmadev> <mailman.1550.1186099225.22759.python-list@python.org> <1186410331.905174.21370@q3g2000prf.googlegroups.com> <7xps204tin.fsf@ruckus.brouhaha.com> <mailman.1677.1186412323.22759.python-list@python.org> Message-ID: <1186413635.676709.160020@j4g2000prf.googlegroups.com> On Aug 6, 9:58 am, "Chris Mellon" <arka... at gmail.com> wrote: > On 06 Aug 2007 07:39:12 -0700, Paul Rubin > > > > <"http://phr.cx"@nospam.invalid> wrote: > > kyoso... at gmail.com writes: > > > I've read that Tkinter doesn't scale well if you're writing complex > > > GUIs. I haven't been able to test this hypothesis though. However, > > > since I had to rewrite VBA apps into Python, to get the right "look > > > and feel" I needed the widgets that wxPython provided. Since I started > > > out with C++, I find wxPython better than Tkinter, but it's all pretty > > > subjective. Try them both! > > > Tkinteger (dang, I always end up typing it that way, I won't even > > bother fixing the error) is easy to use for simple gui's, and it's > > part of the standard python distro which for me is a big advantage (no > > extra crap to download). However, the widget set is rather ugly and > > doesn't blend in well with anyone's native widgets; the widget > > selection itself is rather narrow, and I think kyosohma may be right > > that it doesn't scale well to complex gui's. I've looked at the code > > for IDLE's gui and it's terrifying. > > > At this point I think nobody should write desktop gui apps without a > > good reason. There is a fairly flexible and easy to program gui > > already running on almost every desktop, namely the web browser. > > Before you write a gui using some client side toolkit, ask yourself > > whether you can instead embed a web server in your application and > > write an HTML gui. That approach is not always the answer, but it has > > considerable advantages when you can do it that way. > > Some disadvantages of the web based platform: > > No native look and feel - constrained by the browser. > No control over browser UI idioms. I had to write this post twice > because the text control lost focus and I hit backspace, going back in > the history and losing my work. > No native integration - no "open file", no "browse the filesystem", no > rich drag and drop, no copy/paste. > No or poor dialogs. Poor multiple window support. > More platforms to develop on and test with. > Limited to CSS box model for layout. > > You can mitigate some of these constraints if you *require* the local > web browser technique, rather than supporting local or remote access. > You can mitigate more if you write your own browser host (along the > lines of the dashboard in OS X), but then you get to write 3 > applications instead of one. > > The web is a terrible application platform. There is not a single web > application in existence which has even half the UI functionality of a > rich client application. There are some (even many) applications for > which the benefit of global access and easy deployment makes up for > the lack in functionality, but statements like "At this point I think > nobody should write desktop gui apps without a good reason" are simply > ludicrously misguided. If you could use Python's antiquated Grail web browser and write plugin applications, then that would be awesome! There are trade offs with anything though. Mike From jakub.stolarski at gmail.com Mon Aug 20 02:25:09 2007 From: jakub.stolarski at gmail.com (Jakub Stolarski) Date: Mon, 20 Aug 2007 06:25:09 -0000 Subject: yet another indentation proposal In-Reply-To: <fEZxi.8855$9W6.6492@fe103.usenetserver.com> References: <fEZxi.8855$9W6.6492@fe103.usenetserver.com> Message-ID: <1187591109.948771.144690@g4g2000hsf.googlegroups.com> Why not just use comments and some filter. Just write # _{ at the beginning and # _} at the end. Then filter just before runing indenting with those control sequences? Then there's no need to change interpreter. From greg at cosc.canterbury.ac.nz Fri Aug 17 00:22:23 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 17 Aug 2007 16:22:23 +1200 Subject: about negative polar plots In-Reply-To: <1187076466.955318.249250@57g2000hsv.googlegroups.com> References: <1187076466.955318.249250@57g2000hsv.googlegroups.com> Message-ID: <5ikmb7F3nbe6vU1@mid.individual.net> yadin wrote: > hi am doing a polar plot of the radiation pattern of an antenna. > the polar plots represents the value of the power in dB's and the dB > go from -40dB to 0dB Add 40 so that the range goes from 0 to 40, then plot that to an appropriate scale. -- Greg From mensanator at aol.com Sat Aug 4 21:50:38 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sat, 04 Aug 2007 18:50:38 -0700 Subject: Formatting Results so that They Can be Nicely Imported into a Spreadsheet. In-Reply-To: <1186270555.514649.311280@d30g2000prg.googlegroups.com> References: <1186270555.514649.311280@d30g2000prg.googlegroups.com> Message-ID: <1186278638.931477.39760@z24g2000prh.googlegroups.com> On Aug 4, 6:35?pm, SMERSH009 <SMERSH0... at gmail.com> wrote: > Hi All. > Let's say I have some badly formatted text called doc: > > doc= > """ > friendid > Female > > 23 years old > > Los Gatos > > United States > friendid > Male > > 24 years old > > San Francisco, California > > United States > """ > > How would I get these results to be displayed in a format similar to: > friendid;Female;23 years old;Los Gatos;United States > friendid;Male; 24 years old;San Francisco, California;United States > > The latter is a lot easier to organize and can be quickly imported > into Excel's column format. > > Thanks Much, > Sam d = doc.split('\n') f = [i.split() for i in d if i] g = [' '.join(i) for i in f] rec = [] temprec = [] for i in g: if i: if i == 'friendid': rec.append(temprec) temprec = [i] else: temprec.append(i) rec.append(temprec) output = [';'.join(i) for i in rec if i] for i in output: print i ## friendid;Female;23 years old;Los Gatos;United States ## friendid;Male;24 years old;San Francisco, California;United States From ladynikon at gmail.com Fri Aug 3 12:22:42 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Fri, 3 Aug 2007 12:22:42 -0400 Subject: Eclipse and Python Message-ID: <59f9c5160708030922m2f4f5179nf384135214246d14@mail.gmail.com> Does anyone have any suggested websites for learning Eclipse the python way? thanks, Danyelle From strombrg at gmail.com Sat Aug 18 20:55:33 2007 From: strombrg at gmail.com (Dan Stromberg) Date: Sun, 19 Aug 2007 00:55:33 GMT Subject: Fatest standard way to sum bytes (and their squares)? References: <NPmdnVwqHa74TyPbnZ2dnUVZ_uKpnZ2d@speakeasy.net> Message-ID: <9yMxi.1035$vU4.225@nlpi068.nbdc.sbc.com> On Sun, 12 Aug 2007 02:26:59 -0700, Erik Max Francis wrote: > For a file hashing system (finding similar files, rather than identical > ones), I need to be able to efficiently and quickly sum the ordinals of > the bytes of a file and their squares. Because of the nature of the > application, it's a requirement that I do it in Python, or only with > standard library modules (if such facilities exist) that might assist. > > So far the fastest way I've found is using the `sum` builtin and > generators:: > > ordinalSum = sum(ord(x) for x in data) > ordinalSumSquared = sum(ord(x)**2 for x in data) > > This is about twice as fast as an explicit loop, but since it's going to > be processing massive amounts of data, the faster the better. Are there > any tricks I'm not thinking of, or perhaps helper functions in other > modules that I'm not thinking of? > I see a lot of messages attacking the CPU optimization, but what about the I/O optimization - which admittedly, the question seems to sidestep. You might experiment with using mmap() instead of read()... If it helps, it may help big, because the I/O time is likely to dominate the CPU time. From http Fri Aug 3 21:45:21 2007 From: http (Paul Rubin) Date: 03 Aug 2007 18:45:21 -0700 Subject: How to pass a reference to the current module References: <f90gsg$ek4$1@zinnia.noc.ucla.edu> <pan.2007.08.04.01.46.50.985228@REMOVE.THIS.cybersource.com.au> Message-ID: <7xy7gs9ioe.fsf@ruckus.brouhaha.com> Steven D'Aprano <steve at REMOVE.THIS.cybersource.com.au> writes: > namespace = module.__dict__ > return namespace[name] Am I missing something? It's likely that I just don't understand the problem, but I don't understand these dictionary extractions for what I thought would be an attribute lookup: Python 2.4.4 (#1, Oct 23 2006, 13:58:00) >>> import math >>> parrot = getattr(math, 'sqrt') >>> print parrot(3) 1.73205080757 >>> That just seems like a cleaner way to access stuff in a module, using the published interface instead of an implementation detail. From tzuchien.chiu at gmail.com Wed Aug 22 16:27:01 2007 From: tzuchien.chiu at gmail.com (tzuchien.chiu) Date: Wed, 22 Aug 2007 20:27:01 -0000 Subject: Design philosophy of HTTPServer and BaseHTTPRequestHandler In-Reply-To: <1187790329.575480.14070@i38g2000prf.googlegroups.com> References: <1187776216.269456.310230@q4g2000prc.googlegroups.com> <1187790329.575480.14070@i38g2000prf.googlegroups.com> Message-ID: <1187814421.263942.202220@x35g2000prf.googlegroups.com> On 22 ago, 14:45, Gabriel Genellina <gagsl-... at yahoo.com.ar> wrote: > The server is permanent; request handler instances are created and > destroyed as HTTP requests arrive and are processed. > You should store any permanent info in the server; your > "BaseHTTPRequestHandler-derived class" can reference the server using > its "server" attribute. I found the server attribute in the source code (/Lib), but it is not documented in Python Library Reference 18.19. I wonder that if I can rely on this "undocumented" attribute? From python at jayloden.com Sat Aug 4 18:14:25 2007 From: python at jayloden.com (Jay Loden) Date: Sat, 04 Aug 2007 18:14:25 -0400 Subject: Client-side HTML form processing with Python? In-Reply-To: <1186263839.778333.143200@d30g2000prg.googlegroups.com> References: <1186263839.778333.143200@d30g2000prg.googlegroups.com> Message-ID: <46B4FA41.206@jayloden.com> goldtech wrote: > I want to have an HTML form from a local local html file write a text > field's data to a local text file. > > I have no client or server side tools like PHP, JAVA. I don't know > JavaScript. I can not add anything to the workstation I am using. It's > going to have to be a client-side solution - there's no CGI on the > server, no PHP. > > It's XP with MS-Office, so I guess I have the usual active-x, and I > have Python 2.1. > > Is there a way? Thanks, > Lee G. Even if serving a local page, some kind of web server would be necessary in order to process the request from the submitted form, and execute the Python CGI script. I know you said you can't add anything to the workstation, but you must be able to at least add Python scripts and html files, so perhaps you can get away with adding a self-contained web server? I recommend TinyWeb ( http://www.ritlabs.com/en/products/tinyweb/ ). It's only 53k and supports all the basic webserver functions, including CGI. You can drop TinyWeb in your working directory, start it up with a simple shortcut or batch file, and then have your local HTML form submit to a CGI script processed through TinyWeb. I've used it for a very similar project before, it's so tiny and lightweight that it really doesn't get in the way, and the CGI portion works just fine with Python. If you really can't add anything at all (not even Python packages??), the only other way to do this that I can come up with would be to implement your own simplistic web server in Python that receives the incoming request. Twisted has a CGI-enabled web server in it, and CGIHTTPServer also offers one. However, CGIHTTPServer uses os.fork and is not available on Windows: http://www.python.org/doc/1.5.2p2/lib/module-CGIHTTPServer.html - but you could possibly use it as a starting point. Other than the above the only suggestion I can give would be to search for another way to approach your problem. For instance, using an hta http://msdn2.microsoft.com/en-us/library/ms536496.aspx or using a Tkinter/wxWidgets GUI instead of an html form. -Jay From inq1ltd at inqvista.com Sat Aug 4 13:51:10 2007 From: inq1ltd at inqvista.com (jim-on-linux) Date: Sat, 04 Aug 2007 13:51:10 -0400 Subject: sqlite3 create table col width? In-Reply-To: <1186245190.970687.307920@k79g2000hse.googlegroups.com> References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> <1186240708.874804.271030@b79g2000hse.googlegroups.com> <1186245190.970687.307920@k79g2000hse.googlegroups.com> Message-ID: <200708041351.10507.inq1ltd@inqvista.com> PY help, Using sqlite3 v3.1.3 When I create a table collumn using; newcollum VARCHAR(35), I get a default of 10 spaces. No matter what I set the size to I get 10 spqces, even using varchar(0) defaults to 10 spaces. I would appreciae the help if someone could tell me what I'm missing, I want to varry the column sizes. jim-on-linux From yan.python at gmail.com Tue Aug 14 07:22:28 2007 From: yan.python at gmail.com (yan.python at gmail.com) Date: Tue, 14 Aug 2007 11:22:28 -0000 Subject: how to move cursor in Interactive Interpreter In-Reply-To: <f9rivq$sfc$00$1@news.t-online.com> References: <1187072484.626674.157200@x40g2000prg.googlegroups.com> <f9rivq$sfc$00$1@news.t-online.com> Message-ID: <1187090548.811916.124450@x40g2000prg.googlegroups.com> On 8 14 , 2 44 , Peter Otten <__pete... at web.de> wrote: > yan.pyt... at gmail.com wrote: > > i have a question. > > when i run Interactive Interpreter in linux command promt,how can i > > move the cursor. > > for example,when i enter a string,i often enter the quotation mark "" > > first,and the move the cursor inside the mark to enter the string,in > > windows,it is ok.but when i do that in linux,pressing the "left" key > > will just print "^[[D" in the screen ,but not what i want. > > so , how can i move the cursor Interactive Interpreter in linux? > > i've googled and find nothing useful.who i tell me what to do? > > Python uses GNU readline for cursor movements. The Python version that ships > with your distribution should work out of the box. If you compile Python > yourself make sure that the development package (not just the binary) is > installed. For Suse this is readline-devel. > > Peter thanks for your reply I thought maybe i just didn't install readline correctly,so i deleted python and tried to re-compile the source code(I downloaded the .bz2 version).This time ,I found in the "./Modules/Setup" the description for "readline": # GNU readline. Unlike previous Python incarnations, GNU readline is # now incorporated in an optional module, configured in the Setup file # instead of by a configure script switch. You may have to insert a # -L option pointing to the directory where libreadline.* lives, # and you may have to change -ltermcap to -ltermlib or perhaps remove # it, depending on your system -- see the GNU readline instructions. # It's okay for this to be a shared library, too. #readline readline.c -lreadline -ltermcap dont know exactly what to do,I just delete the "#" mark in the line "#readline readline.c -lreadline -ltermcap " , then tried to "configure","make",but errors of readline occor here. what am i supposed to do to install the module GNU readline correctly then? thanks by the way,my linux is Mandriva 10 From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Aug 2 06:23:54 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 02 Aug 2007 12:23:54 +0200 Subject: Pythonic way for missing dict keys In-Reply-To: <mailman.1493.1186042809.22759.python-list@python.org> References: <mailman.938.1184958565.22759.python-list@python.org> <pan.2007.07.21.00.20.54.768439@REMOVE.THIS.cybersource.com.au> <mailman.954.1184989959.22759.python-list@python.org> <Xns99748CC2DB4AAduncanbooth@127.0.0.1> <1185041243.323915.161230@x40g2000prg.googlegroups.com> <mailman.984.1185101740.22759.python-list@python.org> <87lkd0eprj.fsf@pobox.com> <mailman.1279.1185623588.22759.python-list@python.org> <pan.2007.07.29.04.10.19.329342@REMOVE.THIS.cybersource.com.au> <46b0ed0b$0$2257$426a74cc@news.free.fr> <mailman.1493.1186042809.22759.python-list@python.org> Message-ID: <46b1b0ba$0$25340$426a74cc@news.free.fr> Alex Popescu a ?crit : > Bruno Desthuilliers <bdesth.quelquechose at free.quelquepart.fr> wrote in > news:46b0ed0b$0$2257$426a74cc at news.free.fr: (snip) >> if hasattr(obj, '__call__'): >> # it's a callable >> >> but I don't find it so Pythonic to have to check for a __magic__ >> method. > > It looks like Python devs have decided it is Pythonic, because it is > already in the PEP. I do know, and I disagree with this decision. FWIW, repr(obj) is mostly syntactic sugar for obj.__repr__(), getattr(obj, name) for obj.__getattr__(name), type(obj) for obj.__class__ etc... IOW, we do have a lot of builtin functions that mostly encapsulate calls to __magic__ methods, and I definitively don't understand why this specific one (=> callable(obj)) should disappear. I usually have lot of respect for Guido's talent as a language designer (obviously since Python is still MFL), but I have to say I find this particular decision just plain stupid. Sorry. From iclark at mail.ewu.edu Wed Aug 15 18:03:11 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Wed, 15 Aug 2007 15:03:11 -0700 Subject: All names in the current module In-Reply-To: <f9vij0$1ln$1@sea.gmane.org> References: <87d4xowymq.fsf@wilson.homeunix.com> <f9vij0$1ln$1@sea.gmane.org> Message-ID: <f9vt6v$6aq$1@sea.gmane.org> Ian Clark wrote: > Torsten Bronger wrote: >> Hall?chen! >> >> How can I get a list with all classes defined in the current module? >> Thank you! >> >> Tsch?, >> Torsten. >> > > Assuming you want to see all classes in the re module: > > >>> import re > >>> help(re) #best way > >>> > >>> def isclass(cls): > ... try: > ... return issubclass(cls, cls) > ... except TypeError: > ... pass > ... return False > ... > >>> [cls for cls in dir(re) if isclass(getattr(re, cls))] > ['Scanner', '_pattern_type', 'error'] > > Ian > I love this list, I learn something new everyday. Didn't know about inspect.isclass(). Ignore this post and look at Lawrence's. Ian From FJIFALSDGVAF at spammotel.com Fri Aug 17 14:12:30 2007 From: FJIFALSDGVAF at spammotel.com (Thomas Kellerer) Date: Fri, 17 Aug 2007 20:12:30 +0200 Subject: best GUI library for vector drawing program In-Reply-To: <1187357244.883516.79840@j4g2000prf.googlegroups.com> References: <1187357244.883516.79840@j4g2000prf.googlegroups.com> Message-ID: <5im6oeF3q5onpU1@mid.individual.net> chewie54 wrote on 17.08.2007 15:27: > Hello, > > What would be the best cross-platform GUI library to use for a vector > based CAD program ( something like Visio on Windows ) WxWidgets, > Tk, PyQt, Java Swing, Java SWT,???? I need the capibility to > draw and edit in a window that looks like a page of paper so WYSIWYG > is very important, and I need to save the drawings in vector based > file formats like PS, EPS, SVG, as well as image formats like jpg, > png, and gif. Also, the images need to be high resolution so that > they can be pasted into various other programs in Windows OS, and > Linux OS, and the Mac OS. The NetBeans Platform offers a nice module for this. NetBeans itself uses it for UML, BPEL and ERD modelling and other features (such as the visual XSD editor) http://platform.netbeans.org/ http://graph.netbeans.org/ Thomas From istvan.albert at gmail.com Wed Aug 8 12:50:40 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Wed, 08 Aug 2007 16:50:40 -0000 Subject: Misleading wikipedia article on Python 3? In-Reply-To: <1186589320.335950.142880@b79g2000hse.googlegroups.com> References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <mailman.1660.1186380664.22759.python-list@python.org> <7xzm15q8fy.fsf@ruckus.brouhaha.com> <1186583168.447608.114040@d55g2000hsg.googlegroups.com> <1186589320.335950.142880@b79g2000hse.googlegroups.com> Message-ID: <1186591840.183931.21080@19g2000hsx.googlegroups.com> On Aug 8, 12:08 pm, Paul Boddie <p... at boddie.org.uk> wrote: > However, for every enthusiast of one approach, there > will always be an enthusiast for another (see point #6): True. For example I for one also like the way the current print adds a newline, the vast majority of the time that is exactly what I want. I don't know if this will be kept when print becomes a function (might be that some default parameters make it work the same way) Which reminds me of an experience I had when I originally learned how to program in Pascal, then moved on to C. At first it felt wrong that I had to include the "\n" to print a new line at the end, seemed unreadable (Pascal had separate functions: write and a writeln for it). Today I'd consider it appallingly bad design to have separate functions for such a small difference. i. From orsenthil at users.sourceforge.net Sat Aug 18 07:29:13 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Sat, 18 Aug 2007 16:59:13 +0530 Subject: passing arguments with ampersands In-Reply-To: <f6be0af40708180354u719f5c71p2be27e0ee8317f9b@mail.gmail.com> References: <f6be0af40708180354u719f5c71p2be27e0ee8317f9b@mail.gmail.com> Message-ID: <20070818112913.GA3632@gmail.com> > Quote:D:\ftp\Music\Mixes & Compilations\Above & Beyond - Essential > Mix\001_Essential_Mix_2004-06-06_-_Above_and_Beyond.txt > when i put 'print sys.argv[1:]' at the very beginning of the script, all i > get is this: > > Quote:['D:\\ftp\\Music\\Mixes'] > Can you share the portion of the code? Are you quoting the argument that you are passing? for e.g: #cat 1.py import sys print sys.argv[1] #python 1.py "I am able to print the spaces and & characters" I am able to print the spaces and & characters -- O.R.Senthil Kumaran http://uthcode.sarovar.org From malen at og-entertainment.com Mon Aug 20 09:53:58 2007 From: malen at og-entertainment.com (Niklas Ottosson) Date: Mon, 20 Aug 2007 15:53:58 +0200 (CEST) Subject: Mouse control with ctypes in OS X Message-ID: <20070820135358.0B3052303D@atmail.b-one.net> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070820/f634bc79/attachment.html> From mail at timgolden.me.uk Fri Aug 31 05:46:21 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 31 Aug 2007 10:46:21 +0100 Subject: list index() In-Reply-To: <fOadnfwlCJbQfErbnZ2dnUVZ_jCdnZ2d@speakeasy.net> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188497498.3468.60.camel@dot.uniqsys.com> <mailman.188.1188546300.28954.python-list@python.org> <0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net> <1188551958.728836.137370@x35g2000prf.googlegroups.com> <fOadnfwlCJbQfErbnZ2dnUVZ_jCdnZ2d@speakeasy.net> Message-ID: <46D7E36D.4000301@timgolden.me.uk> Erik Max Francis wrote: > Paddy wrote: > >> I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll >> and role similarly. >> >> My accent is probably from the East Midlands of the UK, but is not >> pronounced. > > _Troll_ and _frolic_ aren't pronounced with the same "o" sound in any > accent I've ever heard of. Which you pronounce _boat_ and _bot_ the > same way, too? [Amusingly contemplating a trolling war about the pronunciation of "troll"] Well they sound the same in my more-or-less South London accent. I can't write those funny phonetic symbols (and I hate to imagine the Unicode encoding hoops I'd have to jump through to make them readable anyway) but both "o"s sound short to me. Like "bot" rather than "boat" using your example. TJG From davmillar at gmail.com Sat Aug 11 11:07:25 2007 From: davmillar at gmail.com (Dave) Date: Sat, 11 Aug 2007 15:07:25 -0000 Subject: Public Telnet Server? Message-ID: <1186844845.304731.18300@x40g2000prg.googlegroups.com> Hi there. I'm a beginner at Python and I'm writing my first Python script. It's a text adventure about coffee and mixing drinks and being crazy and such. I keep updating it and want my friends to beta test it for me, but some of them don't have the right version of Python or don't want to get Python at all. Is there an easy way I can set up a public telnet server so they can just telnet the server and play it? If anyone could give me some options and/or advice, I'd really appreciate it! Dave From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Aug 9 09:42:26 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 09 Aug 2007 15:42:26 +0200 Subject: Help with Dictionaries and Classes requested please. In-Reply-To: <slrnfbm34n.n0.horpner@FIAD06.norwich.edu> References: <46bacae3$0$89254$7b0f0fd3@mistral.news.newnet.co.uk> <46bacf1b$0$54289$7b0f0fd3@mistral.news.newnet.co.uk> <46baf183$0$433$426a74cc@news.free.fr> <46baf384$0$11943$7b0f0fd3@mistral.news.newnet.co.uk> <46bb00d4$0$11943$7b0f0fd3@mistral.news.newnet.co.uk> <slrnfbm34n.n0.horpner@FIAD06.norwich.edu> Message-ID: <46bb19bb$0$399$426a74cc@news.free.fr> Neil Cerutti a ?crit : > On 2007-08-09, special_dragonfly <Dominic at PLEASEASK.co.uk> wrote: >> Is there anyway for python to consider the values within a >> string when entering the data into a dictionary. I know that >> isn't very clear so here's an example: >> >> class MyClass(object): >> def __init__(self,name="",age=""): >> self.name=name >> self.age=age >> >> data="Gary,50" >> d={0:[MyClass(data)]} >> data="Adam,25" >> d[0].append(MyClass(data)) >> >> The data is coming from a text file working on a line by line >> basis. I've just tried and I'm just getting the full string in >> the first field. That seems logical, now I don't want it to >> though! > > That's what happens if you use 0 for the key every time. ;) Hmmm... Neil, I may be wrong but I think you didn't get the point here. As I understand it, Dominic's problem is that it gets strings like "Gary,50" and would like to call MyClass initializer this way : MyClass("Gary", "50") From http Mon Aug 6 15:10:44 2007 From: http (Paul Rubin) Date: 06 Aug 2007 12:10:44 -0700 Subject: Tkinter or wxpython? References: <op.tv98rva4wepdt4@ericb.pragmadev> <mailman.1550.1186099225.22759.python-list@python.org> <1186410331.905174.21370@q3g2000prf.googlegroups.com> <7xps204tin.fsf@ruckus.brouhaha.com> <mailman.1677.1186412323.22759.python-list@python.org> <7xlkcopu4r.fsf@ruckus.brouhaha.com> <mailman.1680.1186416061.22759.python-list@python.org> <7x3aywr4tc.fsf@ruckus.brouhaha.com> <mailman.1684.1186422197.22759.python-list@python.org> Message-ID: <7x8x8oqy17.fsf@ruckus.brouhaha.com> "Chris Mellon" <arkanes at gmail.com> writes: > Define "functionality". From the rest of your posts, that seems to be > limited to "press buttons" and "type small amounts of non-formatted > text" on the interaction side and "display small amounts of simply > formatted text" on the output side. OK, I can live with that, if you include displaying images on the output side. > I'm not denying that you can get > by with this functionality in a large number of cases, Precisely my point. > but it's certainly not optimal in general. > If it were, we'd all still be using VT100 terminals. Nah, HTML gui's are much easier to use than pure text interfaces, because of the visual gui elements, pointing with the mouse, simple control over fonts and color, etc. > > > ...Gmail uses ajax instead of a page load > What you're calling "slickness" is what other people call "usable". I notice google search doesn't use ajax (or didn't til recently) and has satisfied an awful lot of users with simple html. > My out of the box firefox install simply denies the operation and > raises a javascript error. Hmm, the user might have to change a setting in about:config but that's certainly easier than installing a desktop application. I haven't done this with firefox. In Communicator you'd just call netscape.security.privilegemanager and ask for the permission that you needed. > > > How about something as simple as context menus? > > Unnecessary slickness for many apps. I've never needed it. > How have you decided that you've never needed it? Have you ever worked > with a UI designer or workflow expert? Or have you just never bothered > to implement it and you never heard anything from your users? How > closely have you worked with the users of your applications? If the app has enough slickness requirements that the customer is willing to pay for the attention of UI designers or workflow experts, maybe it also needs context menus, I don't know. Generally I'd say there are several levels: 1. In-house app that will have 1 to 10 users who run it now and then. Every minute of unnecessary development is wasting their money, so they want the quickest and cheapest possible solution. Web app is very often an easier way to do this than desktop gui app, even if the functionality is bare bones. I've done several of these, either as desktop apps or web apps, generally working closely with the user, and nobody has said anything about context menus. I think this case is very common. In some instances the sole user is me, so nobody else has to be satisfied. 2. Wide-use app that will have 1000's of users, including non-in-house users who tend to distrust desktop installs. Web app is superior for deployment reasons even if you have to give up some ui niceties. This is what I do most of the time as a web developer. I tend to write simple html to implement functionality, then let a real designer spiff it up to look slick on multiple browsers while I concentrate on the backend programming. 3. In-house app somewhere between 1 and 2, i.e. maybe there are dozens or hundreds of users who will interact with the program all day long. Usability becomes more important, so this can go either way. Maybe this is where you want to UI experts involved. It sounds like your CRUD apps are often in this category. Not everybody's are. Mine haven't been so far. If I were in this situation I'd consider both the web and desktop approaches and could go either way depending on the specific requirements. 4. Shrink-wrap consumer app, zillions of units to ship, pizzazz sells boxes, slickness is king. You need a whiz-bang desktop gui done by real artist/designers. I'm just a coder, so my approach would be write a slapdash tkinter or web gui to figure out the necessary functionality in conjunction with UI specialists, then write a spec based on the prototype and turn it over to the artistic gurus, with me doing the backend stuff in cooperation with them. I haven't so far done anything like this even though I worked at a game company for a while. I think most of us can code our way through life without ever doing it. > As phishing attacks become more common, browsing are restricting the > ability to remove or modify chrome. I'm using firefox 2 and sites pop chromeless windows all the time, so I'm not sure what browsers you're referring to. > It depends on your target audience and deployment arena. The context > is cross platform applications, I don't see anything about cross platform in the OP's original post. If cross platform were important I'd start asking whether the app needed to be usable from mobile phones. If yes, that weighs heavily for browsers. > You simply can't do much of anything beyond display text and basic > crud with straightforward HTML without stying. If that is the sole > limit of your UI needs, then bully for you but that's hardly the > common case and I'd venture that you don't have the experience to > support the rather sweeping claim you made. I think it's a very common case, which is why so much stuff is being done on the web instead of the desktop. > That's simply not true, and I don't think you can objectively justify > it. Besides, you specifically claimed HTML dialogs as being a > replacement for "real" ones, and that can't be done using trivial > interfaces. It requires DHTML, sometimes ajax, and/or browser support. I guess I'm not sure what you mean about dialogs. I would consider some html input fields with a submit button to be a dialog. Sometimes a little client side JS can make things a bit nicer. I guess that technically counts as DHTML but if you keep it simple, you can avoid most cross-browser issues. > I would challenge the assumption that, starting from zero, it is less > complicated to write a web application, much less a "pretend" web app > using a local web server, than a desktop application using Tkinter > (ick) or wxPython or pyQt. I would also challenge the assumption that > 'a lot of the time' you can get away with a simple HTML interface, at > least by my personal definition of 'get away with'. I've worked a lot > with data entry people, where the actual requirements in terms of > slickness and flash are quite small. But "basic html" simply does not > fit the bill. There is a real cost in terms of how fast and how > accurately they can enter data in this environment. Well, not everybody needs to enter data all day long. If they need to enter seven numbers into a form once a week and it takes them 15 seconds with a special desktop app and 17 seconds with a web app and there are only three users, go for the web app if it saves you any development or support time. > Exactly how much time do you think using an HTML interface with an > embedded server would have saved you, especially considering the > careful care you have to take with access to the serial port? I am sure it would have saved at least half the development time of that app. But it's not a fair comparison since that was a 16 bit MS-DOS app written in C. > > I'm not saying file browsing is never needed, just that from > > experimental observation, it's quite often not needed. > > Plural of anecdote and all that. Make a survey of every application > that you interact with and see how many of them need to interact with > arbitrary files from the filesystem. OK, looking at what's on my screen during most of my workday: 1) one or more browser windows. No file system interaction. 2) Several terminal windows, no file interaction from the terminal itself, but I run command line apps (mostly emacs) in the terminals and those sometimes use the file system. 3) Text chat client, I think it can send and receive files but I never use that feature. I would not run this particular app if it were up to me but management chose it. But it is a sort of legitimate use of a desktop gui. 4) Email client again chosen by management. This one does use the file system to send and receive attachments, but that's not fundamentally required since webmail clients are very popular and effective and can upload and download. At home I read email with emacs. The only other desktop gui program I can think of that I use with any regularity is a PDF viewer occasionally launched by the browser. More typically this is done with a browser plugin rather than a separate app, but my desktop is set up to launch xpdf separately. Under Windows I sometimes used IDLE for Python development but under Linux I run python inside emacs. > CRUD with javascript is something I actually have a lot of experience > with. Deficiencies in the data entry UI have real consequences because > you get invalid data and slow data entry speeds. The auto-completing > combo-box, for example, is simply impossible in a browser without > quite complicated (and slow) DHTML and is a huge boon for data entry. I'm not sure what that combo box is. I've probably seen one but I'm just not sure exactly what you're referring to. Maybe it's important if you write heavily used CRUD apps. Not everybody who needs a gui writes those apps. > I'm not trying to claim that there are no benefits to web > applications. But I often see people touting the web as a *superior > application platform*, which is simply false, and as innately simpler > to develop for, which is also false. I think it is simpler until you're trying to do stuff that's both slick and multi-platform, but not everyone cares about being both of those things simultaneously. I generally don't care about slickness and accomplish multi-platform by writing dirt-simple html. From donn at u.washington.edu Wed Aug 15 15:51:26 2007 From: donn at u.washington.edu (Donn Cave) Date: Wed, 15 Aug 2007 12:51:26 -0700 Subject: Who told str() to round my int()'s!!! References: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> <slrnfc5t7i.vtl.hat@se-162.se.wtb.tue.nl> Message-ID: <donn-345153.12512615082007@gnus01.u.washington.edu> In article <slrnfc5t7i.vtl.hat at se-162.se.wtb.tue.nl>, "A.T.Hofkamp" <hat at se-162.se.wtb.tue.nl> wrote: > On 2007-08-11, Adam W. <AWasilenko at gmail.com> wrote: > > After a fair amount of troubleshooting of why my lists were coming > > back a handful of digits short, and the last digit rounded off, I > > determined the str() function was to blame: > > > >>>> foonum > > 0.0071299720384678782 > >>>> str(foonum) > > '0.00712997203847' > >>>> > > > > Why in the world does str() have any business rounding my numbers, and > > how do I get around this? > > You have got a few good reactions already. What is not mentioned yet however > is > the difference between str() and repr(). If only it could have stayed that way. > > Python has two ways to stringify an object: > > str() is intended to deliver a 'human-readable' representation of its > argument, > and typically, humans think a few digits of a float is enough. This is precisely the problem with this notion though: you don't have a good way to predict what will be "readable" (or worse, "friendly" as people used to say in this context) to a human. Adam W reads the output of str() and it isn't what he expected, though usually it's the other way around where people complain about repr(). More generally, there just isn't any humanity in the way we render objects as text strings, a priori. If there is any such thing, it depends completely on the context. To invite the author of an object to devise a text rendition that will be humane (friendly, readable or whatever) is to waste his or her time. There are better ways to conceive of this str/repr distinction, and they've been discussed to death. python.org documentation will probably never be fixed. Donn Cave, donn at u.washington.edu From kyosohma at gmail.com Tue Aug 7 14:30:13 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 07 Aug 2007 11:30:13 -0700 Subject: Dealing with multiple excel sheets In-Reply-To: <1186509914.117596.249330@j4g2000prf.googlegroups.com> References: <1186509914.117596.249330@j4g2000prf.googlegroups.com> Message-ID: <1186511413.666702.294100@m37g2000prh.googlegroups.com> On Aug 7, 1:05 pm, Rohan <vodela.... at gmail.com> wrote: > Hello, > I would like to write a script which does the following job. > Take column1 and 7 from 10 different excel sheets and pasthe them into > a new excel worksheet. > Any ideas on how to do it > Thanks, Try studying this code: http://snippets.dzone.com/posts/show/2036 or this: http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html or this: http://mathieu.fenniak.net/plotting-in-excel-through-pythoncom/ Learning COM objects can be fun...or it can be a pain, depending on your attitude and what you're trying to automate. Mike From python at jayloden.com Thu Aug 9 13:46:51 2007 From: python at jayloden.com (Jay Loden) Date: Thu, 09 Aug 2007 13:46:51 -0400 Subject: Puzzled by "is" In-Reply-To: <20070809173855.9FDEB1E4009@bag.python.org> References: <20070809173855.9FDEB1E4009@bag.python.org> Message-ID: <46BB530B.3030304@jayloden.com> Dick Moores wrote: > >>> () is () > True > >>> (1,) is (1,) > False > > Why? > > Thanks, > > Dick Moores >From the docs for 'is': From AWasilenko at gmail.com Sat Aug 11 13:10:05 2007 From: AWasilenko at gmail.com (Adam W.) Date: Sat, 11 Aug 2007 17:10:05 -0000 Subject: Who told str() to round my int()'s!!! In-Reply-To: <5i67roF3ml00gU4@mid.uni-berlin.de> References: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> <5i67roF3ml00gU4@mid.uni-berlin.de> Message-ID: <1186852205.973858.284130@r34g2000hsd.googlegroups.com> On Aug 11, 12:53 pm, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote: > If `str()` would not round you would get very long numbers because of the > inaccuracies of floating point values. I know Python is lying when 0.1 > prints as 0.1, but do you really want to see > 0.10000000000000000555111512312578270211815834045410156250 instead? I want str() to convert whatever I give it to a string and do nothing else. I will worry about long FP values in previous steps. I still find it very disturbing that str() is doing this AND it is undocumented in all of my books. > Use string formatting to tell the number of digits you want to see: > > In [16]: '%.56f' % 0.1 > Out[16]: '0.10000000000000000555111512312578270211815834045410156250' The book I used to learn Python never introduced string formatting, I suppose I will have to use another and learn it if that is the only way... From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Aug 13 16:11:01 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 13 Aug 2007 22:11:01 +0200 Subject: python + XUL References: <1186894004.913359.132000@b79g2000hse.googlegroups.com> <46BEA6FC.9050907@web.de> <1186966451.081184.63490@r34g2000hsd.googlegroups.com> <1186979744.039833.213840@r34g2000hsd.googlegroups.com> Message-ID: <5ibs6lF3oae7fU1@mid.individual.net> Madhu Alagu wrote: > Has anyone had any success in getting XUL to work with python? Yes. http://www.google.de/search?q=xul+python http://en.wikipedia.org/wiki/Search_engine Bj?rn -- BOFH excuse #74: You're out of memory From Afro.Systems at gmail.com Tue Aug 14 05:45:04 2007 From: Afro.Systems at gmail.com (Tzury) Date: Tue, 14 Aug 2007 09:45:04 -0000 Subject: ctypes windll question Message-ID: <1187084704.869276.317030@r34g2000hsd.googlegroups.com> I followed the tutorial about ctypes and I still cannot figure out how to call a method of a calss within the dll. For example: a dll named 'foo' contain a class named 'bar' which expose a method named 'baz'. if I either do: mydll = windll.foo mycls = mydll.bar or mycls = windll.foo.bar or mycls = windll.foo.bar() I get an erros: "function 'bar' not found " which is right, since bar is a class and not a function. However, I still need to create an instance of this inner class (bar) so I can access its public method (baz). I cannot find anywhere instructions for that. From larry.bates at websafe.com Wed Aug 29 09:48:09 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 29 Aug 2007 08:48:09 -0500 Subject: Pythonwin Install COM exceptions on Windows Vista Ultimate In-Reply-To: <mailman.95.1188374497.28954.python-list@python.org> References: <mailman.95.1188374497.28954.python-list@python.org> Message-ID: <JqqdnTvJir4T5EjbnZ2dnUVZ_qninZ2d@comcast.com> Sandipan News wrote: > What do I do? Can't do without Python! > Any experience, advice, hope is welcome. > Thanks. > Sandipan > > If you are asking if you can run COM objects created in Python on Windows Vista Ultimate, the answer is yes. I have several. -Larry From cai.haibin at gmail.com Thu Aug 16 22:29:47 2007 From: cai.haibin at gmail.com (james_027) Date: Fri, 17 Aug 2007 02:29:47 -0000 Subject: to property or function in class object Message-ID: <1187317787.848991.242720@i38g2000prf.googlegroups.com> hi, i am very new to python, not knowing much about good design. I have an object here for example a Customer object, where I need to retrieve a info which has a number of lines of code to get it. my question is weather what approach should I use? to use the property which is from the python new class style as I understand or simple use function that will return the the info I needed. class Customer(object): current_balance = property(fget=_get_current_balance) def _get_current_balance(self): # coding here or def get_current_balance(self): # coding here While both approach would get the job done, I don't know much about the performance, benefits, design philosophy between the two approach. Any lecture will be very appreciated. Thanks james From bignose+hates-spam at benfinney.id.au Wed Aug 29 19:38:29 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 30 Aug 2007 09:38:29 +1000 Subject: IDE for Python References: <46CAB7D4.5070308@gmail.com> <mailman.277.1187982888.32294.python-list@python.org> <mailman.115.1188417806.28954.python-list@python.org> Message-ID: <87tzqhewsq.fsf@benfinney.id.au> Stefan Behnel <stefan.behnel-n05pAM at web.de> writes: > Eric CHAO wrote: > > I think many python developers don't need such an IDE actually. Just > > like Ruby guys, they use a powerful editor, for example, Textmate, > > instead of all-in-one IDE. It's quick and direct. > > True. However, some use neither an editor nor an IDE but Emacs. "Neither"? Emacs is both editor *and* IDE. -- \ "Some people, when confronted with a problem, think 'I know, | `\ I'll use regular expressions'. Now they have two problems." -- | _o__) Jamie Zawinski, in alt.religion.emacs | Ben Finney From programmer.py at gmail.com Wed Aug 8 21:37:32 2007 From: programmer.py at gmail.com (programmer.py at gmail.com) Date: Wed, 08 Aug 2007 18:37:32 -0700 Subject: accessing parts of large files with File.seek() In-Reply-To: <1186591585.175399.139850@x40g2000prg.googlegroups.com> References: <1186591585.175399.139850@x40g2000prg.googlegroups.com> Message-ID: <1186623452.207655.224400@22g2000hsm.googlegroups.com> On Aug 8, 11:46 am, "mhearne808[insert-at-sign-here]gmail[insert-dot- here]com" <mhearne... at gmail.com> wrote: > I'm having a problem with the File object's seek() method. > Specifically, I cannot use it to seek to a location in a binary file > that is greater than 2^31 (2147483648). This seems unnecessarily > limiting, as it is common these days to have files larger than 2 GB. > > Is there some LargeFile object out there that I can use to read my > file, which is approximately 3.3 GB in size? > > Python version (freshly built from source this morning): > Python 2.5.1 (r251:54863, Aug 8 2007, 09:23:05) > [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin > > Thanks, > > Mike I use large files quite a bit, but in Windows & Linux. Here's a quick excerpt of a local ubuntu-linux session... jaime at elizabeth:/var/virtualbox/VDI$ ls -l total 1682536 -rw-rwx--- 1 jaime vboxusers 40960 2007-07-20 21:41 windows xp.vdi -rw-rwx--- 1 jaime vboxusers 3591387136 2007-07-20 21:53 winxp.vdi jaime at elizabeth:/var/virtualbox/VDI$ ipython Python 2.5.1 (r251:54863, May 2 2007, 16:27:44) Type "copyright", "credits" or "license" for more information. IPython 0.7.3 -- An enhanced Interactive Python. ? -> Introduction to IPython's features. %magic -> Information about IPython's 'magic' % functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: f = file('winxp.vdi') In [2]: f.seek(3591387132) In [3]: f.read() Out[3]: '\x00\x00\x00\x00' In [4]: What exception are you receiving? (Not that I can offer any advice, as I don't have a Mac to use for testing.)... jw From gagsl-py2 at yahoo.com.ar Sun Aug 26 22:43:02 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 26 Aug 2007 23:43:02 -0300 Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com> <1187898049.734696.9500@l22g2000prc.googlegroups.com> <13csoronscqp7d2@corp.supernews.com> <1188090322.663217.102750@22g2000hsm.googlegroups.com> <13d4bucfm4m1lc4@corp.supernews.com> Message-ID: <op.txo5t0i7x6zn5v@gabriel2.softlabbsas.com.ar> En Sun, 26 Aug 2007 22:58:35 -0300, bambam <david at asdf.asdf> escribi?: > Ok, many environments are capable of cached evaluation > of functions without variable parameters so > range(5) > is cached, but > range(v) is re-evaluated every time. Is this defined > behaviour? The range builtin function returns a list, and lists are mutable objects, so it must return a *different* list each time. > That is, is it defined what Python does for > for i in f() > I'm sure it must be, but I haven't seen it yet. If I have > a user defined function returning a range, is it defined > that the range function is called on every loop? If I > have a function returning a range taking a parameter, > for i in f(v) > is it defined that the variable is evaluated for every loop? Find all the (mostly negative) answers yourself in <http://docs.python.org/ref/for.html> -- Gabriel Genellina From rdm at rcblue.com Sun Aug 12 23:41:26 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 12 Aug 2007 20:41:26 -0700 Subject: Binary, Hex, and Decimal string conversions In-Reply-To: <649D1D6C-A44C-4D03-920D-489BBD108789@jedimindworks.com> References: <496954360708111559s1cef4212pabd14e95b27435ea@mail.gmail.com> <C5FFAC23-F5DC-4112-A508-EC9BDF2FAB43@jedimindworks.com> <496954360708121620r4dd68ac9o430326ae8c8ae04d@mail.gmail.com> <649D1D6C-A44C-4D03-920D-489BBD108789@jedimindworks.com> Message-ID: <20070813034138.CA4C81E4012@bag.python.org> At 07:04 PM 8/12/2007, Michael Bentley wrote: >On Aug 12, 2007, at 6:28 PM, Dick Moores wrote: > >>n = 12 >>base = 36 >>print to_base(n, base) >>========================================== >>This seems to work fine for n >= base, but not for n < base. For >>example, the code shown returns "c". Is my indentation wrong, or >>the code? It seems to me that the code should work for the general >>case, not just for n >= base. > >Isn't 'c' the correct answer? Yes, of course. Stupid of me. Dick From jkrukoff at ltgc.com Wed Aug 8 13:45:49 2007 From: jkrukoff at ltgc.com (John Krukoff) Date: Wed, 8 Aug 2007 11:45:49 -0600 Subject: 'Advanced' list comprehension? query Message-ID: <003d01c7d9e3$f55c50e0$0201a8c0@naomi> John Krukoff wrote: > > pyscottishguy at hotmail.com wrote: > > Hi, > > > > I'm playing around with list comprehension, and I'm trying to find the > > most aesthetic way to do the following: > > > > I have two lists: > > > > noShowList = ['one', 'two', 'three'] > > > > myList = ['item one', 'item four', 'three item'] > > > > I want to show all the items from 'myList' that do not contain any of > > the strings in 'noShowList'. > > > > i.e. 'item four' > > > > I can do it like this: > > > > def inItem(noShowList, listitem): > > return [x for x in noShowList if x in listitem] > > > > print [x for x in myList if not inItem(noShowList, x)] > > > > and I can do it (horribly) with: > > > > print [x for x in myList if not (lambda y, z:[i for i in y if i in z]) > > (noShowList, x)] > > > > I can also print out the items that DO contain the 'noShowList' > > strings with: > > > > print [x for x in myList for y in noShowList if y in x] > > > > but I can't get the 'not' bit to work in the above line. > > > > Any ideas? > > Thanks! > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > So, conceptually speaking, you're dealing with two loops here, one over > the items to filter, and one over the items to check for substring > matches. If you want to do that with list comprehensions, I'd make it > obvious that there's two of them: > > >>> [ listItem for listItem in myList if not [ noShow for noShow in > noShowList if noShow in listItem ] ] > ['item four'] > > This is a pretty good place for the functional programming tools though, > specifically "filter", > http://docs.python.org/tut/node7.html#SECTION007130000000000000000 > , which gives a solution that looks like this: > > >>> filter( lambda listItem : not [ noShow for noShow in noShowList if > noShow in listItem ], myList ) > ['item four'] > > or using purely functional tools, like this: > > >>> filter( lambda listItem : not sum( map( lambda noShow: noShow in > listItem, noShowList ) ), myList ) > ['item four'] > > All these solutions have the problem that they're still less efficient > than the unwrapped for loop, like so: > > >>> aFiltered = [] > >>> for listItem in myList: > ... for noShow in noShowList: > ... if noShow in listItem: > ... break > ... else: > ... aFiltered.append( listItem ) > ... > >>> aFiltered > ['item four'] > > This is due to the list comprehensions testing all the possiblities, > instead of giving up on the first one found. You can jam that early break > into the functional approach using itertools, but it starts to look really > ugly on one line (requires 2.5 for if expression): > > >>> list( itertools.ifilter( lambda listItem : True if len( list( > itertools.takewhile( lambda test : not test, itertools.imap( lambda > noShow: noShow in listItem, noShowList ) ) ) ) == len( noShowList) else > False, myList ) ) > ['item four'] > > Which can be made to look much better by breaking the 'noShow in listItem' > test out into a separate function, and does have the advantage that by > using itertools.ifilter this is a lazy approach. There's got to be a > better way to do the test to see if takewhile bailed early than using len, > though. > > --------- > John Krukoff > helot at comcast.net Ah, yeah, any was the function I needed to simplify things and do the early break. I really need to upgrade to 2.5. >>> list( itertools.ifilter( lambda listItem : not any( itertools.imap( lambda noShow: noShow in listItem, noShowList ) ), myList ) ) ['item four'] Thanks Jason! --------- John Krukoff helot at comcast.net From gmcalendar at gmail.com Thu Aug 23 09:33:34 2007 From: gmcalendar at gmail.com (gmcalendar at gmail.com) Date: Thu, 23 Aug 2007 13:33:34 -0000 Subject: simple spider in python Message-ID: <1187876014.845912.236690@e9g2000prf.googlegroups.com> Hi everybody, i'm new to the forum so: hello everybody (should I say "world"?) ^_^ I'm trying to do a simple spider in python which: 1) ask google a query 2) parse the data I'm a python newbie so *any* help would be very, very welcommed. Thanks in advice! cheers! From beema.shafreen at gmail.com Tue Aug 21 00:59:39 2007 From: beema.shafreen at gmail.com (Beema shafreen) Date: Tue, 21 Aug 2007 10:29:39 +0530 Subject: hi everybody Message-ID: <aa405c1f0708202159g1e1a9a54o6d4006587f75fe44@mail.gmail.com> hi everybody, i have written to fetch the url, and accesstje nm and np entries my code: import re import urllib2 import time Gene_id=raw_input("Please enter the gene_id:") fh = urllib2.urlopen(' http://www.ncbi.nlm.nih.gov/sites/entrez?db=gene&cmd=search&term='+Gene_id) for line in fh.readlines(): pattern = re.compile('(NM_\d+.\d{0,5})</a>.*(NP_\d+.\d{0,5})</a>') m = pattern.search(line) if m: nm_entry = m.group(1) np_entry = m.group(2) length = len(np_entry) #data = raw_input("There are %s entry, They are:" %(length)) fh1 = urllib2.urlopen(' http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?val='+nm_entry) for line1 in fh1.readlines(): p1 = re.compile('source\s*(\d{1}.*\d+)') m1 = p1.search(line1) if m1: seq = m1.group(1) seq_len = seq.split('..') print nm_entry, 'Length of NM_seq:', seq_len[1],np_entry fh1.close() fh.close() time.sleep(2) in my result : Please enter the gene_id: (after this i want to get the text and data) eg., there are 11 entries and the nm and np entry the final print statement. i have include the highlighted text in code where it is repeaded since inside the looping please check about the following code and post your comments and where is include the text to get the result properly #data = raw_input("There are %s entry, They are:" %(length)) regards shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070821/c0a961a8/attachment.html> From raims at dot.com Mon Aug 6 22:30:27 2007 From: raims at dot.com (Lawrence Oluyede) Date: Tue, 7 Aug 2007 04:30:27 +0200 Subject: help with flexible decorators References: <1186452596.052963.136840@e9g2000prf.googlegroups.com> Message-ID: <1i2gkbz.p057tl1uhoy2iN%raims@dot.com> james_027 <cai.haibin at gmail.com> wrote: > While the enhance decorator work with functions of 1 argument, how do > I make it to work with more than one arguments. Using *args. Something like this: def enhance(f): def _new(*args): return f(*args) + 1 return _new @enhance def f(*args): return sum(args) In [22]: f(6) Out[22]: 7 In [23]: f(6, 4) Out[23]: 11 In [24]: f(6, 4, 10) Out[24]: 21 -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From devraj at gmail.com Sun Aug 26 04:52:03 2007 From: devraj at gmail.com (Devraj) Date: Sun, 26 Aug 2007 08:52:03 -0000 Subject: ActiveRecord for Python/MySQL In-Reply-To: <far9ul$vb3$1@aioe.org> References: <1188103880.146814.110780@q4g2000prc.googlegroups.com> <far9ul$vb3$1@aioe.org> Message-ID: <1188118323.164567.6290@e9g2000prf.googlegroups.com> Thanks On Aug 26, 5:26 pm, EuGeNe Van den Bulke <eugene.vandenbu... at gmail.com> wrote: > Devraj wrote: > > My application uses MySQL as a backend and am using the MySQL/Python > > bindings. Are there any libraries that provide a database abstraction > > layer like Activerecords for Python?' > > SQLObject > SQLAclhemy > DejaVu > Storm > > Google for Python ORM you may find more! > > EuGeNe --http://www.3kwa.com From exarkun at divmod.com Fri Aug 10 06:52:13 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 10 Aug 2007 06:52:13 -0400 Subject: The Future of Python Threading In-Reply-To: <1186740111.918048.77920@d30g2000prg.googlegroups.com> Message-ID: <20070810105213.4947.649573204.divmod.quotient.20843@ohm> On Fri, 10 Aug 2007 10:01:51 -0000, "Justin T." <jmtulloss at gmail.com> wrote: >Hello, > >While I don't pretend to be an authority on the subject, a few days of >research has lead me to believe that a discussion needs to be started >(or continued) on the state and direction of multi-threading python. > > [snip - threading in Python doesn't exploit hardware level parallelism > well, we should incorporate stackless and remove the GIL to fix this] > I think you have a misunderstanding of what greenlets are. Greenlets are essentially a non-preemptive user-space threading mechanism. They do not allow hardware level parallelism to be exploited. In a hypothetical Python interpreter, equivalent to current CPython except for the removal of the GIL, you could certainly have greenlets running in different pthreads, and thus take care of hardware parallelism, but you could do the same without greenlets too. So Stackless Python is an unrelated matter. >There has been much discussion on this in the past [2]. Those >discussions, I feel, were premature. Now that stackless is mature (and >continuation free!), Py3k is in full swing, and parallel programming >has been fully realized as THE next big problem for computer science, >the time is ripe for discussing how we will approach multi-threading >in the future. Many of the discussions rehash the same issues as previous ones. Many of them are started based on false assumptions or are discussions between people who don't have a firm grasp of the relevant issues. I don't intend to suggest that no improvements can be made in this area of Python interpreter development, but it is a complex issue and cheerleading will only advance the cause so far. At some point, someone needs to write some code. Stackless is great, but it's not the code that will solve this problem. In the mean time, you might consider some multi-process solutions. There are a number of tools for getting concurrency like that. Jean-Paul From mccredie at gmail.com Mon Aug 13 20:13:50 2007 From: mccredie at gmail.com (Matt McCredie) Date: Mon, 13 Aug 2007 17:13:50 -0700 Subject: AttributeError: 'module' object has no attribute 'HTTPSHandler' In-Reply-To: <9e95df10708131712i7c27b200pdebd68a254e30537@mail.gmail.com> References: <e04d2e90708100957t79ed5a72s259281d912508fc1@mail.gmail.com> <9e95df10708101153j74eb6431kd216503ab6c770ae@mail.gmail.com> <9e95df10708101352h45076f1cm36550126b1b548e3@mail.gmail.com> <e04d2e90708101549y50640f1aic067389992c6d73e@mail.gmail.com> <9e95df10708131712i7c27b200pdebd68a254e30537@mail.gmail.com> Message-ID: <9e95df10708131713gb2f1873jd435362c19acae7c@mail.gmail.com> > > I am using Fedora Core 4 linux. Where should I look for _ssl.pyd ? I > am trying to build and use Python-2.5.1 > I don't have access to that type of system. I do know that you need OpenSSL to use ssl. It might be as simple as just finding and installing OpenSSL for fedora. You can also find the source in the python repository at: http://svn.python.org/projects/external/openssl-0.9.8a And build that yourself. I _think_ that if you have it installed, configure might find it for you and autmatically build _ssl.pyd. Matt From jmtulloss at gmail.com Fri Aug 10 17:51:50 2007 From: jmtulloss at gmail.com (Justin T.) Date: Fri, 10 Aug 2007 21:51:50 -0000 Subject: The Future of Python Threading In-Reply-To: <1i2njyp.1o6yslqe7ff47N%luc@honk-honk.com> References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <1i2njyp.1o6yslqe7ff47N%luc@honk-honk.com> Message-ID: <1186782710.600889.245930@j4g2000prf.googlegroups.com> On Aug 10, 2:02 pm, l... at honk-honk.com (Luc Heinrich) wrote: > Justin T. <jmtull... at gmail.com> wrote: > > What these seemingly unrelated thoughts come down to is a perfect > > opportunity to become THE next generation language. > > Too late: <http://www.erlang.org/> > > :) > > -- > Luc Heinrich Uh oh, my ulterior motives have been discovered! I'm aware of Erlang, but I don't think it's there yet. For one thing, it's not pretty enough. It also doesn't have the community support that a mainstream language needs. I'm not saying it'll never be adequate, but I think that making python into an Erlang competitor while maintaining backwards compatibility with the huge amount of already written python software will make python a very formidable choice as languages adapt more and more multi-core support. Python is in a unique position as its actually a flexible enough language to adapt to a multi-threaded environment without resorting to terrible hacks. Justin From carsten at uniqsys.com Fri Aug 24 14:54:26 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 24 Aug 2007 14:54:26 -0400 Subject: creating a tar file with python In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE2F1@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE2F1@efmailx> Message-ID: <1187981666.3385.70.camel@dot.uniqsys.com> On Fri, 2007-08-24 at 12:18 -0400, Brian McCann wrote: > Ed, Carsten, Steve, > > I don?t care if Steve Holden is the python God himself, > He's a rude, arrogant, vulgar human who shows his true level > of intellect by his use of profanity That is your opinion of Steve, and you are entitled to your opinion. Those of us who have known him longer have a very different opinion of him. You are coming off as a disrespectful, clueless, mindless, thankless, spoiled brat. I'm not saying that that's what you are in real life. You're probably a nice person to work with in real life. I'm just pointing out what kind of opinion one might form of you based on your output on this thread. Now, please, let's all take a deep breath, calm down, and keep in mind that we are all human beings, we make mistakes, and we all have feelings that can get hurt. Most importantly, let's keep in mind that the limited medium of an Internet mailing list paints a very skewed picture of who we are, and we should give each other the benefit of the doubt as much as possible. Ultimately, we're all here to talk about Python and help each other out. Thanks for listening. Peace, -- Carsten Haese http://informixdb.sourceforge.net From sundol at sfc.keio.ac.jp Mon Aug 20 03:02:23 2007 From: sundol at sfc.keio.ac.jp (Hyunchul Kim) Date: Mon, 20 Aug 2007 16:02:23 +0900 Subject: How to decompress .Z file? Message-ID: <1187593343.30969.4.camel@hckim-desktop> Hi, all How can .Z file be decompressed? According to python library reference, .Z file might not be supported by python, yet. Best, Hyunchul Kim From Dominic at PLEASEASK.co.uk Tue Aug 14 09:14:45 2007 From: Dominic at PLEASEASK.co.uk (special_dragonfly) Date: Tue, 14 Aug 2007 14:14:45 +0100 Subject: Class problems. References: <46c1a34a$0$54289$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <46c1a6ec$0$11684$7b0f0fd3@mistral.news.newnet.co.uk> Just ignore this, I was being an idiot... "special_dragonfly" <Dominic at PLEASEASK.co.uk> wrote in message news:46c1a34a$0$54289$7b0f0fd3 at mistral.news.newnet.co.uk... > Hello, > I'm having problems retrieving data I think I've put into my program. I > have a class and a function. I'm reading in from a personally made text > file of the data needed for the class. The FieldsDictionary needs to be > accesable outside the function, but my problem is this: > the print FieldsDictionary[key].Fieldname (which I should have just > created because of the line above), returns: > AttributeError: 'list' object has no attribute 'Fieldname' > am I just accessing it wrongly? > I was under the impression that Fields Dictionary should contain a key > referencing to a list of instances of the class. i.e. > FieldsDictionary{key:[instance1, instance2, instance 3]} > Is this not what I've programmed? > > class FieldClass(object): > def > __init__(self,Fieldname="",Fieldlength=0,Type=["A","S","N"],Location=["D","C","L","H","TBA"]): > self.Fieldname=Fieldname > self.Fieldlength=Fieldlength > self.Type=Type > self.Location=Location > > def > EnterDictionary(FieldsDictionary,key,myfile,FIELD_QUANTITY_OFFSET,LINE_START,LINE_END): > data=myfile.readline().strip() > for i in range(int(data[FIELD_QUANTITY_OFFSET:])): > args =myfile.readline().strip()[LINE_START:LINE_END].split(",") > print args > FieldsDictionary.setdefault(key, []).append(FieldClass(*args)) > print FieldsDictionary[key].Fieldname > From kyosohma at gmail.com Sun Aug 12 21:11:44 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 13 Aug 2007 01:11:44 -0000 Subject: Hex editor - Python beginner's code open to review In-Reply-To: <f9jasr021hs@news1.newsguy.com> References: <f9jasr021hs@news1.newsguy.com> Message-ID: <1186967504.796928.264650@l22g2000prc.googlegroups.com> On Aug 10, 10:36 pm, CC <cr... at BOGUS.sbcglobal.net> wrote: > Hi: > > http://web.newsguy.com/crcarl/python/hexl.py > > This is my first Python program other than tutorial code snippet > experimentation. I chose a hex line editor. I may do a hex screen > editor once this is done, if I feel like playing with the curses module. > Or move straight to wxPython. > > This is unfinished, and is really just a hex viewer at this point. It > seems like a good point to stop and see what others think. I would be > interested to hear any comments. > > My command parsing if of course crude, brute-force, and not very > scalable. I am doing some reading on this subject, and will be trying > to do a more generalized approach in the next revision. This is going > to be a subject where I need to learn a lot, because I have 2-3 > embedded applications in C that need varying levels of command parsers, > so I will be seeking to improve this skill considerably. > > Thanks for input. > > -- > _____________________ > Christopher R. Carlen > cr... at bogus-remove-me.sbcglobal.net > SuSE 9.1 Linux 2.6.5 Looks like mostly clean code to me. I don't understand why you declare "Offset" globally twice. Wouldn't it make more sense to just stick it at the top of the file like your "Hexdigits" variable? I'm also not sure if your style follows the style guide...then again, mine probably doesn't either. You can check it out here though: http://www.python.org/doc/essays/styleguide.html Rather than using if/else statements for error checking, you may want to consider using try/except: http://docs.python.org/tut/node10.html That my 2?! Mike From wegwerp at gmail.com Wed Aug 15 10:53:58 2007 From: wegwerp at gmail.com (Bas) Date: Wed, 15 Aug 2007 14:53:58 -0000 Subject: FM synthesis using Numpy In-Reply-To: <mailman.1990.1187134824.22759.python-list@python.org> References: <mailman.1990.1187134824.22759.python-list@python.org> Message-ID: <1187189638.121287.311030@k79g2000hse.googlegroups.com> You got your math wrong. What you are calculating is: sin(2*pi*(1000+15*sin(2*pi*6*t))*t) = sin(2*pi*1000*t + 2*pi*15*sin(2*pi*6*t)*t) The 'instantaneous frequency' can be calculated by differentiating the argument of the sine and dividing by 2pi: x = sin(phi(t)) -> f_inst = d (phi(t)) / dt / (2*pi) So in your case: f_inst = 1000 + 15*sin(2*pi*6*t) + 2*pi*t*6*15*cos(2*pi*6*t) the last term explains the effect you hear. What you want is: f_inst = f0 + df*cos(2*pi*fm*t) Integrating this and multiplying by 2pi gives the phase: phi(t) = 2*pi*f0*t + sin(2*pi*fm*t)*df/fm So you can achieve the frequency modulation by using phase modulation (these two are related). You can do this with your own code by phi = oscillator(t, freq=6, amp=15/6) tone = oscillator(t, freq=1000, amp=0.1, phase=phi) cheers, Bas From grante at visi.com Fri Aug 31 13:33:25 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 31 Aug 2007 17:33:25 -0000 Subject: low level ethernet device access in linux References: <mailman.223.1188580797.28954.python-list@python.org> Message-ID: <13dgk75erohnta9@corp.supernews.com> On 2007-08-31, Tom Brown <brown at esteem.com> wrote: > I understand that I am getting this error because I am running > the application as a user and not as root. I would like to be > able to run this app. as a user. Is there a way to create a > socket without running the app. as root or sudo? Yes. According to the raw(7) man page: ERRORS EPERM The user doesn't have permission to open raw sockets. Only pro- cesses with a effective user ID of 0 or the CAP_NET_RAW attribute may do that. Anticipating your next question: $ man capabilities -- Grant Edwards grante Yow! Well, I'm INVISIBLE at AGAIN ... I might as well visi.com pay a visit to the LADIES ROOM ... From ninja.krmenadl at nes.com Mon Aug 20 10:16:44 2007 From: ninja.krmenadl at nes.com (Boris Ozegovic) Date: Mon, 20 Aug 2007 16:16:44 +0200 Subject: I Need help from all the group participants Message-ID: <fac7nj$ci9$1@localhost.localdomain> Hi, I am working on some system, and the communication will take place through the chatterbot which will be written in AIML (interpreter is written in Python). English is not my mother tongue, so I need huge favor: if all of you can write two sentences, so that I could have greater pattern base. The first sentence is finding someone's heart rate, example: "Please, can you tell me John's heart rate", and the other one is setting the alarm when someone's heart rate is lower then x, and greater than y, example: "Can you, please, send me information when John's heart rate is lower than 60, and greater than 100". You can manipulate time (right now, now, right this moment), and everything else you can think about. -- Ne dajte da nas la?ljivac Bandi? truje: http://cnn.blog.hr/arhiva-2007-06.html#1622776372 From laurent.pointal at limsi.fr Fri Aug 31 03:03:45 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 31 Aug 2007 09:03:45 +0200 Subject: Coding Standards In-Reply-To: <1188540331.961231.36850@r23g2000prd.googlegroups.com> References: <1188540331.961231.36850@r23g2000prd.googlegroups.com> Message-ID: <fb8egh$2h0$1@news2.u-psud.fr> davidsamith at gmail.com a ?crit : > 'Good code' is code that works, is bug free, and is readable and > maintainable. Standards need to be followed for coding. Read more... > > http://brsx.co.uk/SWtesting/FAQs/FAQs012.asp You misstyped your URL and referenced a C++ related document, for Python its here: http://www.python.org/dev/peps/pep-0008/ ;-) From conra2004 at yahoo.com Fri Aug 17 07:57:47 2007 From: conra2004 at yahoo.com (yadin) Date: Fri, 17 Aug 2007 04:57:47 -0700 Subject: passing variables and values to texboxdisplays Message-ID: <1187351867.699825.91860@57g2000hsv.googlegroups.com> hi! Can any one tell me why is it that i can't see my second frame and why is the value of freq not Appended in the First frame ...thanks I know it is wx python but it has to do with passing variables.thanks import wx def create(parent): return Frame1(parent) [wxID_FRAME1, wxID_FRAME1FREQ, wxID_FRAME1FREQDISP, wxID_FRAME1STATICTEXT1, ] = [wx.NewId() for _init_ctrls in range(4)] class Frame1(wx.Frame): def _init_ctrls(self, prnt): # generated method, don't edit wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt, pos=wx.Point(380, 179), size=wx.Size(241, 133), style=wx.DEFAULT_FRAME_STYLE, title='Frame1') self.SetClientSize(wx.Size(233, 99)) self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1, label='frequency disp', name='staticText1', parent=self, pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) self.freqdisp = wx.TextCtrl(id=wxID_FRAME1FREQDISP, name='freqdisp', parent=self, pos=wx.Point(104, 24), size=wx.Size(100, 21), style=0, value='') self.freq = wx.Button(id=wxID_FRAME1FREQ, label='get freq', name='freq', parent=self, pos=wx.Point(24, 56), size=wx.Size(184, 23), style=0) self.freq.Bind(wx.EVT_BUTTON, self.OnButton1Button, id=wxID_FRAME1FREQ) def __init__(self, parent): self._init_ctrls(parent) def OnButton1Button(self, event): def create(parent): return Frame2(parent) [wxID_FRAME2, wxID_FRAME2FREQ, wxID_FRAME2FREQDISP, wxID_FRAME2STATICTEXT1,] = [wx.NewId() for _init_ctrls in range(4)] class Frame2: def __init__(self): # wx.Frame.__init__(self, id=wxID_FRAME2, name='', parent=prt, pos=wx.Point(400, 179), size=wx.Size(300, 133), style=wx.DEFAULT_FRAME_STYLE, title='Frame2') self.SetClientSize(wx.Size(233, 99)) self.staticText1 = wx.StaticText(id=wxID_FRAME2STATICTEXT1, label='frequency goes here first', name='staticText2', parent=self, pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) self.freqdisp2 = wx.TextCtrl(id=wxID_FRAME2FREQDISP, name='freqdisp2', parent=self, pos=wx.Point(104, 24), size=wx.Size(100, 21), style=0, value=' ') self.freq = wx.Button(id=wxID_FRAME2FREQ, label='get freq', name='freq', parent=self, pos=wx.Point(24, 56), size=wx.Size(184, 23), style=0) self.freq.Bind(wx.EVT_BUTTON, self.OnButton2Button, id=wxID_FRAME2FREQ) def __init__(self, parent): self._init_ctrls(parent) def OnButton2Button(self, event): freqdisp.Append('this is it 24HZ!') if __name__ == '__main__': app = wx.PySimpleApp() frame = create(None) frame.Show() app.MainLoop() From gerdusvanzyl at gmail.com Sat Aug 25 09:38:42 2007 From: gerdusvanzyl at gmail.com (Gerdus van Zyl) Date: Sat, 25 Aug 2007 13:38:42 -0000 Subject: pure python gaussian blur In-Reply-To: <mailman.1977.1187112429.22759.python-list@python.org> References: <1187108679.401416.224060@19g2000hsx.googlegroups.com> <mailman.1977.1187112429.22759.python-list@python.org> Message-ID: <1188049122.152639.26060@q3g2000prf.googlegroups.com> Ok, now answering my own question :-) Gaussian blurs can be optimized by seperating the equation and applying in two passes. I also implemented a version using State Vector Machines from www- personal.engin.umd.umich.edu/~jwvm/ece581/21_GBlur.pdf but it does not produce correct results. Most probably my fault, but it is 4x faster. (code available on request) Then after all this i learnt that using multiple box blurs approximate a gaussian blur within 3%. This is the solution i use now and is fast enough for my needs and in pure python. Code for gaussian blur and box blur below. ~Gerdus van Zyl Seperated Gaussian blur: def blurB(self): pixels = self.array temp1 = copy.copy(pixels) #temp2 = copy.copy(pixels) stride = self.width * 4 clr = array.array('B',[255,255,255,255]) w = self.width h = self.height def pascal(n): """Prints n first lines of Pascal`s triangle author: DR#m <dnpsite.narod.ru> last rev 20.03.05""" #n += 1 l=[1] p=[] for i in xrange(n): l2=[1] for j in xrange(len(l)-1): l2.append(l[j]+l[j+1]) l2.append(1) #print l l=l2 return l N = 5 g = pascal(N) print '>',g gauss_fact = g #gauss_fact = [1,2,1] #gauss_fact = [1,1] gauss_width = len(gauss_fact) s = 0 for n in gauss_fact: s += n gauss_sum = s print "Pass01" for i in range(1,w-1): #print i," of ",w for j in range(1,h-1): sumr=0 sumg=0 sumb=0 for k in range(0,gauss_width): x = i-((gauss_width-1)>>1)+k y = j offset = y * stride + x * 4 pixel = pixels[offset:offset +4] r = pixel[0] g = pixel[1] b = pixel[2] sumr+=r*gauss_fact[k] sumg+=g*gauss_fact[k] sumb+=b*gauss_fact[k] clr[0] = sumr/gauss_sum clr[1] = sumg/gauss_sum clr[2] = sumb/gauss_sum x = i y = j offset = y * stride + x * 4 temp1[offset:offset+4] = clr print "Pass02" for i in range(1,w-1): #print i," of ",w for j in range(1,h-1): sumr=0 sumg=0 sumb=0 for k in range(0,gauss_width): x = i-((gauss_width-1)>>1)+k y = j offset = y * stride + x * 4 pixel = temp1[offset:offset+4] r = pixel[0] g = pixel[1] b = pixel[2] sumr+=r*gauss_fact[k] sumg+=g*gauss_fact[k] sumb+=b*gauss_fact[k] clr[0] = sumr/gauss_sum clr[1] = sumg/gauss_sum clr[2] = sumb/gauss_sum self.setPixel(i,j,clr) #to temp1 Box Blur: def _boxBlur(self): N = 5 xsum = 0 xsumar = [] pixels = self.array opixels = copy.copy(pixels) stride = self.width * 4 clr = array.array('B',[255,255,255,255]) w = self.width h = self.height pixel = 0 for rgb in [0,1,2]: for x in range(0,w): #print i," of ",w for y in range(0,h): hN = N/2 offset = (y-hN) * stride + (x-hN) * 4 if offset < 0: offset = 0 pixel = pixels[offset+rgb] xsumar.append(pixel) if len(xsumar) > N: xsumar = xsumar[-N:] xsum = 0 for v in xsumar: xsum += v xsum /= len(xsumar) pixels[offset+rgb] = xsum #x for rgb in [0,1,2]: for y in range(0,h): #print i," of ",w for x in range(0,w): hN = N/2 offset = (y-hN) * stride + (x-hN) * 4 if offset < 0: offset = 0 pixel = pixels[offset+rgb] xsumar.append(pixel) if len(xsumar) > N: xsumar = xsumar[-N:] xsum = 0 for v in xsumar: xsum += v xsum /= len(xsumar) pixels[offset+rgb] = xsum From jmtulloss at gmail.com Fri Aug 10 12:52:23 2007 From: jmtulloss at gmail.com (Justin T.) Date: Fri, 10 Aug 2007 16:52:23 -0000 Subject: The Future of Python Threading In-Reply-To: <mailman.1826.1186743471.22759.python-list@python.org> References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <mailman.1826.1186743471.22759.python-list@python.org> Message-ID: <1186764743.225475.241870@q3g2000prf.googlegroups.com> On Aug 10, 3:57 am, Steve Holden <st... at holdenweb.com> wrote: > Justin T. wrote: > > Hello, > > > While I don't pretend to be an authority on the subject, a few days of > > research has lead me to believe that a discussion needs to be started > > (or continued) on the state and direction of multi-threading python. > [...] > > What these seemingly unrelated thoughts come down to is a perfect > > opportunity to become THE next generation language. It is already far > > more advanced than almost every other language out there. By > > integrating stackless into an architecture where tasklets can be > > divided over several parallelizable threads, it will be able to > > capitalize on performance gains that will have people using python > > just for its performance, rather than that being the excuse not to use > > it. > > Aah, the path to world domination. You know you don't *have* to use > Python for *everything*. > True, but Python seems to be the *best* place to tackle this problem, at least to me. It has a large pool of developers, a large standard library, it's evolving, and it's a language I like :). Languages that seamlessly support multi-threaded programming are coming, as are extensions that make it easier on every existent platform. Python has the opportunity to lead that change. > > Be my guest, if it's so simple. > I knew somebody was going to say that! I'm pretty busy, but I'll see if I can find some time to look into it. > > I doubt that a thread on c.l.py is going to change much. It's the > python-dev and py3k lists where you'll need to take up the cudgels, > because I can almost guarantee nobody is going to take the GIL out of > 2.6 or 2.7. > I was hoping to get a constructive conversation on what the structure of a multi-threaded python would look like. It would appear that this was not the place for that. > Is it even possible > to run threads of the same process at different priority levels on all > platforms? No, it's not, and even fewer allow the scheduler to change the priority dynamically. Linux, however, is one that does. From bdesth.quelquechose at free.quelquepart.fr Thu Aug 2 11:03:29 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 02 Aug 2007 17:03:29 +0200 Subject: i am new to python-Please somebody help In-Reply-To: <1186063842.827016.95030@q3g2000prf.googlegroups.com> References: <1186047103.673871.150460@z24g2000prh.googlegroups.com> <pan.2007.08.02.12.51.13.363293@REMOVE.THIS.cybersource.com.au> <1186063842.827016.95030@q3g2000prf.googlegroups.com> Message-ID: <46b249a4$0$31219$426a74cc@news.free.fr> gregarican a ?crit : (snip) > This link answers my question --> http://www.google.com/search?hl=en&q=Python+list+rudeness. I seriously don't think that this newsgroup can be qualified as "rude" (and I'm possibly one of the "rudest" persons here). Compared to most comp.* newsgroup, Python is certainly one of the most tolerant and newbie-friendly around - and quite a lot of newcomers say so. FWIW, even FAQs, RTFMs or STFWs are usually expressed in a mostly polite way, and almost always with links and pointers (and FWIW, it's the case here). > Honestly, I have developed in both Ruby and Python for years now and > have consistently found that the Ruby community if more newbie- > friendly than Python's. I spent sometimes lurking on c.l.ruby and didn't find it *that* friendly. Not more than c.l.py at least, and certainly less respectful of peoples coming from other languages... Now if you want some examples of definitively "rude" newsgroups, I suggest you take your chance on other newsgroups in the comp.* hierarchy... From hyugaricdeau at gmail.com Wed Aug 29 09:25:07 2007 From: hyugaricdeau at gmail.com (Hyuga) Date: Wed, 29 Aug 2007 13:25:07 -0000 Subject: self extracting zipefile (windows) and (standard module) zipefile In-Reply-To: <1188388421.010643.19050@50g2000hsm.googlegroups.com> References: <1188388421.010643.19050@50g2000hsm.googlegroups.com> Message-ID: <1188393907.080206.246270@y42g2000hsy.googlegroups.com> First of all, there's really no such thing as a "self extracting zipefile". I mean, obviously you have to do something to unzip it. A file doesn't just execute itself. What you're dealing with is not a _zip file_. It's an executable that has a zip file bundled with it, and the code to unzip it, most likely into your current directory (though some such executables allow you to provide a path to unzip to). You'll have to execute it--there's no way you can operate on it like a normal zip file. On Aug 29, 7:53 am, Werner <Werner.Me... at fujitsu-siemens.com> wrote: > Hi, > > I try to read (and extract) some "self extracting" zipefiles on a > Windows system. The standard module zipefile seems not to be able to > handle this. > > >>> fName = r"C:\tmp\mySelfExtratingFile.exe" > >>> import zipfile > >>> zipefile.is_zipfile(fName)) > > False > > Is there a wrapper or has some one experience with other libaries to > extract those files? > > Thanks in advance > Werner From zyzhu2000 at gmail.com Fri Aug 17 09:41:57 2007 From: zyzhu2000 at gmail.com (beginner) Date: Fri, 17 Aug 2007 13:41:57 -0000 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: <mailman.2104.1187336977.22759.python-list@python.org> References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> <mailman.2104.1187336977.22759.python-list@python.org> Message-ID: <1187358117.200341.270960@r23g2000prd.googlegroups.com> On Aug 17, 2:35 am, S?bastien Buchoux <seb.buch... at gmail.com> wrote: > beginner a ?crit : > > > > > Hi All. > > > I'd like to do the following in more succint code: > > > if k in b: > > a=b[k] > > else: > > a={} > > b[k]=a > > > a['A']=1 > > > In perl it is just one line: $a=$b->{"A"} ||={}. > > > Thanks, > > Geoffrey > > One solution I often use in such cases: > > try: > a = b[k] > except KeyError: #or except IndexError: if b is a list/tuple and not a dict > a = {} > b[k] = a > > a['A'] = 1 > > Indeed, exceptions are handled faster than "if/else" loops. As it was > mentionned earlier, One neat solution in Perl may not be the perfect one > in Python. > > Cheers, > > S?bastien- Hide quoted text - > > - Show quoted text - Wow. This solution is interesting. I'll try this. Thanks. From airconditi at gmail.com Tue Aug 7 15:46:51 2007 From: airconditi at gmail.com (airconditi at gmail.com) Date: Tue, 07 Aug 2007 12:46:51 -0700 Subject: Tuning - Styling Message-ID: <1186516011.575543.88670@22g2000hsm.googlegroups.com> Cool cars, tuning & styling, here you can find many tuned cars with tons of pictures!!!!!!! http://tuning-styling.blogspot.com/ From antroy at gmail.com Wed Aug 15 07:08:53 2007 From: antroy at gmail.com (Ant) Date: Wed, 15 Aug 2007 04:08:53 -0700 Subject: creating and appending to a dictionary of a list of lists In-Reply-To: <1187145044.394889.312590@x35g2000prf.googlegroups.com> References: <1187145044.394889.312590@x35g2000prf.googlegroups.com> Message-ID: <1187176133.986004.213880@a39g2000hsc.googlegroups.com> On Aug 15, 3:30 am, pyscottish... at hotmail.com wrote: > Hey, > > I started with this: > > factByClass = {} > ... > def update(key, *args): > x = factByClass.setdefault(key, [[], [], [], [] ]) > for i, v in enumerate(args): > x[i].append(v) > > Is there a better way? Well, the following is perhaps neater: >>> factByClass = defaultdict(lambda: [[],[],[],[]]) >>> def update(key, *args): ... map(list.append, factByClass[key], args) ... >>> update('one', 1, 2, 3, 4) >>> update('one', 5, 6, 7, 8) >>> update('two', 9, 10, 11, 12) >>> >>> print factByClass defaultdict(<function <lambda> at 0x00F73430>, {'two': [[9], [1 0], [11], [12]], 'one': [[1, 5], [2, 6], [3, 7], [4, 8]]}) It abuses the fact that list.append modifies the list in place - normally you would use map to get a new list object. In this case the new list returned by map is just a list of None's (since append returns None - a common idiom for functions that operate by side effect), and so is not used directly. -- Ant... http://antroy.blogspot.com/ From laurent.pointal at limsi.fr Tue Aug 28 02:54:59 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 28 Aug 2007 08:54:59 +0200 Subject: SCF released to GPL In-Reply-To: <zHLAi.102$7P7.54@newssvr19.news.prodigy.net> References: <ZBnAi.21498$eY.43@newssvr13.news.prodigy.net> <46d29a6c$0$27404$ba4acef3@news.orange.fr> <zHLAi.102$7P7.54@newssvr19.news.prodigy.net> Message-ID: <fb0gs3$g8n$2@news2.u-psud.fr> hg a ?crit : > 2) I'm desperately searching for the French NG from my client but cannot > find it ... any clue ? Maybe you can pass the message ? Done. See http://groups.google.com/group/fr.comp.lang.python/browse_frm/thread/fa4474921f77b1be/8d6150d502447510#8d6150d502447510 From indu_shreenath at yahoo.co.in Fri Aug 10 05:00:28 2007 From: indu_shreenath at yahoo.co.in (indu_shreenath at yahoo.co.in) Date: Fri, 10 Aug 2007 02:00:28 -0700 Subject: how to get output. In-Reply-To: <46BB64B6.1000303@websafe.com> References: <mailman.1777.1186641317.22759.python-list@python.org> <5hvrhhF3m15c7U1@mid.uni-berlin.de> <1186645852.687961.323420@x35g2000prf.googlegroups.com> <1186646135.742185.5280@x35g2000prf.googlegroups.com> <46BB64B6.1000303@websafe.com> Message-ID: <1186736428.586532.265680@e16g2000pri.googlegroups.com> On Aug 10, 12:02 am, Larry Bates <larry.ba... at websafe.com> wrote: > indu_shreen... at yahoo.co.in wrote: > > I corrected a typ below. > > > On Aug 9, 12:50 pm, indu_shreen... at yahoo.co.in wrote: > >> Hey, > > >> I did write the following: > >> but it does not work. > > >> import subprocess as sp > >> try: > >> p = sp.Popen("DIR . /AD /B", stdout=sp.PIPE) > >> result = p.communicate()[0] > >> print result > >> except: > >> print "error" > > >> This throws error. > >> DIR . /AD /B will list out only directories in the current directory. > > >> Thanks, > >> Indu > > >> On Aug 9, 11:46 am, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > > >>> indu_shreenath schrieb: > >>>> Hey, > >>>> I want to get the output of "DIR /AD /B" command to a varriable using > >>>> python. How can I do this? > >>> Using the subprocess-module. > >>> However, I'm not sure what DIR /AD /B does - but there are many > >>> functions in module os that might deliver what you want without invoking > >>> an external command. > >>> Diez- Hide quoted text - > >> - Show quoted text - > > That is better done in python with: > > import os > dirs=[d for d in os.listdir(os.curdir) if os.path.isdir(d)] > > or > > dirs=filter(os.path.isdir, os.listdir(os.curdir)) > > -Larry- Hide quoted text - > > - Show quoted text - Thanks I could implement it. Indu From enleverlesX.XmcX at XmclaveauX.com Mon Aug 27 14:03:23 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Mon, 27 Aug 2007 20:03:23 +0200 Subject: How to free memory ( ie garbage collect) at run time with Python 2.5.1(windows) References: <1188224306.863247.127890@50g2000hsm.googlegroups.com> <mn.dbf07d78329985f0.46195@XX.XmclaveauX.com> Message-ID: <46d31272$0$25942$ba4acef3@news.orange.fr> A?e! gmail said : "illegal attachment" (because .exe?) I will try to send a zipped-file... @+ Michel Claveau From michele.simionato at gmail.com Fri Aug 31 05:31:05 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 31 Aug 2007 09:31:05 -0000 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188547369.428712.194430@x35g2000prf.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> <1188547369.428712.194430@x35g2000prf.googlegroups.com> Message-ID: <1188552665.363115.175310@x35g2000prf.googlegroups.com> On Aug 31, 10:02 am, Russ <uymqlp... at sneakemail.com> wrote: > > Hi Alex. I've always enjoyed your Piggies talks at > Google (although I missed he last one because I was out > of town). I'm disappointed to see that you seem to have > taken personal offense from remarks I made to someone else who > attacked me first. I am curious. Why do you think I attacked you? The conversion went as follows: > On Aug 29, 7:21 am, Russ <uymqlp... at sneakemail.com> wrote: >> Thanks for that information. That's too bad, because it seems like a >> strong positive capability to add to Python. I wonder why the cold >> reception. Were there problems with the idea itself or just the >> implementation? Or is it just a low priority? > me: > Why do you think that would ad a strong positive capability? > To me at least it seems a big fat lot of over-engineering, not > needed in 99% of programs. In the remaining 1%, it would still not > be needed since Python provides out of the box very powerful > metaprogramming capabilities so that you can implement > yourself the checks you need, if you really need them. Basically you said "I think DbC is good" and I said "I don't think so". I would not call that an attack. If you want to see an attack, wait for Alex replying to you observations about the low quality of code at Google! ;) Michele Simionato From horpner at yahoo.com Wed Aug 1 12:27:02 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 01 Aug 2007 16:27:02 GMT Subject: Python end of file marker similar to perl's __END__ References: <1185940391.135261.130950@i38g2000prf.googlegroups.com> <1185976656.753817.27980@x40g2000prg.googlegroups.com> <slrnfb17m5.224.horpner@FIAD06.norwich.edu> <eml6o4-tvd.ln1@lairds.us> Message-ID: <qv2si.37263$G23.1227@newsreading01.news.tds.net> On 2007-08-01, Cameron Laird <claird at lairds.us> wrote: > In article <slrnfb17m5.224.horpner at FIAD06.norwich.edu>, > Neil Cerutti <horpner at yahoo.com> wrote: >>On 2007-08-01, beginner <zyzhu2000 at gmail.com> wrote: >>> Thanks everyone for responding. It doesn't look like python has >>> it. I would definitely miss it. As Steve said, the nice thing >>> about __END__ is that things below __END__ do not have to have >>> legit syntax. That let me focus on the lines of code I am >>> debugging and do not have to worry about some bad syntax down >>> the line. This feature is especially handy if I am, saying, >>> replacing modoules or changing data structures. >> >>A C-like trick might be helpful while refactoring: >> >><working code> >>if False: >> <non-working code> >> >>You have to indent all the non-working code by one level, but >>with a good editor that's a snap. >> >>Python will still parse the following lines (it must be valid >>Python syntax), but the resulting parse tree won't be executed. > . > . > . > I want to re-emphasize the "triple-quote it" tip mentioned > earlier in this thread. I think the original questioner > will find this quite satisfying, if I understand his situ- > ation at all. > > *I* certainly have source code with embedded "junk" > commented out as multi-line strings. I used to do that, but now that I use doctests so much it's infeasible to comment out arbitrary code that way, since they can't necessarily nest. But Diez suggestion is even easier than the if False suggestion I made. -- Neil Cerutti From mhearne808 at gmail.com Fri Aug 31 09:47:02 2007 From: mhearne808 at gmail.com (mhearne808[insert-at-sign-here]gmail[insert-dot-here]com) Date: Fri, 31 Aug 2007 06:47:02 -0700 Subject: fcntl problems In-Reply-To: <mailman.186.1188541398.28954.python-list@python.org> References: <1188512377.441241.107900@q4g2000prc.googlegroups.com> <1188515889.352267.220790@q5g2000prf.googlegroups.com> <mailman.186.1188541398.28954.python-list@python.org> Message-ID: <1188568022.988154.188230@y42g2000hsy.googlegroups.com> On Aug 31, 12:23 am, Miles <semantic... at gmail.com> wrote: > Sorry, that last quote-only reply was accidental. :) > > On 8/30/07, mhearne808 wrote: > > I've been doing some experiments, and here are some specific examples > > to try. > > [snipped examples] > > > From these last two experiments I can only conclude that file locking > > isn't doing a durned thing. > > > What's going on? > > File locking isn't doing a durned thing in those cases because you're > only obtaining the lock from a single process. > > > According to my Python Cookbook: > > "Exclusive lock: This denies all _other_ processes both read and write > > access to the file." > > This is only for mandatory locking; POSIX flock is advisory locking, > which states: "Only one process may hold an exclusive lock for a given > file at a given time." Advisory locks don't have any effect on > processes that don't use locks. Mandatory locks are kernel enforced, > but non-POSIX and not available in Mac OS X. > > -Miles I think I'm still confused. Maybe I should explain the behavior that I want, and then figure out if it is possible. I have a script that will be run from a cron job once a minute. One of the things this script will do is open a file to stash some temporary results. I expect that this script will always finish its work in less than 15 seconds, but I didn't want to depend on that. Thus I started to look into file locking, which I had hoped I could use in the following fashion: Process A opens file foo Process A locks file foo Process A takes more than a minute to do its work Process B wakes up Process B determines that file foo is locked Process B quits in disgust Process A finishes its work Since I couldn't figure out file locking, I decided to just have Process A create a "pid" file in the directory - analogous to the "Occupied" sign on an airplane bathroom. This works, but it seems a little hacky. --Mike From Michael.J.Fromberger at Clothing.Dartmouth.EDU Thu Aug 2 12:54:45 2007 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Thu, 02 Aug 2007 12:54:45 -0400 Subject: a dict trick References: <1186036331.304916.304020@e9g2000prf.googlegroups.com> Message-ID: <Michael.J.Fromberger-09FEF9.12544502082007@localhost> In article <1186036331.304916.304020 at e9g2000prf.googlegroups.com>, james_027 <cai.haibin at gmail.com> wrote: > hi > > for example I have this dictionary > > dict = {'name':'james', 'language':'english'} > > value = 'sex' in dict and dict['sex'] or 'unknown' > > is a right pythonic of doing this one? I am trying to get a value from > the dict, but if the key doesn't exist I will provide one. Hi, James, You might prefer: d = {'name': 'James', 'language': 'English'} value = d.get('sex', 'unknown') This accomplishes what your above code does, using a method of the built-in dict object. If you also wish to ADD the new value to the dictionary, you may also use the following: value = d.setdefault('sex', 'unknown') This returns the same value as the above, but also adds the key 'sex' to the dictionary as a side-effect, with value 'unknown'. Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From stef.mientki at gmail.com Tue Aug 14 17:24:00 2007 From: stef.mientki at gmail.com (stef mientki) Date: Tue, 14 Aug 2007 23:24:00 +0200 Subject: buggie in else syntax ? Message-ID: <46C21D70.8000409@gmail.com> hello, I've the idea that the "else" syntax is not always handled correctly, or I'm overlooking something. This pieces of code are automatic translation from another language, sometimes it works, sometimes it doesn't ??? This piece of code works nice: a = 2 def JSM (line_nr): print line_nr if a>3: print 'asddas' else: JSM(230) ; \ <== this is the problem line, that's ok here print 'aaps' While this piece of code gives a syntax error: #Function button_antidender(bit in pin,sbyte in out Button_Counter_Temp,byte in demp) return bit is def button_antidender ( pin, button_counter_temp, demp ): #serial_hw_write(counter) Serial_HW_Write ( button_counter_temp ) ;JSM(226) if JSM(227) and ( button_counter_temp >= 0 ): if JSM(228) and ( pin == on ): button_counter_temp = button_counter_temp + 1 ;JSM(229) else: JSM(230) ; \ <=== SYNTAX ERROR button_counter_temp = 1 ;JSM(231) Traceback (most recent call last): File "D:\data_to_test\JALsPy\JALsPy.py", line 347, in ? Run_JALsPy_Application () File "D:\data_to_test\JALsPy\JALsPy.py", line 327, in Run_JALsPy_Application JG.app.MainLoop() File "D:\data_to_test\JALsPy\JALsPy.py", line 255, in MainLoop import JAL_simulation_file File "D:\data_to_test\JALsPy\JAL_simulation_file.py", line 265 else: JSM(230) ; \ I guess it's not the preferred syntax, but the resemblance with the original language it optimal. Why is it sometimes accepted an sometimes give an error message ? thanks, Stef Mientki From tim.couper at scivisum.co.uk Thu Aug 30 10:44:50 2007 From: tim.couper at scivisum.co.uk (Tim Couper) Date: Thu, 30 Aug 2007 15:44:50 +0100 Subject: Important Research Project In-Reply-To: <1188482087.098419.56490@k79g2000hse.googlegroups.com> References: <13ddcvm1bsu3s94@corp.supernews.com> <1188482087.098419.56490@k79g2000hse.googlegroups.com> Message-ID: <46D6D7E2.7020609@scivisum.co.uk> Paul Excellent post .. brightens up the otherwise hum-drum life! Tim Dr Tim Couper CTO, SciVisum Ltd www.scivisum.com Paul McGuire wrote: > On Aug 30, 8:12 am, "E.D.G." <edgrs... at ix.netcom.com> wrote: > >> Important Research Project (Related to computer programming) >> >> Posted by E.D.G. on August 30, 2007 edgrs... at ix.netcom.com >> >> This report is being posted to a number of Internet Newsgroups >> > > Always the hallmark of a considerate poster. > > >> to see if >> there are any experienced computer programmers who would like to provide >> some assistance with an effort to develop a Perl language computer program. >> >> Interested parties can try contacting me by e-mail or by posting a >> response note to the comp.lang.perl.misc newsgroup. They would need to >> download a recent (free) MSI copy of Perl from the ActiveState Web site and >> get it running on a Windows XP or Vista system. >> >> http://www.activestate.com >> >> > > This is a little backwards, one usually presents their research topic > *first* and their contact info *last*. The reason? SO PEOPLE KNOW > WHAT THE @#$(&#!@ YOU ARE WORKING ON! Ok, I'll bite, keep reading... > > >> I am presently using Perl 5.8.8 >> > > Whoop-de-doo for you. > > >> but plan to upgrade to the latest >> version as soon as possible. People can use Windows 98 if that is the only >> operating system available. Perl also runs on other operating systems. But >> at this time I specifically need help with the Windows version. >> >> > > I suspect Perl is largely the same Perl on all those platforms. Win > 98? Is this a zombie spam from the turn of the century? > > >> The goal is to have a single Perl program (or modules) perform functions >> that have been done by a sizeable collection of other language programs in >> the past. >> >> > > Doing what!? Grrr..., keep reading, there's gotta be a punch line... > > >> Help is presently needed with learning how to get Perl to generate >> charts and also produce standalone .exe copies of itself. The plan is to >> then make those .exe copies available to other scientific researchers around >> the world for free use along with free use updates when they become >> available. If other researchers wish to get Perl running on their own >> computers then they will probably also be given the source code for the >> original program for free use so that they can do their own development >> work. >> >> > > Ohmigod, is Google broken? Or has Perl gone this long and this far > without support for creating charts and graphs? Sounds like about 10 > minutes of research. > > >> Perl was originally chosen because it is quite versatile, is a free >> download, and is supported both by ActiveState and quite a few independent >> programmers. So other researchers could get their own versions running >> without having to worry about viruses or cost. >> >> > > (Why is this posted on all these non-Perl newsgroups, then? I've > *seen* Perl already, and never want to again!) > > >> So far the work is fairly advanced. The effort has been underway for at >> least a decade. >> > > ... and we are just getting around to plotting some data. > > >> The core data generation program was formally copyrighted >> several years ago. >> > > Red flag #37 - "formally copyrighted", wooo-ooooh > > >> My present version of Perl will send data to Windows as >> if it were being manually typed into the keyboard (important for controlling >> other programs). And it can directed to respond to most keystrokes even >> when another program is the active one. Unfortunately, Windows also >> presently responds to those keystrokes. And that complicates things a bit. >> >> > > ... and has for the past decade, and I still haven't figured it out. > > >> Not being a professional computer programmer I have been finding it >> difficult to get new features such as a chart generating ability merged with >> and running with Perl. And the entire research project is now being slowed >> as a result. One of my colleagues has done an extensive amount of work with >> Basic. And I even offered to pay him to help with the Perl development >> effort. But after he downloaded a copy of Perl and examined it he decided >> that this would involve too much effort. I have to agree with him. >> >> > > Maybe that up-front language choice could stand a review... > > >> Once it is possible to create charts and .exe versions the plan is for >> researchers around the world to develop Perl modules for generating a >> variety of data related to sun, moon, planet, ocean tide crest and trough, >> and Solid Earth Tide locations. Most of those data can already be generated >> with other programs. Some of the data are not yet available anywhere as far >> as I am aware. If the effort is unusually successful the Perl program (or >> modules) might eventually be converted to CGI programs that will run at one >> or more Internet Web sites. >> > > AHHH! The "research", I almost forgot! Why is it left to the end of > the message? And do we still know what the @#(*&$ this "variety of > data" is for? I'm going to take a wild guess here - earthquake > prediction? perpetual motion? picking guaranteed-to-win lottery > numbers? > > After a pitch like that, who could not be tempted at the prospect of > "generating a variety of data related to sun, moon, etc. etc."? Sign > me up - NOT! > > GTFA, > -- Paul > > From daniels at dsl-only.net Sun Aug 26 22:45:45 2007 From: daniels at dsl-only.net (Scott David Daniels) Date: Sun, 26 Aug 2007 19:45:45 -0700 Subject: beginner, idiomatic python In-Reply-To: <13d4bucfm4m1lc4@corp.supernews.com> References: <13cqlqbbpn0dmea@corp.supernews.com> <1187898049.734696.9500@l22g2000prc.googlegroups.com> <13csoronscqp7d2@corp.supernews.com> <1188090322.663217.102750@22g2000hsm.googlegroups.com> <13d4bucfm4m1lc4@corp.supernews.com> Message-ID: <13d4elsj1so0ed3@corp.supernews.com> bambam wrote: > That is, is it defined what Python does for > for i in f() > I'm sure it must be, but I haven't seen it yet. If I have > a user defined function returning a range, is it defined > that the range function is called on every loop? If I > have a function returning a range taking a parameter, > for i in f(v) > is it defined that the variable is evaluated for every loop? Nope. Take the tutorial. for i in f(v): <suite> is the same as: iterator = iter(f(v)) for i in iterator: <suite> -Scott David Daniels Scott.Daniels at Acm.Org From sdeibel at wingware.com Fri Aug 31 13:39:10 2007 From: sdeibel at wingware.com (Stephan Deibel) Date: Fri, 31 Aug 2007 13:39:10 -0400 Subject: Wing IDE 3.0 beta2 released Message-ID: <46D8523E.8030301@wingware.com> Hi, I'm happy to announce the release of Wing IDE 3.0 beta 2. It is available from http://wingware.com/wingide/beta Changes since the previous beta release include: * Stackless Python 2.4 and 2.5 are now supported * Python 2.5 for 64-bit Windows is now supported * Fixed Zope WingDBG so it will connect back to IDE * Improved auto-completion coverage for imports and end cases * Up to 10% speed-up when running in debugger * Fixed many other bugs, particularly source browser, OS commands, testing tool, and source assistant (*) In addition, we have introduced Wing IDE 101, a free scaled back version of Wing IDE designed for teaching introductory programming courses. The CHANGELOG.txt file in the installation provides additional details. The major new features introduced in Wing 3.0 are: * Multi-threaded debugger * Debug value tooltips in editor, debug probe, and interactive shell * Autocompletion in debug probe and interactive shell * Automatically updating project directories * Testing tool, currently supporting unittest derived tests (*) * OS Commands tool for executing and interacting with external commands (*) * Rewritten indentation analysis and conversion (*) * Introduction of Wing IDE 101, a free edition for beginning programmers * Available as a .deb package for Debian and Ubuntu * Support for Stackless Python * Support for 64 bit Python on Windows and Linux (*)'d items are available in Wing IDE Professional only. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Compatibility Notes ------------------- The file pattern in the Testing tab of Project Properties will need to be re-entered if the project was saved with one of the 3.0 alpha releases. Reporting Bugs -------------- Please report bugs using the Submit Bug Report item in the Help menu or by emailing support at wingware dot com. This is beta quality software that installs side-by-side with Wing 2.x or 1.x. We advise you to make frequent backups of your work when using any pre-release version of Wing IDE. Upgrading --------- To upgrade a 2.x license or purchase a new 3.x license: Upgrade https://wingware.com/store/upgrade Purchase https://wingware.com/store/purchase Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. If you are not ready to upgrade, feel free to keep using a series of trial licenses. There will be no limit on the number of trials until 3.0 final is out. Thanks! The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From bignose+hates-spam at benfinney.id.au Thu Aug 30 04:00:37 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 30 Aug 2007 18:00:37 +1000 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <87hcmhebwv.fsf@benfinney.id.au> <5jn9qgFdmbcU3@mid.uni-berlin.de> Message-ID: <87d4x5e9ju.fsf@benfinney.id.au> Marc 'BlackJack' Rintsch <bj_666 at gmx.net> writes: > On Thu, 30 Aug 2007 17:09:36 +1000, Ben Finney wrote: > > It's letting you know that the item isn't in the list. There's no > > sensible return value from an "index" function in that condition. > > What about -1? C programmers do this all the time. :-) I don't believe you've contradicted me :-) -- \ "If you ever drop your keys into a river of molten lava, let | `\ 'em go, because, man, they're gone." -- Jack Handey | _o__) | Ben Finney From thorsten at thorstenkampe.de Sat Aug 11 17:51:31 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 11 Aug 2007 22:51:31 +0100 Subject: python 2.5 bug References: <1186825286.493878.80380@l70g2000hse.googlegroups.com> <5i5fktF3ml00gU1@mid.uni-berlin.de> <1186826980.346619.287670@r34g2000hsd.googlegroups.com> <46bdfb3f$0$5102$ba4acef3@news.orange.fr> <MPG.2128171394cc51d9989700@news.individual.de> <1186861838.057027.179250@l70g2000hse.googlegroups.com> Message-ID: <MPG.21283fc045aba712989701@news.individual.de> * (Sat, 11 Aug 2007 12:50:38 -0700) > On 11 kol, 20:58, Thorsten Kampe <thors... at thorstenkampe.de> wrote: > > * Laurent Pointal (Sat, 11 Aug 2007 20:09:03 +0200) > > > vedrandeko... at v-programs.com wrote: > > > > On 11 kol, 11:59, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote: > > > >> On Sat, 11 Aug 2007 02:41:26 -0700, vedrandekovic wrote: > > > >> > I was install Python 2.5 and uninstall Python 2.4 now I cannot run my > > > >> > scripts, only from idle > > > > > IMHO Python 2.4 was registered for .py files, Python 2.5 take precedence > > > when installed, but when Python 2.4 has been removed, it remove .py files > > > association too (so break Python 2.5 association). > > > > > * manually associate .py/.pyc/.pyo files to python.exe, .pyw files to > > > pythonw.exe. > > > > > * or reinstall Python 2.5 so that it re-setup ad-hoc associations. > > > > Yeah. Did the Original Poster mention any details about his problem. > > Like - for instance - that he's using Windows? > > > Now I was restart my windows and python 2.5 also.Now everything works > fine except python and py2exe script install ( of course something > must destroy my day ) now when I run: > > $ cd c:\Python25\Lib\site-packages\ > $ python mysetup.py py2exe > 'python' is not recognized as an internal or external command, > operable program or batch file. > > why? Because the directory containing python.exe is not in your path. By the way: the Python installation routine doesn't modify your path so it is likely unrelated to that. T. From bbxx789_05ss at yahoo.com Thu Aug 30 16:30:27 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 30 Aug 2007 13:30:27 -0700 Subject: gc.garbage In-Reply-To: <mailman.157.1188499024.28954.python-list@python.org> References: <1188467173.708043.44800@w3g2000hsg.googlegroups.com> <46D692FC.4030805@v.loewis.de> <1188498335.633506.90050@q4g2000prc.googlegroups.com> <mailman.157.1188499024.28954.python-list@python.org> Message-ID: <1188505827.505656.243400@z24g2000prh.googlegroups.com> On Aug 30, 12:36 pm, "Chris Mellon" <arka... at gmail.com> wrote: > On 8/30/07, 7stud <bbxx789_0... at yahoo.com> wrote: > > > On Aug 30, 3:50 am, "Martin v. L?wis" <mar... at v.loewis.de> wrote: > > > > gc.set_debug(gc.DEBUG_LEAK) > > > > print gc.garbage > > > > > --output:-- > > > > [] > > > > gc: uncollectable <Dog 0x56e10> > > > > gc: uncollectable <Cat 0x56e30> > > > > gc: uncollectable <dict 0x58270> > > > > gc: uncollectable <dict 0x43e40> > > > > gc.garbage is filled only after these messages > > > are printed, not before. You need to add an explicit > > > call to gc.collect() if you want to see what > > > uncollectable garbage you have. > > > > Regards, > > > Martin > > > Hi, > > > Thanks for the response. I had a cut and paste error in my reply, so > > here it is again with the corrections... > > > Now, if I run the code: > > > ------------ > > import gc > > > class Cat(object): > > def __del__(): > > pass > > > class Dog(object): > > def __del__(): > > pass > > > def some_func(): > > the_dog = Dog() > > the_cat = Cat() > > the_dog.cat = the_cat > > the_cat.dog = the_dog > > > some_func() > > > gc.set_debug(gc.DEBUG_LEAK) > > gc.collect() > > print gc.garbage > > ----------- > > > I get this output: > > > ---------- > > gc: uncollectable <Dog 0x56e10> > > gc: uncollectable <Cat 0x56e30> > > gc: uncollectable <dict 0x58300> > > gc: uncollectable <dict 0x43e40> > > [<__main__.Dog object at 0x56e10>, <__main__.Cat object at 0x56e30>, > > {'cat': <__main__.Cat object at 0x56e30>}, {'dog': <__main__.Dog > > object at 0x56e10>}] > > ----------- > > > Why are there two entries in the list for each uncollectable > > object(same addresses)? Also, I haven't bound the names "cat" or > > "dog" anywhere in my program. What do those names mean in the list? > > Read your output carefully! > > gc.garbage is a list of objects. The objects are printed just as they > would be anywhere else in Python. You've got the dog object, the cat > object, and the __dict__ of each instance. > > Ah. I missed the braces inside the list, but I still don't understand where the names "cat" and "dog" come from. > DEBUG_SAVEALL is set, then all unreachable objects will be added to > this list rather than freed." What is the definition of an "unreachable object"? If I add the following: ----- y = Cat() del y ----- That object doesn't make it into gc.garbage. From steve at holdenweb.com Sat Aug 4 09:12:23 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 04 Aug 2007 09:12:23 -0400 Subject: bias in random.normalvariate?? In-Reply-To: <f912rl$50u$1@sea.gmane.org> References: <1186198720.800007.38800@k79g2000hse.googlegroups.com> <f912rl$50u$1@sea.gmane.org> Message-ID: <f91tvn$uj9$1@sea.gmane.org> Robert Kern wrote: > drewlist at gmail.com wrote: >> I'm a Python newbie and certainly no expert on statistics, but my wife >> was taking a statistics course this summer and to illustrate that >> sampling random numbers from a distribution and taking an average of >> the samples gives you a random number as the result (bigger sample -> >> smaller variance in the calculated random number, converging in on the >> mean of the original distribution), I threw together this program: >> >> #! /usr/bin/python >> >> import random; >> >> i=1 >> samplen=100 >> mean=130 >> lo=mean >> hi=mean >> sd=10 >> sum=0 >> while(i<=samplen): >> x=random.normalvariate(mean,sd) >> #print x >> if x<lo: lo=x >> if x>hi: high=x >> sum+=x >> i+=1 >> print 'sample mean=', sum/samplen, '\n' >> print 'low value =', lo >> print 'high value=', high > > Your code has an error. In the middle of your code, you changed "hi" to "high". > Which very nicely makes the point that you can test algorithms driven by random data using statistical functions on the output! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From iddw at hotmail.com Tue Aug 21 14:25:29 2007 From: iddw at hotmail.com (Dave Hansen) Date: Tue, 21 Aug 2007 11:25:29 -0700 Subject: Newbee Question In-Reply-To: <13cl6nes7skrh75@corp.supernews.com> References: <mailman.15.1187620149.26576.python-list@python.org> <1187621470.484615.7010@i13g2000prf.googlegroups.com> <13cl6nes7skrh75@corp.supernews.com> Message-ID: <1187720729.970795.112680@i38g2000prf.googlegroups.com> On Aug 21, 2:57 am, Dennis Lee Bieber <wlfr... at ix.netcom.com> wrote: [...] > > pay = min(num, 22) * 0.4 + max(num-22, 0) * 1.4 pay = num*0.4 + (num>22)*(num-22) ;-) -=Dave From jstroud at mbi.ucla.edu Thu Aug 9 21:28:35 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 09 Aug 2007 18:28:35 -0700 Subject: beginner whitespace question In-Reply-To: <1186708404.901323.204730@g12g2000prg.googlegroups.com> References: <1186703261.136506.208660@x35g2000prf.googlegroups.com> <1186703525.591462.122140@m37g2000prh.googlegroups.com> <1186704161.334597.218750@z24g2000prh.googlegroups.com> <1186707164.095766.243480@q3g2000prf.googlegroups.com> <1186708404.901323.204730@g12g2000prg.googlegroups.com> Message-ID: <f9gf03$3al$1@daisy.noc.ucla.edu> eggie5 wrote: > But this still isn't valid: > > from django.db import models > > class Poll(models.Model): > question = models.CharField(max_length=200) > pub_date = models.DateTimeField('date published') > > def __unicode__(self): > return self.question > > > > class Choice(models.Model): > poll = models.ForeignKey(Poll) > choice = models.CharField(max_length=200) > votes = models.IntegerField() > > def __unicode__(self): > return self.choice You want this: from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField() def __unicode__(self): return self.choice But this mixes tabs and spaces. Rules: 1. Don't use tabs! 2. If you are clueless enough to violate (1), then don't mix tabs and spaces. 3. Don't use tabs! Tabs are for tables, hence the name. "Use spaces for space and use tabs for tables" can be a little mnemonic to help you remember the rules. We can make a little song together if you can think of some things that rhyme with "don't" and "use" and "tabs". You have been warned. Next time I'll piont and laugh as I answer. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From dieter_vanderelst at emailengine.org Tue Aug 14 13:26:05 2007 From: dieter_vanderelst at emailengine.org (Dieter Vanderelst) Date: Tue, 14 Aug 2007 19:26:05 +0200 Subject: pil_usm for python 2.5? Message-ID: <1187112365.2431.1205363633@webmail.messagingengine.com> Hi list, Does anybody have a version of pil_usm (module for gaussian blurring) that is compiled for Python 2.5? Regards, Dieter -- Dieter Vanderelst d.vanderelst at tue.nl Department of Industrial Design Designed Intelligence -- Dieter Vanderelst dieter_vanderelst at emailengine.org From cai.haibin at gmail.com Wed Aug 1 22:16:59 2007 From: cai.haibin at gmail.com (james_027) Date: Thu, 02 Aug 2007 02:16:59 -0000 Subject: access the name of my method inside it In-Reply-To: <1185959202.302467.276080@x35g2000prf.googlegroups.com> References: <1185959202.302467.276080@x35g2000prf.googlegroups.com> Message-ID: <1186021019.073479.287410@i13g2000prf.googlegroups.com> Hi all! Thanks for all your idea, this community is truly a great one! james From Lost at inhere.com Mon Aug 27 09:18:06 2007 From: Lost at inhere.com (Lost in the Wasteland) Date: Mon, 27 Aug 2007 08:18:06 -0500 Subject: Let's Unite Against Jews and Mongrels! In-Reply-To: <1188198797.772672.60840@r29g2000hsg.googlegroups.com> References: <1188198797.772672.60840@r29g2000hsg.googlegroups.com> Message-ID: <1188220560_8937@sp12lax.superfeed.net> Nenad Milicevic - The Aryan Serb wrote: > Belgrade, Serbia > Looks like a nice place to vacation. ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From tjreedy at udel.edu Mon Aug 20 17:30:48 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 20 Aug 2007 17:30:48 -0400 Subject: str().join() isn't working References: <496954360708200905i2100b32ag5983ab729e5d216f@mail.gmail.com><mailman.4.1187633821.32294.python-list@python.org><1187634895.387910.179500@m37g2000prh.googlegroups.com> <496954360708201249y1db0aa14qf0de14538fb51b9d@mail.gmail.com> Message-ID: <fad17f$252$1@sea.gmane.org> "Robert Dailey" <rcdailey at gmail.com> wrote in message news:496954360708201249y1db0aa14qf0de14538fb51b9d at mail.gmail.com... | Hi all, | | Thanks for your response. I figured out the issue. I was using | list.append() to append another list, when I should have been using | expand(). Sorry for the confusion. The method is .extend, not .expand ;=) From carsten at uniqsys.com Fri Aug 31 22:13:16 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 31 Aug 2007 22:13:16 -0400 Subject: list index() In-Reply-To: <fbagd1$gnm$4@lust.ihug.co.nz> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <46d674c2$0$417$426a34cc@news.free.fr> <1188496588.750629.208100@g4g2000hsf.googlegroups.com> <mailman.154.1188497511.28954.python-list@python.org> <1188498073.997168.282420@q5g2000prf.googlegroups.com> <mailman.156.1188498891.28954.python-list@python.org> <fbagd1$gnm$4@lust.ihug.co.nz> Message-ID: <1188612796.3259.3.camel@localhost.localdomain> On Sat, 2007-09-01 at 13:50 +1200, Lawrence D'Oliveiro wrote: > In message <mailman.156.1188498891.28954.python-list at python.org>, Carsten > Haese wrote: > > has_key() will go away, period. It has been made obsolete by "in", which > > is faster and more concise. > > And is also a backdoor way of introducing non-virtual methods into Python, > is it not. If by that you mean that "in" tests can't be overridden, that's not true: >>> class LyingDict(dict): ... def __contains__(self, key): return False ... >>> d = LyingDict() >>> d[1] = 42 >>> 1 in d False If you mean something else, please clarify. -- Carsten Haese http://informixdb.sourceforge.net From lasses_weil at klapptsowieso.net Thu Aug 30 18:03:38 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Fri, 31 Aug 2007 00:03:38 +0200 Subject: Setting a read-only attribute In-Reply-To: <1188510690.622808.247220@z24g2000prh.googlegroups.com> References: <1188509700.915517.178440@z24g2000prh.googlegroups.com> <1188510690.622808.247220@z24g2000prh.googlegroups.com> Message-ID: <46d73eba$0$4516$9b4e6d93@newsspool3.arcor-online.net> Arnaud Delobelle wrote: > On Aug 30, 10:35 pm, "tleeuwenb... at gmail.com" <tleeuwenb... at gmail.com> > wrote: >> I have an object and wish to set an attribute on it which, >> unfortunately for me, is read-only. > > If it's read-only then you can't set it! > >> How can I go about this? > > Joke aside, I think you need to be more specific. > To be more specific about much more specific you should be: If you know the exact problem/hurdle you have to overcome, explain it. Otherwise kindly provide the traceback (error message) you get when attempting to set the attribute. /W From http Sat Aug 11 08:05:40 2007 From: http (Paul Rubin) Date: 11 Aug 2007 05:05:40 -0700 Subject: LRU cache? Message-ID: <7x8x8ixomj.fsf_-_@ruckus.brouhaha.com> Anyone got a favorite LRU cache implementation? I see a few in google but none look all that good. I just want a dictionary indexed by strings, that remembers the last few thousand entries I put in it. It actually looks like this is almost a FAQ. A well-written implementation would probably make a good standard library module. From hancock.robert at gmail.com Mon Aug 13 17:58:10 2007 From: hancock.robert at gmail.com (milan_sanremo) Date: Mon, 13 Aug 2007 21:58:10 -0000 Subject: chmod g+ Equivalent Message-ID: <1187042290.821786.178420@19g2000hsx.googlegroups.com> I've read the documentation on os.chmod() and can implement all the standard commands, but what is the syntax for the equivalent of chmod g + to set the group id? From jstroud at mbi.ucla.edu Thu Aug 16 19:21:00 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 16 Aug 2007 16:21:00 -0700 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: <1187303750.590497.208060@x40g2000prg.googlegroups.com> References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> Message-ID: <fa2m4s$k1g$1@daisy.noc.ucla.edu> beginner wrote: > Hi All. > > I'd like to do the following in more succint code: > > if k in b: > a=b[k] > else: > a={} > b[k]=a > > a['A']=1 > > > In perl it is just one line: $a=$b->{"A"} ||={}. I'm afraid you've asked a non sequiter: euler 40% cat test.pl $a=$b->{"A"} ||={} ; print "$a\n" ; $b->{"B"} = 0 ; $a=$b->{"B"} ||={} ; print "$a\n" ; $b->{"X"} = 15 ; $a=$b->{"X"} ||={} ; print "$a\n" ; euler 41% perl test.pl HASH(0x92662a0) HASH(0x926609c) 15 James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From naga86 at gmail.com Thu Aug 23 06:20:21 2007 From: naga86 at gmail.com (Nagarajan) Date: Thu, 23 Aug 2007 10:20:21 -0000 Subject: Raw strings to normal strings conversion? In-Reply-To: <5j534qF3qf8ssU2@mid.uni-berlin.de> References: <1187851660.209024.59860@l22g2000prc.googlegroups.com> <Xrbzi.21051$eY.3412@newssvr13.news.prodigy.net> <1187860900.740674.87180@e9g2000prf.googlegroups.com> <5j534qF3qf8ssU2@mid.uni-berlin.de> Message-ID: <1187864421.890009.326890@e9g2000prf.googlegroups.com> On Aug 23, 2:42 pm, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote: > On Thu, 23 Aug 2007 09:21:40 +0000, Nagarajan wrote: > > On Aug 23, 1:21 pm, James Stroud <jstr... at mbi.ucla.edu> wrote: > >> Nagarajan wrote: > >> > Is there a way by which I could obtain normal string form of a raw > >> > string. > >> > XML CDATA is returned as raw string. But I need the string to actually > >> > escape special chars. > > >> > Any idea? > > >> This doesn't seem clear. Perhaps an example of what you get and what you > >> want it converted to. > > > Here is an example: > >>> rawstr = r'a\nb' > >>> print rawstr > > a\nb > > > Now I need this newstr to actually interpret '\n', in other words, to > > behave like a normal string. > > So you get a string with Newlines as two character sequence \n. You don't > get "raw" strings. That is a concept in Python source code. When the > program is running there is no such distinction between "raw" and "normal" > strings. Here's a solution: > > In [87]: print r'a\nb' > a\nb > > In [88]: print r'a\nb'.decode('string-escape') > a > b > > Ciao, > Marc 'BlackJack' Rintsch Thanks a lot. From wildemar at freakmail.de Mon Aug 13 05:33:14 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 13 Aug 2007 11:33:14 +0200 Subject: Adventure-Engines in Python Message-ID: <46C0255A.4080707@freakmail.de> Are there any? I've set out to make an adventure game and now I'm trying to find a set of python-modules to help me do that. I know of the usual non-python suspects (AGAST, AGS, Wintermute, ...) and while I they are really good, I'd like one that is cross platform. I've found pyScumm and pyAdv but both don't seem to be ready for use yet. So are there any "usable" engines written in python? /W From fperez.net at gmail.com Thu Aug 2 14:32:43 2007 From: fperez.net at gmail.com (Fernando Perez) Date: Thu, 02 Aug 2007 12:32:43 -0600 Subject: Bug in execfile? Message-ID: <f8t80e$gvh$1@sea.gmane.org> Hi all, I'm finding the following behavior truly puzzling, but before I post a bug report on the site, I'd rather be corrected if I'm just missing somethin obvious. Consider the following trivial script: # Simple script that imports something from the stdlib from math import sin, pi wav = lambda k,x: sin(2*pi*k*x) print wav(1,0.25) # EOF The above runs just fine from a prompt, or even interactively via execfile(). Now, consider calling it by using this instead: #!/usr/bin/env python """Test for a bug (?) in scope handling by the execfile() builtin.""" def runscript(fname): """Run a file by calling execfile().""" execfile(fname) # Note: if you activate this section so that execfile() is directly called # first, then the bug below disappears!!! if 0: print '='*80 print '# Trying execfile:' execfile('execfilebugscript.py') # The bug: we get an exception from running the little script, where the 'sin' # name imported from math is not visible to the lambda. print '-'*80 print '# Trying the runscript wrapper:' runscript('execfilebugscript.py') ##### EOF If I run the above, calling the first script 'execfilebugscript.py' and the second 'execfilebug.py', I get this: planck[test]> ./execfilebug.py -------------------------------------------------------------------------------- # Trying the runscript wrapper: Traceback (most recent call last): File "./execfilebug.py", line 21, in <module> runscript('execfilebugscript.py') File "./execfilebug.py", line 7, in runscript execfile(fname) File "execfilebugscript.py", line 6, in <module> print wav(1,0.25) File "execfilebugscript.py", line 4, in <lambda> wav = lambda k,x: sin(2*pi*k*x) NameError: global name 'sin' is not defined WTF??? Now even weirder, if the 'if 0' is turned into 'if 1' so that *first* execfile is called at the top-level (not inside a function), then *both* calls work: planck[test]> ./execfilebug.py ================================================================================ # Trying execfile: 1.0 -------------------------------------------------------------------------------- # Trying the runscript wrapper: 1.0 I'm really, really puzzled by this. From reading the execfile() docs, I had the hunch to change the call to: execfile(fname,{}) and now the problem disappears, so I can keep on working. But I'm still very bothered by the fact that changing that first call 'if 0' to 'if 1' has any effect on the later call to runscript(). That really doesn't feel right to me... Any wisdom will be much appreciated. Cheers, f From conspiracy.black3 at gmail.com Wed Aug 8 15:08:45 2007 From: conspiracy.black3 at gmail.com (conspiracy.black3 at gmail.com) Date: Wed, 08 Aug 2007 12:08:45 -0700 Subject: Google Conspiracy Revealed! Message-ID: <1186600125.435154.68910@m37g2000prh.googlegroups.com> http://www.nasaconspiracy.net/2007/06/content-generator-recognizing-generated.html - Amazing Google Conspiracies Revealed from CIA, NSA and Government conspiracies and Dr.Kevorkians magic pills. From kar1107 at gmail.com Tue Aug 21 23:58:13 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Tue, 21 Aug 2007 20:58:13 -0700 Subject: Chaining programs with pipe In-Reply-To: <13cnbl0p9qf26e0@corp.supernews.com> References: <1187734166.384152.178040@o80g2000hse.googlegroups.com> <1187743235.124030.321200@l22g2000prc.googlegroups.com> <13cnbl0p9qf26e0@corp.supernews.com> Message-ID: <1187755093.138467.71270@x35g2000prf.googlegroups.com> On Aug 21, 8:33 pm, Grant Edwards <gra... at visi.com> wrote: > On 2007-08-22, Karthik Gurusamy <kar1... at gmail.com> wrote: > > > Not sure on non-unix platforms, but in unix like platforms it's best > > to reuse shell's power. > > >>>> import commands > >>>> commands.getoutput('ls | wc') > > ' 4 4 24' > > Executing a shell just because you want a pipe seems like a bit > of overkill. Doing it the "right" way with subprocess is > pretty trivial. Probably I should've put extra stress on the word "reuse". The example quoted was trivial; if you replace the pipeline to have say 5 processes, the advantage of not-reinventing the wheel becomes more obvious. I would call hand-crafting the pipe-setup an "overkill" when a very good solution already exists to solve the problem. Yes, it may be trivial to do; but not simpler than delegating to a shell. Karthik > > -- > Grant Edwards grante Yow! I was born in a > at Hostess Cupcake factory > visi.com before the sexual > revolution! From pavlovevidence at gmail.com Mon Aug 27 19:21:43 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 27 Aug 2007 16:21:43 -0700 Subject: "Try:" which only encompasses head of compound statement In-Reply-To: <1188250535.607963.42540@22g2000hsm.googlegroups.com> References: <1188250535.607963.42540@22g2000hsm.googlegroups.com> Message-ID: <1188256903.075011.173820@k79g2000hse.googlegroups.com> On Aug 27, 5:35 pm, Jameson.Qu... at gmail.com wrote: > I have: > > try: > for line in open(myFileName): > count += 1 > except IOError: > print "Can't open myfile" > > (I know, this is bad, I never close the file, but its just for > illustration). But then I change it to: > > try: > for line in open(myFileName): > count += openAndProcessSubfile(line) > except IOError: > print "Can't open myfile" > > ... now the 'except' incorrectly catches errors from > openAndProcessSubfile. > Of course, I can always do: > > try: > myFile = open(myFileName) > except IOError: > print "Can't open myfile" > for line in myFile: > count += openAndProcessSubfile(line) > > ...But if my compound statement is "with" instead of "for" that seems > to defeat the purpose: > > try: > myFile = open(myFileName) > except IOError: > print "Can't open myfile" > with myFile as anotherNameForMyFile: > .... I suspect this isn't often complained about because this usage of try...except kind of misses the boat. The above treats the exception as nothing more than an error return code, but it's often not optimal to handle error so close to the call. The best reason to catch and handle an exception very close to the call is if you intend to recover from it right away. For example: try: f = open("fileA") except IOError: f = open("fileB") If you don't intend to recover right away, it's usually better to let the exception propogate until up the call chain until the point where you do want to recover. Consider this: is there any other code in your program that has to do something different based on whether you successfully opened this file or not? If so, how will you notify it whether the call has succeeded or not? Very often, the caller itself needs to know. You could, say, set a flag to indicate it's failed, but why do that when you could simply let the caller detect and handle the error itself? If you don't intend to recover at all, you should let it propogate up to the point where you will resume normal processing (for example: before the next input prompt), and handle it there. Especially if you're going to print an error message: printing an error message at the point the error occurs can severely limit code reusability. Enough rambling. Here's what I'd do in your situation: nothing. Don't handle the exception here at all. Let it raise IOError. My code would look like this: with open('myFile') as myFile: .... However, I would handle the exeption wherever I intended to take action based on success or failure. It looks like you are treating "file-not-found" as non-fatal, and other IOErrors as fatal? In that case, we would have to check the error code to distinguish, and reraise if not file not found. # this is the point where success or failure # determines what I do next, that's why I handle # the exception here. try: load_myFile() except IOError, e: if e.errno == 2: # file not found is usually errno 2 print "file not found" else: raise else: # load succeeded, do whatever. One other useful technique is recasting: catching an error close to the call, and raising a different error. Carl Banks From carsten at uniqsys.com Wed Aug 8 09:52:04 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 08 Aug 2007 09:52:04 -0400 Subject: Something in the function tutorial confused me. In-Reply-To: <f9ceb9$jsm$1@sea.gmane.org> References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <slrnfbe1fd.n4.horpner@FIAD06.norwich.edu> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <slrnfbeofu.20s.horpner@FIAD06.norwich.edu> <1186424693.529497.217040@w3g2000hsg.googlegroups.com> <46B8626A.2070303@bigfoot.com> <mailman.1726.1186537161.22759.python-list@python.org> <5hsoi3F3mlni2U1@mid.individual.net> <f9ceb9$jsm$1@sea.gmane.org> Message-ID: <1186581124.3383.55.camel@dot.uniqsys.com> On Wed, 2007-08-08 at 08:52 -0400, Steve Holden wrote: > While it's correct that rebinding y will usually cause it to reference a > different object, this need not be true of assignment. The augmented > assignment operations do no necessarily rebind their left-hand operand - > that depends on the implementation of the relevant method in whatever > type is the subject of the augmented assignment. > > An *assignment* to y therefore *usually* rebinds the name y to point to > a different value. You are certainly correct within the bounds of the terminology you're using, but I think some clarifications are necessary. The language reference draws a clear distinction between assignments and augmented assignments. In an augmented assignment, the difference between a mutable target and a non-mutable target is indeed of utmost relevance. However, drawing this distinction into a discussion about what *assignments* will and won't do is confusing matters. In a "plain" assignment of the form "name = expression", the mutability of the object that the name is pointing to, if any, does not matter. I believe that that was the point greg was trying to make when he objected to this statement of yours: """ When the function starts out with None as y's value any assignment to y causes it to reference a different value (since None is immutable). So the next time the function is called y is pointing at the None that it was pointing at the last time the function was called (since None cannot be mutated). """ The problem is your ambiguous use of the word "assignment." In the sense of the Language Reference, "any assignment to y" is a simple assignment that always modifies a namespace and never modifies an object. In that sense, the mutability of None really isn't the issue. If you use the broader sense in which "assignment" includes augmented assignments, the mutability of None does become relevant. I agree that greg's delivery was unduly disrespectful, but I think he was making a valid point. Hope this helps clear up the confusion. Best regards, -- Carsten Haese http://informixdb.sourceforge.net From BerndWill at googlemail.com Sat Aug 11 06:00:10 2007 From: BerndWill at googlemail.com (OpenPavilion) Date: Sat, 11 Aug 2007 10:00:10 -0000 Subject: question: howto transfer objects between server and client? In-Reply-To: <46bd7faa$0$239$e4fe514c@news.xs4all.nl> References: <1186823076.923464.294120@57g2000hsv.googlegroups.com> <46bd7faa$0$239$e4fe514c@news.xs4all.nl> Message-ID: <1186826410.019139.121680@l70g2000hse.googlegroups.com> On 11 Aug., 11:21, Irmen de Jong <irmen.NOS... at xs4all.nl> wrote: > OpenPavilion wrote: > > Since XMLRPC has limited features: Is there any other server/client > > technique to transfer objects (not strings, or dictionaries, but self > > defined object types) ? > > Take a look at Pyro; http://pyro.sourceforge.net > > --Irmen Thanks Irmen, just found out, that if I use "pickle.dumps(object)" (on client side) and "pickle.loads(object)" (on server side) before and after sending, I have access to the object. I love this python language ! Python is a really, really nice language and I often find that the solution is easier as I thought in the first place ... Thanks anyway !! Regards Bernd From a.harrowell at gmail.com Fri Aug 17 08:38:16 2007 From: a.harrowell at gmail.com (TYR) Date: Fri, 17 Aug 2007 12:38:16 -0000 Subject: Naming dictionaries recursively Message-ID: <1187354296.177606.273300@22g2000hsm.googlegroups.com> I'd like to do something like this; iterate through a file which consists of data stored in dictionary format, one dict on each line, and read each line into a new dict using one of the values in the dict as its name... for example: stuff = open('data.txt') for eachLine in stuff: name{} name = eachLine ....and then do something clever to extract the value of the key (name) from the line and use it as the dictionary's name. A line from data.txt would look like this: {'name' : Bob, 'species' : Humboldt, 'colour' : red, 'habits' : predatory}. Aim is to call one of them by name, and merge the values in that dictionary into a string pulled from another source. From aleax at mac.com Fri Aug 17 23:00:06 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 17 Aug 2007 20:00:06 -0700 Subject: Can python threads take advantage of use dual core ? References: <1187366443.621295.97020@e9g2000prf.googlegroups.com> <5ilvg4F3pqv6aU1@mid.uni-berlin.de> <46c5c924$0$7688$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <1i309vp.8k7vpd1g1ulkgN%aleax@mac.com> Stefan Behnel <stefan.behnel-n05pAM at web.de> wrote: ... > Which virtually all computation-intensive extensions do. Also, note the gmpy doesn't (release the GIL), even though it IS computationally intensive -- I tried, but it slows things down horribly even on an Intel Core Duo. I suspect that may partly be due to the locking strategy of the underlying GMP 4.2 library (which I haven't analyzed in depth). In practice, when I want to exploit both cores to the hilt with gmpy-based computations, I run multiple processes. Alex From jstroud at mbi.ucla.edu Fri Aug 24 16:44:26 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 24 Aug 2007 13:44:26 -0700 Subject: Co-developers wanted: document markup language In-Reply-To: <87y7g0udnp.fsf@wilson.homeunix.com> References: <87odgyyx9u.fsf@wilson.homeunix.com> <87tzqpew22.fsf@wilson.homeunix.com> <fal3cv$bi2$1@panix3.panix.com> <87tzqp77my.fsf@wilson.homeunix.com> <famljb$1d9$1@panix3.panix.com> <87y7g0udnp.fsf@wilson.homeunix.com> Message-ID: <fanfva$23k$1@daisy.noc.ucla.edu> Torsten Bronger wrote: > Reading only forums and newsgroups, one may think that this is > impossible but in real life, I've seen more people using LaTeX > exactly once and never again than people who keep using it. This is funny. I developed a pretty good competence in LaTeX to write my thesis (which thanks to LaTeX, looked beautiful) and never once used LaTeX again. The biggest hurdle to these markup languages is collaborative documents and that LaTeX and the like are impossible for collaborators to learn. Yes, impossible, in the 0%-chance-of-ever-happening meaning. So you get stuck with Word. This is the reality once you are passed writing term papers. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From mcl.office at googlemail.com Sun Aug 19 16:36:32 2007 From: mcl.office at googlemail.com (mosscliffe) Date: Sun, 19 Aug 2007 13:36:32 -0700 Subject: 1)URL QueryString Parsing 2)Search Engine Spiders In-Reply-To: <f4Xxi.28397$RX.20357@newssvr11.news.prodigy.net> References: <1187513415.188232.187270@50g2000hsm.googlegroups.com> <f4Xxi.28397$RX.20357@newssvr11.news.prodigy.net> Message-ID: <1187555792.508140.125300@a39g2000hsc.googlegroups.com> On 19 Aug, 13:54, samwyse <dejan... at email.com> wrote: > mosscliffewrote: > > I am trying to create a back link, equivalent to the browser back > > action and I can not use java script. The target user does not allow > > java script. > > > I am using HTTP_REFERER. > > > I need to add the original Query String values. > > > Is there a way to get the QueryString element other than by using > > cgi.FieldStorage, as I just want to return with the values that were > > current in the calling page. > > > gv.orgQueryString = "" > > > gv.BackButton = '<A href="' + os.environ.get("HTTP_REFERER") + > > gv.orgQueryString + '">BACK</A>' > > I'm not sure I understand your problem. Does the above code not work? > > > Am I right in thinking Search Engine Spiders will never see my script > > pages as they exist only for the duration of the python script's > > execution ? And even then as they are xxx.py, they would not be > > seen. > > Anyone who accesses your web server will see the pages that you serve. > If you serve the xxx.py files, then they can be seen and indexed, > otherwise they are invisible. I currently have to build the query string from each field passed. I was hoping I could somehow just split the query string. something like TheQueryStribgBit = FullURL.split("&") but I can't find a reference to FullURL with os.environ's I apologise for my lack of clarity - the grey matter is getting a bit long in the tooth. Richard From python at jayloden.com Mon Aug 20 16:11:13 2007 From: python at jayloden.com (Jay Loden) Date: Mon, 20 Aug 2007 16:11:13 -0400 Subject: reading a line in file In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE2B6@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE2B2@efmailx><2dc0c81b0708201029k5909d919vcf0deebae74a79c7@mail.gmail.com><93066C069973ED448DC2BCEA9C44A7383BE2B4@efmailx> <2dc0c81b0708201207p7f83f2e0l6de15fd70be252a5@mail.gmail.com> <93066C069973ED448DC2BCEA9C44A7383BE2B6@efmailx> Message-ID: <46C9F561.50405@jayloden.com> Brian McCann wrote: > Shawn, Tim ,Jay > > many thanks, > > It looks like there are many ways this problem can be approached > > either by using regex or a tokens > > Tim I'm not familiar with your solution, but will learn about that > method also > Jay, what do you mean by regex comes with a lot of overhead? > --Brian Regular expression parsing can have a lot of overhead, i.e. processing power/memory usage so it's recommended that they only be used when actually needed. If you only have to search for a very specific set of text or manipulate text that is very rigidly, then there's little benefit to including regular expressions. By comparison, if you have a need to match a lot of various cases or conditions, a regular expression can be by far the more efficient or logical method to use. -Jay From jstroud at mbi.ucla.edu Sat Aug 4 04:52:28 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 04 Aug 2007 08:52:28 GMT Subject: How to pass a reference to the current module In-Reply-To: <pan.2007.08.04.04.56.18.773038@REMOVE.THIS.cybersource.com.au> References: <f90gsg$ek4$1@zinnia.noc.ucla.edu> <pan.2007.08.04.01.46.50.985228@REMOVE.THIS.cybersource.com.au> <f90lon$av5$1@daisy.noc.ucla.edu> <7xtzrg3vof.fsf@ruckus.brouhaha.com> <f90tvv$nt7$2@zinnia.noc.ucla.edu> <pan.2007.08.04.04.56.18.773038@REMOVE.THIS.cybersource.com.au> Message-ID: <g7Xsi.43654$Um6.2191@newssvr12.news.prodigy.net> Steven D'Aprano wrote: > I suggest you're falling for the anti-pattern of "Big Design Up Front", > and are overly complicating your system "just in case it's useful". Why > not just _insist_ that main.py and UserDefined1.py must be different > modules? You're the application developer, you're allowed to do that. The idea of the module I'm writing is to allow the user to define functions where they want and to create single-file python scripts that can make use of my API. The point of the module is to be beginner friendly, but maybe that is asking too much as user friendliness might be a potentially useful but provably unnecessary attribute. >> 2. foo is defined in `main` > > Maybe you should just prohibit that? Do you really want to allow users to > call arbitrary code in your main application at arbitrary times and places? It would be the user's main and they would be importing my module. I would like my module to be aware of the contents of the user's module. I thought such a thing would be possible because it seems like something similar is happening in distutils py2app. > But in any case, it shouldn't matter. main is the program running -- it > has to be, because you can't import it from another program -- so > globals()['foo'] will work. > > >> Possibility two (even when it is a properly named module) sets the stage >> for a circular import, but I believe in python this is not entirely >> worrisome. However, the combination above makes it difficult to pass a >> reference to the `main` namespace without some sort of introspection. > > That's what globals() is for. On second thought this might not be horribly bad: FunctionUser.do_something_with(globals(), 'doit', 7) or FunctionUser.do_something_with(UserDefined1.globals(), 'foo', 7) From a beginner-user's perspective (i.e. potential users of my module), it seems a little awkward, but might be more natural on the whole than the alternatives. However, if I had my druthers, I would rather have some way to pass a reference to the current module in the former case and have do_something_with() call globals(). I really like the idea of having the module or its namespace as an optional argument and implicitly using the calling global namespace if its left out. But perhaps this is bad design from an "explicit is better than implicit" perspective. >> [foo] >> param1 = float >> param2 = 4 >> >> [option1] >> __module__ = 'UserDefined1' >> __function__ = 'doit' > > > I'm not sure why you need the quotation marks around the module and > function names. What else could UserDefined1 be, other than a string? Yes, those were typos. And to be consistent, the whole listing of the configuration file should be (note: 'doit'->do_something_with): [foo] param1 = float param2 = 4 [option1] __module__ = UserDefined1 __function__ = do_something_with param1 = str param2 = 30.0 [doit] param1 = float param2 = float [etc.] With the user's main having the following in it: from UserDefined1 import some_function def foo(): [etc.] def doit(): [etc.] I'm afraid my previous listing of the config file could cause confusion. James From stargaming at gmail.com Wed Aug 1 07:59:32 2007 From: stargaming at gmail.com (Stargaming) Date: 01 Aug 2007 11:59:32 GMT Subject: Python end of file marker similar to perl's __END__ References: <1185940391.135261.130950@i38g2000prf.googlegroups.com> <1185947061.985093.306840@22g2000hsm.googlegroups.com> <46b023ee$0$6528$9b622d9e@news.freenet.de> <mailman.1426.1185965815.22759.python-list@python.org> Message-ID: <46b075a4$0$7447$9b622d9e@news.freenet.de> On Wed, 01 Aug 2007 06:56:36 -0400, Steve Holden wrote: > Stargaming wrote: >> On Wed, 01 Aug 2007 05:44:21 +0000, Michele Simionato wrote: >> >>> On Aug 1, 5:53 am, beginner <zyzhu2... at gmail.com> wrote: >>>> Hi All, >>>> >>>> This is just a very simple question about a python trick. >>>> >>>> In perl, I can write __END__ in a file and the perl interpreter will >>>> ignore everything below that line. This is very handy when testing my >>>> program. Does python have something similar? >>> I wished from something like that. What you can do at the moment, is >>> to comment or triple quote the code you don't want to run. >> >> Or, if in a function body, you could insert a `return` statement. When >> in top-level code, invoking `sys.exit` (or exit/quit) can do the trick. >> A ``raise Exception`` might help, too, but could be kinda distracting >> sometimes. >> >> So, there is no general purpose solution as perl has it (I guess that >> __END__ works everywhere at least), rather different solutions for >> different cases. > > I think you have missed the point. A return statement or call to > sys.exit() doesn't remove the requirement that the rest ofthe source > file be legal Python. In a Perl program you can put anything you like > after __END__. > > regards > Steve That was my point actually. No, there is no such general purpose solution as in perl, but if he just wanted to quit execution (to, eg., not commit changes to his database), this would be the way to go. Multiline strings are the other way to include (nearly) arbitrary data. From jipksaman at gmail.com Sun Aug 26 14:46:07 2007 From: jipksaman at gmail.com (abdo911) Date: Sun, 26 Aug 2007 11:46:07 -0700 Subject: YOU MUST KNOW THIS MAN Message-ID: <1188153967.206797.224850@d55g2000hsg.googlegroups.com> Allow me to share with you here some information about one man his name is muhammad. In The Name Of Allaah, Most Gracious, Most Merciful YOU MUST KNOW THIS MAN MUHAMMAD (May peace and blessings of God Almighty be upon him) You may be an atheist or an agnostic; or you may belong to anyone of the religious denominations that exist in the world today. You may be a Communist or a believer in democracy and freedom. No matter what you are, and no matter what your religious and political beliefs, personal and social habits happen to be - YOU MUST STILL KNOW THIS MAN! He was by far the most remarkable man that ever set foot on this earth. He preached a religion, founded a state, built a nation, laid down a moral code, initiated numberless social and political reforms, established a dynamic and powerful society to practice and represent his teachings, and completely revolutionized the worlds of human thought and action for all times to come. HIS NAME IS MUHAMMAD, peace and blessings of Almighty God be upon him and he accomplished all these wonders in the unbelievably short span of twenty-three years. Muhammad, peace and blessings of God Almighty be upon him was born in Arabia on the 20th of August, in the year 570 of the Christian era, and when he died after 63 years, the whole of the Arabian Peninsula had changed from paganism and idol-worship to the worship of One God; from tribal quarrels and wars to national solidarity and cohesion; from drunkenness and debauchery to sobriety and piety; from lawlessness and anarchy to disciplined living; from utter moral bankruptcy to the highest standards of moral excellence. Human history has never known such a complete transformation of a people or a place before or since! The Encyclopedia Britannica calls him "the most successful of all religious personalities of the world". Bernard Shaw said about him that if Muhammad were alive today he would succeed in solving all those problems which threaten to destroy human civilization in our times. Thomas Carlysle was simply amazed as to how one man, single- handedly, could weld warring tribes and wandering Bedouins into a most powerful and civilized nation in less than two decades. Napoleon and Gandhi never tired of dreaming of a society along the lines established by this man in Arabia fourteen centuries ago. Indeed no other human being ever accomplished so much, in such diverse fields of human thought and behavior, in so limited a space of time, as did Muhammad, peace and blessings of God Almighty be upon him. He was a religious teacher, a social reformer, a moral guide, a political thinker, a military genius, an administrative colossus, a faithful friend, a wonderful companion, a devoted husband, a loving father - all in one. No other man in history ever excelled or equaled him in any of these difficult departments of life. The world has had its share of great personalities. But these were one sided figures who distinguished themselves in but one or two fields such as religious thought or military leadership. None of the other great leaders of the world ever combined in himself so many different qualities to such an amazing level of perfection as did Muhammad, peace and blessings of God Almighty be upon him. The lives and teachings of other great personalities of the world are shrouded in the mist of time. There is so much speculation about the time and the place of their birth, the mode and style of their life, the nature and detail of their teachings and the degree and measure of their success or failure that it is impossible for humanity today to reconstruct accurately and precisely the lives and teachings of those men. Not so this man Muhammad, peace and blessings of God Almighty be upon him. Not only was he born in the fullest blaze of recorded history, but every detail of his private and public life, of his actions and utterances, has been accurately documented and faithfully preserved to our day. The authenticity of the information so preserved is vouched for not only by faithful followers but also by unbiased critics and open-minded scholars. At the level of ideas there is no system of thought and belief-secular or religious, social or political-which could surpass or equal ISLAAM- the system which Muhammad peace and blessings of God Almighty be upon him propounded. In a fast changing world, while other systems have undergone profound transformations, Islaam alone has remained above all change and mutation, and retained its original form for the past 1400 years. What is more, the positive changes that are taking place in the world of human thought and behavior, truly and consistently reflect the healthy influence of Islam in these areas. Further, it is not given to the best of thinkers to put their ideas completely into practice, and to see the seeds of their labors grow and bear fruit, in their own lifetime. Except of course, Muhammad, peace and blessings of God Almighty be upon him, who not only preached the most wonderful ideas but also successfully translated each one of them into practice in his own lifetime. At the time of his death his teachings were not mere precepts and ideas straining for fulfillment, but had become the very core of the life of tens of thousands of perfectly trained individuals, each one of whom was a marvelous personification of everything that Muhammad peace and blessings of God Almighty be upon him taught and stood for. At what other time or place and in relation to what other political, social, religious system, philosophy or ideology-did the world ever witness such a perfectly amazing phenomenon? Indeed no other system or ideology secular or religious, social or political, ancient or modern - could ever claim the distinction of having been put into practice in its fullness and entirety EVEN ONCE in this world, either before or after the death of its founder. Except of course ISLAAM, the ideology preached by Muhammad, peace and blessings of God Almighty be upon him which was established as a complete way of life by the teacher himself, before he departed from this world. History bears testimony to this fact and the greatest skeptics have no option but to concede this point. In spite of these amazing achievements and in spite of the countless absolutely convincing and authentic miracles performed by him and the phenomenal success which crowned his efforts, he did not for a moment claim to be God or God's incarnation or Son - but only a human being who was chosen and ordained by God to be a teacher of truth to man kind and a complete model and pattern for their actions. He was nothing more or less than a human being. But he was a man with a noble and exalted mission-and his unique mission was to unite humanity on the worship of ONE AND ONLY GOD and to teach them the way to honest and upright living in accordance with the laws and commands of God. He always described himself as A MESSENGER AND SERVANT OF GOD, and so indeed every single action and movement of his proclaimed him to be. A world which has not hesitated to raise to Divinity individuals whose very lives and missions have been lost in legend and who historically speaking did not accomplish half as much-or even one tenth-as was accomplished by Muhammad, peace and blessings of God Almighty be upon him should stop to take serious note of this remarkable man's claim to be God's messenger to mankind. Today after the lapse of some 1400 years the life and teachings of Prophet Muhammad, peace and blessings of God Almighty be upon him, have survived without the slightest loss, alteration or interpolation. Today they offer the same undying hope for treating mankind's many ills which they did when Prophet Muhammad, peace and blessings of God Almighty be upon him, was alive. This is our honest claim and this is the inescapable conclusion forced upon us by a critical and unbiased study of history. The least YOU should do as a thinking, sensitive, concerned human being is to stop for one brief moment and ask yourself: Could it be that these statements, extraordinary and revolutionary as they sound, are really true? Supposing they really are true, and you did not know this man Muhammad, peace and blessings of God Almighty be upon him or hear about his teachings? Or did not know him well and intimately enough to be able to benefit from his guidance and example? Isn't it time you responded to this tremendous challenge and made some effort to know him? It will not cost you anything but it may well prove to be the beginning of a completely new era in your life. Come, let us make a new discovery of the life of this wonderful man Muhammad, peace and blessings of God Almighty be upon him the like of whom never walked on this earth, and whose example and teachings can change YOUR LIFE and OUR WORLD for the better. May God shower His choicest blessings upon him! Written by S.H. Pash From fdu.xiaojf at gmail.com Sat Aug 11 02:55:24 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Sat, 11 Aug 2007 14:55:24 +0800 Subject: The Future of Python Threading In-Reply-To: <1186782710.600889.245930@j4g2000prf.googlegroups.com> References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <1i2njyp.1o6yslqe7ff47N%luc@honk-honk.com> <1186782710.600889.245930@j4g2000prf.googlegroups.com> Message-ID: <46BD5D5C.2060809@gmail.com> Justin T. wrote: > On Aug 10, 2:02 pm, l... at honk-honk.com (Luc Heinrich) wrote: >> Justin T. <jmtull... at gmail.com> wrote: >>> What these seemingly unrelated thoughts come down to is a perfect >>> opportunity to become THE next generation language. >> Too late: <http://www.erlang.org/> >> >> :) >> >> -- >> Luc Heinrich > > Uh oh, my ulterior motives have been discovered! > > I'm aware of Erlang, but I don't think it's there yet. For one thing, > it's not pretty enough. It also doesn't have the community support > that a mainstream language needs. I'm not saying it'll never be > adequate, but I think that making python into an Erlang competitor > while maintaining backwards compatibility with the huge amount of > already written python software will make python a very formidable > choice as languages adapt more and more multi-core support. Python is > in a unique position as its actually a flexible enough language to > adapt to a multi-threaded environment without resorting to terrible > hacks. > > Justin > Multi-core or multi-CPU computers are more and more popular, especially in scientific computation. It will be a great great thing if multi-core support can be added to python. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Aug 24 03:50:09 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 24 Aug 2007 09:50:09 +0200 Subject: beginner, idomatic python 2 In-Reply-To: <46ce8d0c$0$410$426a74cc@news.free.fr> References: <13csjmeaoqh9le3@corp.supernews.com> <46ce8d0c$0$410$426a74cc@news.free.fr> Message-ID: <46ce8d75$0$410$426a74cc@news.free.fr> Bruno Desthuilliers a ?crit : (snip) > and ALL_LOWER That's 'ALL_UPPER', of course :( > for symbolic (pseudo) > constants. > From zyzhu2000 at gmail.com Fri Aug 24 01:44:50 2007 From: zyzhu2000 at gmail.com (beginner) Date: Fri, 24 Aug 2007 05:44:50 -0000 Subject: List Comprehension Question: One to Many Mapping? In-Reply-To: <1187934068.998593.201240@x40g2000prg.googlegroups.com> References: <1187929443.636690.287450@i13g2000prf.googlegroups.com> <1187934068.998593.201240@x40g2000prg.googlegroups.com> Message-ID: <1187934290.472868.36770@q3g2000prf.googlegroups.com> On Aug 24, 12:41 am, Davo <davb... at gmail.com> wrote: > On Aug 23, 9:24 pm, beginner <zyzhu2... at gmail.com> wrote: > > > > > > > Hi All, > > > How do I map a list to two lists with list comprehension? > > > For example, if I have x=[ [1,2], [3,4] ] > > > What I want is a new list of list that has four sub-lists: > > > [[1,2], [f(1), f(2)], [3,4], [f(3), f(4)]] > > > [1,2] is mapped to [1,2] and [f(1), f(2)] and [3,4] is mapped to > > [3,4], [f(3), f(4)]. > > > I just can't find any way to do that with list comprension. I ended up > > using a loop (untested code based on real code): > > > l=[] > > for y in x: > > l.append(y) > > l.append([f(z) for z in y]) > > > Thanks, > > Geoffrey > > This may be what you want: > > l = [[y, [f(z) for z in y]] for y in x] > > But It's a bit dense. How about: > l=[] > for y in x: > Fy = [f(z) for z in y] > l.extend([y, Fy]) > > -- David- Hide quoted text - > > - Show quoted text - This is exactly what I was looking for. Thanks. From vedrandekovic at v-programs.com Wed Aug 22 15:18:15 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Wed, 22 Aug 2007 12:18:15 -0700 Subject: redirect or cover .bat log In-Reply-To: <1187791309.427046.22400@q3g2000prf.googlegroups.com> References: <1187764689.836375.212730@z24g2000prh.googlegroups.com> <5j26bvF3s7lbpU2@mid.uni-berlin.de> <1187767578.925671.107000@q4g2000prc.googlegroups.com> <5j2br6F3r2avsU1@mid.uni-berlin.de> <1187787876.962883.66970@r34g2000hsd.googlegroups.com> <1187791309.427046.22400@q3g2000prf.googlegroups.com> Message-ID: <1187810295.951965.239300@m37g2000prh.googlegroups.com> On 22 kol, 16:01, Gabriel Genellina <gagsl-... at yahoo.com.ar> wrote: > On 22 ago, 10:04, vedrandeko... at v-programs.com wrote: > > > > > > >> > e.g I need run my my_scripts_setup.bat that contain: > > > > >> > python myscript_setup.py py2exe > > > > >> > Can I cover or redirect log of that process into my wx program? > > > >> > I'am using Windows XP SP2, and Python 2.5. > > Try the subprocess module. For the single line command you posted > earlier, you don't even need the bat file: > > import subprocess > p = subprocess.Popen(["python", "myscript_setup.py", "py2exe"], > stdout=subprocess.PIPE, stderr=subprocess.STDOUT) > p.wait() > output_from_process = p.stdout.readlines() > > This would be fine if executing the script takes relatively a short > time and doesn't generate so many output lines; there are other > examples in the subprocess module documentation <http:// > docs.python.org/lib/module-subprocess.html> > > -- > Gabriel Genellina Hi, This works fine. Thanks! From bignose+hates-spam at benfinney.id.au Thu Aug 30 23:18:40 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 31 Aug 2007 13:18:40 +1000 Subject: strings (dollar.cents) into floats References: <mailman.140.1188483282.28954.python-list@python.org> <877incd20i.fsf@benfinney.id.au> <46d75cf3$0$7698$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <87ps14bddb.fsf@benfinney.id.au> Wildemar Wildenburger <lasses_weil at klapptsowieso.net> writes: > But what use is there for floats, then? When is it OK to use them? When one is willing to sacrifice decimal precision for speed of calculation, and doesn't need the numbers to stay precise. E.g. when performing millions of calculations on real-world (analogue) measurements. -- \ "Too many Indians spoil the golden egg." -- Sir Joh | `\ Bjelke-Petersen | _o__) | Ben Finney From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Aug 1 06:01:29 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 01 Aug 2007 12:01:29 +0200 Subject: standalone process to interact with the web In-Reply-To: <1185904623.754078.198910@e9g2000prf.googlegroups.com> References: <1185899130.331170.151980@e16g2000pri.googlegroups.com> <mailman.1375.1185900147.22759.python-list@python.org> <1185904623.754078.198910@e9g2000prf.googlegroups.com> Message-ID: <46b059ed$0$31743$426a74cc@news.free.fr> beginner a ?crit : > Hi Steve, > > On Jul 31, 11:42 am, Steve Holden <st... at holdenweb.com> wrote: >> beginner wrote: >>> Hi Everyone, >>> I am looking for a way to allow a standalone python process to easily >>> interactive with a few web pages. It has to be able to easily receive >>> requests from the web and post data to the web. >>> I am thinking about implementing a standalone soap server, but I am >>> not sure which library is good. >>> Any suggestions? >>> Thanks a lot, >>> Geoffrey >> Look nor further than mechanize - >> (snip) > This seems to be an HTTP client library. It is very interesting, but > is not what I need. I am looking for something that can provide > service to web pages. For example, when a browser requests a web page, > the web page is going to send a few requests to my server. My server > then is going to respond, and the web page takes the response and > format it in human readable form. IOW, you want to embed a web server in your application. From bthate at gmail.com Sat Aug 25 15:59:32 2007 From: bthate at gmail.com (bthate) Date: Sat, 25 Aug 2007 19:59:32 -0000 Subject: GOZERBOT 0.7.1 released Message-ID: <1188071972.308657.217650@y42g2000hsy.googlegroups.com> GOZERBOT 0.7.1 released - This release fixes the following bugs: * the udp encryption was fixed * a newline injection bug in the RSS plugin was discovered at CCC camp and fixed. credits for finding this bug go to Astro- - version 0.7.1 can be downloaded at http://gozerbot.org. for upgrading see doc/UPGRADE. - debian users can find 0.7.1 in unstable - about gozerbot (from http://wiki.gozerbot.org): Gozerbot is an Jabber|IRC bot, written in the Python programming language. Gozerbot runs on Unix/Unix like operating systems. It requires a Shell and a Python interpreter version 2.4 or higher features: * user management by userhost * fleet, combine multiple bots * relaying between fleet bots * various list types * chain commands * builtin webserver * collective, connect bots through their webserver * easily extendible through plugins * DCC support * RSS support * database support * jabbersupport * karma, quotes, items, todo and shoppinglists * easy update of development versions (hg,svn) to the latest code with just one irc command * other stuff the gozerbot development team From gregpinero at gmail.com Sun Aug 5 12:56:31 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Sun, 05 Aug 2007 16:56:31 -0000 Subject: Best way to capture output from an exec'ed (or such) script? In-Reply-To: <mailman.1635.1186307437.22759.python-list@python.org> References: <1186084086.212050.264270@q3g2000prf.googlegroups.com> <mailman.1547.1186097565.22759.python-list@python.org> <1186154066.529360.90260@q75g2000hsh.googlegroups.com> <1186264336.502429.232840@r34g2000hsd.googlegroups.com> <mailman.1635.1186307437.22759.python-list@python.org> Message-ID: <1186332991.527508.225630@57g2000hsv.googlegroups.com> On Aug 5, 5:50 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Sat, 04 Aug 2007 18:52:16 -0300, gregpin... at gmail.com > <gregpin... at gmail.com> escribi?: > > >> On Aug 2, 7:32 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote:> > >> If your web server is multithreaded (or you use some other way to > >> process > >> > many simultaneous requests) you have to be more careful - remember > >> that > >> > sys.stdout is global, you must find a way to distinguish between > >> output > >> > from different processes all going into the same collector. > > > I'm actually worried about this now. Does anyone know of any > > potential solutions? Anything to at least get me started? > > You can use threading.currentThread() to distinguish between threads, and > a Lock (or RLock) to ensure the output doesn't get mixed: > > def write(msg): > t = time.strftime("%x %X", time.localtime()) > who = threading.currentThread().getName() > line = "%s (%-15.15s) %s\n" % (t, who, msg) > OutputDebugString("%s (%-15.15s) %s\n" % (t, who, msg)) > loglock.acquire() > try: > with logfile() as f: > f.write(line) > finally: > loglock.release() > > -- > Gabriel Genellina Thanks, Gabriel. I'm not actually making the threads myself though. Rather it's a simple single threaded script running under FastCGI. Would your method still work? I don't know too much about how FastCGI works. Perhaps that's where I should start. -Greg From mattheww at chiark.greenend.org.uk Wed Aug 22 12:49:39 2007 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 22 Aug 2007 17:49:39 +0100 (BST) Subject: Eval and raw string ?? References: <1187798806.029598.264740@q3g2000prf.googlegroups.com> Message-ID: <ZmF*iPXSr@news.chiark.greenend.org.uk> Mark <creechm at gmail.com> wrote: > Eval() doesn't seem to recognize the r'string' format. Is there a way > around this. > Example: > If I input: ---------> eval("r'C:\tklll\ndfd\bll'") > I get the output: > > Traceback (most recent call last): > File "<pyshell#3>", line 1, in <module> > eval("r'C:\tklll\ndfd\bll'") > File "<string>", line 1 > r'C: klll > ^ > SyntaxError: EOL while scanning single-quoted string > > The same principle applies for exec. The \n is being converted to a newline before the string is passed to eval. Try eval(r"r'C:\tklll\ndfd\bll'") -M- From zunbeltz at gmail.com Fri Aug 10 03:40:17 2007 From: zunbeltz at gmail.com (zunbeltz at gmail.com) Date: Fri, 10 Aug 2007 00:40:17 -0700 Subject: float to string with different precision Message-ID: <1186731617.128913.279360@m37g2000prh.googlegroups.com> Hi, I have to print float numbers to a file. Each float should be 5 characters in width (4 numbers and the decimal point). My problem is that I do not now how to specify float to have different numbers of decimals. For example 5.32 -> 5.320 10.356634 -> 10.357 289.234 -> 289.2 In the string formating operations only fixed number of decimal digits is allow. Thanks in advance for the help, Zunbeltz From luc at honk-honk.com Fri Aug 10 17:02:50 2007 From: luc at honk-honk.com (Luc Heinrich) Date: Fri, 10 Aug 2007 23:02:50 +0200 Subject: The Future of Python Threading References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> Message-ID: <1i2njyp.1o6yslqe7ff47N%luc@honk-honk.com> Justin T. <jmtulloss at gmail.com> wrote: > What these seemingly unrelated thoughts come down to is a perfect > opportunity to become THE next generation language. Too late: <http://www.erlang.org/> :) -- Luc Heinrich From jstroud at mbi.ucla.edu Wed Aug 22 19:32:53 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 22 Aug 2007 23:32:53 GMT Subject: Learning Python using a book based on version 1.5 In-Reply-To: <1187814437.775758.159510@e9g2000prf.googlegroups.com> References: <1187814437.775758.159510@e9g2000prf.googlegroups.com> Message-ID: <FI3zi.10911$3x.7829@newssvr25.news.prodigy.net> dogatemycomputer at gmail.com wrote: > Greetings, > > A friend of mine dropped off a copy of Sams Teach Yourself Python in > 24 Hours published in 2000. I skimmed the first couple of chapters > looking for the interpreter version and the book was based on version > Python version 1.5. > > Is this book still relevant? Should I toss it and look for something > newer? > > Any thoughts would be appreciated. > > Best Regards, > Dave > If you want to make a decision based on a quorum, I would suggest to not bother with that book. Yes the SAMS TY books are usually great (especially anything Laura Lemay), but you if you use a 1.5 book, you will be learning some stuff you will *need* to unlearn at the expense of learning things you should know. I think the online tutorial is the way to go, or the newest Learning Python from Lutz. After that, check out TPIP (Mertz) or the Programming Python book from Lutz (for a global-esque view of the python world). Maybe even think about the Cookbook (ed. Martelli). Dive-Into-Python starts with one of those "Don't worry about what all this means" examples, which I tend to hate and so I never got passed the first example--it may get better as you go judging from all of its proponents. James From iclark at mail.ewu.edu Thu Aug 2 16:57:29 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Thu, 02 Aug 2007 13:57:29 -0700 Subject: Bug in execfile? In-Reply-To: <f8t80e$gvh$1@sea.gmane.org> References: <f8t80e$gvh$1@sea.gmane.org> Message-ID: <f8tgfq$e2u$1@sea.gmane.org> Fernando Perez wrote: > Hi all, > > (snip) > > I'm really, really puzzled by this. From reading the execfile() docs, I had > the hunch to change the call to: > > execfile(fname,{}) > > and now the problem disappears, so I can keep on working. > > But I'm still very bothered by the fact that changing that first call 'if 0' > to 'if 1' has any effect on the later call to runscript(). That really > doesn't feel right to me... First an example: #foo.py from math import sin #EOF >>> dir() ['__builtins__', '__doc__', '__name__'] >>> execfile('foo.py') >>> dir() ['__builtins__', '__doc__', '__name__', 'sin'] New session: >>> dir() ['__builtins__', '__doc__', '__name__'] >>> execfile('foo.py', {}) >>> dir() ['__builtins__', '__doc__', '__name__'] >>> help(execfile) Help on built-in function execfile in module __builtin__: execfile(...) execfile(filename[, globals[, locals]]) Read and execute a Python script from a file. The globals and locals are dictionaries, defaulting to the current globals and locals. If only globals is given, locals defaults to it. By default execfile works on the *current* namespace. So exec'ing a script that modified it's global namespace will also modify the global namespace of the calling module (see my first example). If you specify a dictionary then execfile will use that as the global and local (maybe) namespace of the file that it is running (hence the global namespace of the calling module stays in tact per the second example). That is why execfile(fname, {}) works for you, it doesn't pollute your current namespace. It uses a different namespace when calling the file then is being used by the calling module. No idea why your function failed though. *shrug* Ian From xah at xahlee.org Sat Aug 4 21:27:24 2007 From: xah at xahlee.org (Xah Lee) Date: Sat, 04 Aug 2007 18:27:24 -0700 Subject: The Modernization of Emacs: keyboard shortcuts pain In-Reply-To: <1185282252.520022.20780@z28g2000prd.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272678.877166.209640@j4g2000prf.googlegroups.com> <1184764620.778937.264760@m37g2000prh.googlegroups.com> <1185282252.520022.20780@z28g2000prd.googlegroups.com> Message-ID: <1186277244.045554.308420@i13g2000prf.googlegroups.com> The following article a extended version of previous post. A HTML version can be found at http://xahlee.org/emacs/emacs_kb_shortcuts_pain.html ----------------------------------- WHY EMACS'S KEYBOARD SHORTCUTS ARE PAINFUL Xah Lee, 2007-07 A important aspect in designing a keyboard shortcut set, for a application that has intensive, repetitive, prolonged human-machine interaction (such as coding and text editing), is to consider ergonomic principles. Specifically: allocate keyboard shortcuts for the most frequently used commands, and, the top most frequently used commands should have most easily-pressed keystrokes. For example, they should be on the home row. This article shows why Emacs's keyboard shortcut set are the most ergonomically unsound. THE SWAPPING OF CONTROL AND META MODIFIERS Emacs's keyboard shortcuts is very inefficient. The primary cause is because, emacs's keyboard shortcuts are designed with a keyboard that practically has the Ctrl and Alt key positions swapped. Space Cadet keyboard above: The Space-cadet keyboard (Source?, 2007-07) . The common keyboard used around emacs era in the 1980s are those keyboards from Lisp Machines?. (see Space-cadet keyboard?) The keyboard on lisp machines have the Control key right besides the space bar (similar to the position of Alt keys on PC keyboards), and Meta to the left of Control. So, the Control key is right under the thumb, and the Meta is secondary to Control. This is why, the shortcuts for the most used commands in emacs involve the Control key instead of the Meta key. (e.g. The cursor movements: C-p, C-n, C-f, C-b, C-a, C-e, the cut/paste/undo C-w, C-y, C-/, the kill-line C-k, the mark C-SPC, the search C-s.) Lisp Machine's keyboards fell out of use alone with Lisp Machines. Since the 1990s, the IBM PC keyboard? (and its decedents) becomes the most popular and is used by more than 99% of personal computers today. The PC keyboard does not have Meta key but have Alt instead, which is practically used as Meta for emacs. The Ctrl and Alt key's position are essentially swapped from the Control and Meta on the Lisp Machine's keyboards. Emacs however, did not change its keyboard shortcut set by switching the commands that are mapped to the Control and Meta keys. This makes emacs keyboard shortcuts very painful, and the frequent need to press the far-away Control key makes the Emacs Pinky syndrome. (Many emacs-using programer celebrities have injured their hands with emacs. (e.g. Richard Stallman?, Jamie Zawinski?), and emacs's Ctrl and Meta combinations are most cited as the major turn-off to potential users among programers) THE CHOICE OF KEYS The shortcut's key choices are primarily based on first letter of the commands, not based on key position and finger strength or ease of pressing the key. For example, the single char cursor moving shortcuts (C-p previous-line ?, C-n next-line ?, C-b backward-char ?, C-f forward-char ?) are scattered around the keyboard with positions that are most difficult to press. (these shortcuts all together accounts for 43% of all commands executed by a keyboard shortcut) Of these, the most frequently used is C-n (next-line), which accounts for 20% of all shortcut calls, but is assigned to the letter n, positioned in the middle of the keyboard, which is one of the most costy key to press. Similarly, the second most used among these is the C-p (previous- line), accounting for 16% of all shortcut command calls, is located in a position above the rigth hand's pinky, also one of the most costy key to press. (Here we assumes the QWERTY keyboard layout. On the Dvorak layout, it is about as bad.) OUTDATED COMMANDS A significant portion of emacs's major shortcuts (those with M-?key? or C-?key?) are mapped to commands that are almost never used today. Some of these occupies the most precious space (Home row with Meta: e.g. M-s (center-line), M-j (indent-new-comment-line), M-k (kill- sentence)). Most programer who have used emacs for years never use these commands. For example: digit-argument, M-1 to M-9 negative-argument, M-- move-to-window-line, M-r center-line, M-s transpose-words, M-t tab-to-tab-stop, M-i M-g prefix, M-g indent-new-comment-line, M-j tmm-menubar, M-' zap-to-char, M-z back-to-indentation, M-m tags-loop-continue, M-, find-tag, M-. NO EMPLOYMENT OF THE SHIFT KEY For historical reasons, emacs do not use any keybindings involving the Shift with a letter. (e.g. there's no ?meta shift a?, or ?control shift a?) This is so because in early computing environment, such key combination cannot be distinguished, due to a practical combination of ASCII?, Computer terminal?, telnet?. Today, however, employing the Shift key as part of a shortcut with other modifiers is common and convenient. For example, on Mac OS X, Undo and Redo are Cmd+Z and Cmd+Shift+Z, Save and Save As are Cmd+S and Cmd+Shift+S. On Mac and Windows, moving to next/previous field/ window/application often use the Shift key for reversing direction. In text editing on both Mac and Windows, a modifier key with a arrow key will move cursor by word/paragraph, and with Shift down will select them while moving. Using the Shift key as a reverse operation is very easy to remember, and doesn't take another precious shortcut letter. By not using the Shift key, commands with a logical reverse operation necessarily have to find other key space, and overall making the shortcut set more difficult to remember, or scattered, or more difficult to press. A FLAW IN KEYBINDING POLICY Any major software, maintains a guide for the developers about the choices of keyboard shortcuts, so that the shortcuts will be consistant. Emacs has this in its Emacs Lisp manual: Elisp Manual: Key- Binding-Conventions. This guide, indicates that the only key space reserved for users to define, are the function keys F5 to F9, and key stroke sequence starting with Ctrl+c followed by a single letter key. This is a severe restraint to the utility of customized shortcuts. F5 to F9 are only 6 keys. The key sequence starting with C-c followed by a letter, is a difficult sequence to execute, and there are only 26 spaces there. The function keys, F1 to F12, are very good candidates for user defined shortcut space, similarly for the digit key shortcuts, 0 to 9. These series of key space can be multiplied by any combination of modifiers of Control, Meta, Shift. For example, a user might define the them to insert various templates, headers/footers, a system of customized HTML/XML tags. Or, she might assign them to various special emacs modes such as dired, shell, ftp, email, calendar, calc, *scratch*, make-frame-command (Open a new window), insert signature. It seems too drastic a policy, to limit user defined keys to only F5 to F9, and key sequence of Control+c followed by a single letter key. EPILOGUE: FAILURE TO CHANGE Today, most commonly used keyboard shortcuts have been somewhat informally standardized. For example, C/X/V is for Copy/Cut/Paste. O is for Open. S is for Save, Shift-S is for Save As. P is for Print. F is for Find/Search. Tab is for next, Shift tab for previous. These are common conventions today in every application across Microsoft Windows and Macintosh (and most Linuxes). These shortcuts conventions are primarily brought about by Apple Computer Inc's Human interface guidelines? and IBM's Common User Access? in the 1990s. In the early 1990s, DOS era software, each application has its own scheme of shortcuts. The following is a excerpt from the Wikipedia article on Common User Access?: CUA was a detailed specification and set strict rules about how applications should look and function. Its aim was in part to bring about harmony between MS-DOS applications, which until then had implemented totally different user interfaces. Examples: * In WordPerfect, the command to open a file was [F7], [3]. * In Lotus 1-2-3, a file was opened with [/] (to open the menus), [W] (for Workspace), [R] (for Retrieve). * In Microsoft Word, a file was opened with [Esc] (to open the menus), [T] (for Transfer), [L] (for Load). * In WordStar, it was [Ctrl]+[K]+[O]. * In Emacs, a file was opened with [Ctrl]+[x] followed by [Ctrl]+ [f] (for find-file). Some programs used [Esc] to cancel an action, some used it to complete one; WordPerfect used it to repeat a character. Some programs used [End] to go to the end of a line, some used it to complete filling in a form. [F1] was often help but in WordPerfect that was [F3]. [Ins] sometimes toggled between overtype and inserting characters, but some programs used it for ?paste?. Thus, every program had to be learned individually and its complete user interface memorized. It was a sign of expertise to have learned the UIs of dozens of applications, since a novice user facing a new program would find their existing knowledge of a similar application absolutely no use whatsoever. Commercial software have updated themselves with time (or went extinct), but emacs has not. Xah xah at xahlee.org ? http://xahlee.org/ From antroy at gmail.com Wed Aug 8 07:10:32 2007 From: antroy at gmail.com (Ant) Date: Wed, 08 Aug 2007 04:10:32 -0700 Subject: Seek the one billionth line in a file containing 3 billion lines. In-Reply-To: <46b996b1$0$12384$426a74cc@news.free.fr> References: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> <7xzm12o7o7.fsf@ruckus.brouhaha.com> <mailman.1729.1186557385.22759.python-list@python.org> <46b996b1$0$12384$426a74cc@news.free.fr> Message-ID: <1186571432.901348.138990@g4g2000hsf.googlegroups.com> On Aug 8, 11:10 am, Bruno Desthuilliers <bruno. 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > Jay Loden a ?crit : > (snip) > > > If we just want to iterate through the file one line at a time, why not just: > > > count = 0 > > handle = open('hugelogfile.txt') > > for line in handle.xreadlines(): > > count = count + 1 > > if count == '1000000000': > > #do something > > for count, line in enumerate(handle): > if count == '1000000000': > #do something You'd get better results if the test were: if count == 1000000000: Or probably even: if count == 999999999: Since the 1 billionth line will have index 999999999. Cheers, -- Ant... http://antroy.blogspot.com/ From timid.gentoo at gmail.com Sun Aug 12 22:16:06 2007 From: timid.gentoo at gmail.com (_spitFIRE) Date: Sun, 12 Aug 2007 21:16:06 -0500 Subject: retrieving ATOM/FSS feeds Message-ID: <f9oecg$249v$1@sxnews1.qg.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I'm using feedparser library to parser ATOM/RSS feeds. However, I don't get the entire post! but only summaries! How do I retrieve the entire feed? I believe that the parser library should have support for doing that or the specification should detail how it can be done? Or should I simply get the feed link and do HTML scraping? - -- _ _ _]{5pitph!r3}[_ _ _ __________________________________________________ ?I'm smart enough to know that I'm dumb.? - Richard P Feynman -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGv77mA0th8WKBUJMRAk80AJ9VCIBXIZVhuPtT7bfY4dRrM15H+gCeOVJG 77Zbl8jmWPsp4QjP85Lbwbc= =Ho+8 -----END PGP SIGNATURE----- From johnmasters at oxtedonline.net Thu Aug 9 16:21:22 2007 From: johnmasters at oxtedonline.net (John K Masters) Date: Thu, 9 Aug 2007 21:21:22 +0100 Subject: Puzzled by "is" In-Reply-To: <f9frbl$dps$1@sea.gmane.org> References: <20070809194105.39BD11E400A@bag.python.org> <f9frbl$dps$1@sea.gmane.org> Message-ID: <20070809202122.GA3970@spookie1.spookiegate> On 15:53 Thu 09 Aug , Steve Holden wrote: > Dick Moores wrote: > > At 10:46 AM 8/9/2007, Bill Scherer wrote: > >> Dick Moores wrote: > [...] > >> There is only one empty tuple. > >> Does that clear it up for you? > > > > But isn't that the same as saying, "That's just the reality of > > Python; it is what it is."? I want to know why there is only one > > empty tuple, but more than one (1,). > > > Why? Because. > > Seriously, it's just an optimization by the implementers. There is no > need for more than one empty tuple, since tuples can never be modified > once created. > > But they decided not to create (1, ) in advance. They probably knew that > hardly anybody would want to create that tuple ;-) [Seriously: if you > started trying to predict which tuples would be used you would go > insane, but the empty tuple is the most likely candidate]. > > > Also, > > >>> [] is [] > > False > > > In that case it would definitely NOT make sense to have them the same > list. Python always ensures that the [] constructor creates a new list, > since that list may be bound to one or more variables and mutated. You > wouldn't want > > a = [] > b = [] > a.append("boo!") > > to change b so it was no longer an empty list. If you wanted a and b to > reference the same list you would change the second statement to > > b = a > > regards > Steve OK fiddling around with this and reading the docs I tried:- a = 'qqqqqqqqqq' #10 q's b = 'qqqqqqqqqq' #10 q's a is b true c = 'q' * 10 c 'qqqqqqqqqq' #10 q's d = 'q' * 10 d 'qqqqqqqqqq' #10 q's c is d false So from what I've read "==" tests for equivalence, "is" tests for identity but that does not explain the behaviour above. Regards, John -- War is God's way of teaching Americans geography Ambrose Bierce (1842 - 1914) From steve at holdenweb.com Wed Aug 8 11:48:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 08 Aug 2007 11:48:51 -0400 Subject: Something in the function tutorial confused me. In-Reply-To: <1186581124.3383.55.camel@dot.uniqsys.com> References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <slrnfbe1fd.n4.horpner@FIAD06.norwich.edu> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <slrnfbeofu.20s.horpner@FIAD06.norwich.edu> <1186424693.529497.217040@w3g2000hsg.googlegroups.com> <46B8626A.2070303@bigfoot.com> <mailman.1726.1186537161.22759.python-list@python.org> <5hsoi3F3mlni2U1@mid.individual.net> <f9ceb9$jsm$1@sea.gmane.org> <1186581124.3383.55.camel@dot.uniqsys.com> Message-ID: <f9col1$q8i$1@sea.gmane.org> Carsten Haese wrote: > On Wed, 2007-08-08 at 08:52 -0400, Steve Holden wrote: [...] > > The problem is your ambiguous use of the word "assignment." In the sense > of the Language Reference, "any assignment to y" is a simple assignment > that always modifies a namespace and never modifies an object. In that > sense, the mutability of None really isn't the issue. > > If you use the broader sense in which "assignment" includes augmented > assignments, the mutability of None does become relevant. > > I agree that greg's delivery was unduly disrespectful, but I think he > was making a valid point. > > Hope this helps clear up the confusion. > > Best regards, > And this is why we should all be using the term "binding", which is normal in Python. I'll try to be more careful in future. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From ricaraoz at gmail.com Thu Aug 30 22:26:37 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 30 Aug 2007 23:26:37 -0300 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188525647.003223.199620@q5g2000prf.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> Message-ID: <46D77C5D.10503@bigfoot.com> Russ wrote: > Paul Rubin wrote: >> Bruno Desthuilliers <bdesth.quelquechose at free.quelquepart.fr> writes: >>> FWIW, the "Eiffel and SPARK Ada folks" also "brilliantly explained" >>> why one can not hope to "write reliable programs" without strict >>> static declarative type-checking. >> I don't know about Eiffel but at least an important subset of SPARK >> Ada's DBC stuff is done using static analysis tools (not actually >> built into the compiler as it happens) to verify statically >> (i.e. without actually running the code) that the code fulfills the >> DBC conditions. I don't see any way to do that with Python >> decorators. > > Yes, thanks for reminding me about that. With SPARK Ada, it is > possible for some real > (non-trivial) applications to formally (i.e., mathematically) *prove* > correctness by static > analysis. I doubt that is possible without "static declarative type- > checking." > > SPARK Ada is for applications that really *must* be correct or people > could die. I've always wondered... Are the compilers (or interpreters), which take these programs to machine code, also formally proven correct? And the OS in which those programs operate, are they also formally proven correct? And the hardware, microprocessor, electric supply, etc. are they also 'proven correct'? > With all > due respect, most (not all, but most) Python programmers never get > near such programs > and have no idea about how stringent the requirements are. Nor do most > programmers > in general, for that matter. (It's not an insult) > From steve at holdenweb.com Wed Aug 22 23:50:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 22 Aug 2007 23:50:41 -0400 Subject: porting vc++ project to python? In-Reply-To: <46cc611f$0$25500$ba620dc5@text.nova.planet.nl> References: <46cc611f$0$25500$ba620dc5@text.nova.planet.nl> Message-ID: <faj06i$ku7$1@sea.gmane.org> marco Starglider wrote: > hi, > > i have a very large project in visual studio2005->visual c++ in windowsxp. > i'd like to port it, or my next project, over to python. > is this possible without rewriting all my code? > are there multiple options to do this? > my project is so large, that entirely rewriting it > is actually no option. > > regards, > > m > > ps i guess, it's an option to transform my current code into one or more > python extensions/modules, and then calling them from a python core > module? > > Clients of mine have had very good results wrapping C++ functionality with Boost (http://www.boost.org/libs/python/doc/). It might work for you too. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From nick at craig-wood.com Wed Aug 29 07:30:08 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 29 Aug 2007 06:30:08 -0500 Subject: Unable to read large files from zip References: <mailman.92.1188349863.28954.python-list@python.org> Message-ID: <slrnfdain8.aai.nick@irishsea.home.craig-wood.com> Kevin Ar18 <kevinar18 at hotmail.com> wrote: > > I posted this on the forum, but nobody seems to know the solution: http://python-forum.org/py/viewtopic.php?t=5230 > > I have a zip file that is several GB in size, and one of the files inside of it is several GB in size. When it comes time to read the 5+GB file from inside the zip file, it fails with the following error: > File "...\zipfile.py", line 491, in read bytes = self.fp.read(zinfo.compress_size) > OverflowError: long it too large to convert to int That will be an number which is bigger than 2**31 == 2 GB which can't be converted to an int. It would be explained if zinfo.compress_size is > 2GB, eg >>> f=open("z") >>> f.read(2**31) Traceback (most recent call last): File "<stdin>", line 1, in ? OverflowError: long int too large to convert to int However it would seem nuts that zipfile is trying to read > 2GB into memory at once! > There have been one or more posts about 2GB limits with the zipfile > module, as well as this bug report: > http://bugs.python.org/issue1189216 Also, older zip formats have a > 4GB limit. However, I can't say for sure what the problem is. > Does anyone know if my code is wrong Your code looks OK to me. > or if there is a problem with Python itself? Looks likely. > If Python has a bug in it ...then you have the source and you can have a go at fixing it! Try editing zipfile.py and getting it to print out some debug info and see if you can fix the problem. When you have done submit the patch to the python bug tracker and you'll get that nice glow from helping others! Remember python is open source and is made by *us* for *us* :-) If you need help fixing zipfile.py then you'd probably be better off asking on python-dev. -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From jp.eugster at googlemail.com Tue Aug 7 10:17:19 2007 From: jp.eugster at googlemail.com (jp.eugster at googlemail.com) Date: Tue, 07 Aug 2007 14:17:19 -0000 Subject: making a opc client in Python and use opc server Events In-Reply-To: <1183042522.949829.19840@m36g2000hse.googlegroups.com> References: <1180949568.305737.175350@n4g2000hsb.googlegroups.com> <1183042522.949829.19840@m36g2000hse.googlegroups.com> Message-ID: <1186496239.764001.259880@57g2000hsv.googlegroups.com> On 28 juin, 16:55, jp.eugs... at googlemail.com wrote: > On 4 juin, 11:32, getelectro... at gmail.com wrote: > > > > > > > Hi all > > I have a sample code to implement opc client in Python. i use a > > file .py making by makepy with pythonwin for Com Interface. > > i can get all server in machine, connect to server opc, disconnect, > > add group, add item, read, write item in server opc. > > > import win32com.client # librairie pour utiliser l'interface COM/DCOM > > from win32com.client import gencache > > gencache.EnsureModule('{DFB83232-A952-11D2-A46B-00C04F796375}', 0, 1, > > 0) > > > for svr in opcserver.GetOPCServers(): > > print svr > > > #connect to server OPC Demo Simulation from Matrikon > > opcserver.Connect('Matrikon.OPC.Simulation.1') > > > # Instance object Groups > > groups=opcserver.OPCGroups > > #add group > > group=groups.Add('Group1') > > > #instance onject Items > > items=group.OPCItems > > # add item in server opc > > tem=items.AddItem('File1.item1',1) > > > #read item value > > item.Read(win32com.client.constants.OPCDevice) > > > # write a new value > > item.Write(100) > > > #read item value > > item.Read(win32com.client.constants.OPCDevice) > > #if no pb you have 100 :) > > > #Disconnect > > #opcserver.Disconnect() > > > BUT, and BUT, i want to use a event from opc server for uodating item > > value with this below class. And i don't konw how make it!!!!!!!! > > help me plz > > > opcserver=win32com.client.Dispatch('OPC.Automation.1') > > and now i want to use events from opc server. in a class: > > class DIOPCGroupEvent: > > class DIOPCGroupsEvent: > > class DIOPCServerEvent: > > Try this: > > # Event Handlers > class ServerEvent: > def __init__(self): > print 'Init ServerEvent' > > def OnServerShutDown(self, Reason): > print 'OnServerShutDown', Reason > > class GroupEvent: > def __init__(self): > print 'Init GroupEvent' > > def OnAsyncCancelComplete(self, CancelID): > print 'OnAsyncCancelComplete', CancelID > > def OnDataChange(self, TransactionID, NumItems, ClientHandles, > ItemValues, Qualities, TimeStamps): > print 'OnDataChange', zip(ClientHandles, ItemValues, Qualities) > > def OnAsyncReadComplete(self, TransactionID, NumItems, ClientHandles, > ItemValues, Qualities, > TimeStamps, Errors): > print 'OnAsyncReadComplete', zip(ClientHandles, ItemValues, > Qualities) > > def OnAsyncWriteComplete(self, TransactionID, NumItems, > ClientHandles, Errors): > print 'OnAsyncWriteComplete', zip(ClientHandles, Errors) > > class GroupsEvent: > def __init__(self): > print 'Init GroupsEvent' > > def OnGlobalDataChange(self, TransactionID, GroupHandle, NumItems, > ClientHandles, ItemValues, > Qualities, TimeStamps): > print 'OnGlobalDataChange', zip(ClientHandles, ItemValues, > Qualities) > > opc = DispatchWithEvents('Matrikon.OPC.Automation.1', ServerEvent) > > groups = DispatchWithEvents(opc.OPCGroups, GroupsEvent) > groups.DefaultGroupIsActive = True > groups.DefaultGroupUpdateRate = 2000 > > group1 = DispatchWithEvents(groups.Add('G1'), GroupEvent) > group2 = DispatchWithEvents(groups.Add('G2'), GroupEvent) > #etc ... > > It works for the GroupsEvents but I don't get the GroupEvent for each > group, I may still do someting wrong..- Masquer le texte des messages pr?c?dents - > > - Afficher le texte des messages pr?c?dents - In order to get the GroupEvent, you have to keep a reference to the group you add eg: g1 = groups.Add('G1') group1 = DispatchWithEvents(g1, GroupEvent) etc... From nair.jitendra at gmail.com Fri Aug 24 02:12:52 2007 From: nair.jitendra at gmail.com (nair.jitendra at gmail.com) Date: Fri, 24 Aug 2007 06:12:52 -0000 Subject: online doc bug Message-ID: <1187935972.181274.158260@r23g2000prd.googlegroups.com> hyperlink "site module documentation" in Section 4.1 on page http://docs.python.org/inst/search-path.html leads to a nonexistent page. Regards jitendra nair From S.Mientki-nospam at mailbox.kun.nl Fri Aug 3 07:16:51 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 03 Aug 2007 13:16:51 +0200 Subject: (no) fast boolean evaluation ? missing NOT In-Reply-To: <f8uu5f$i3u$1@news2.u-psud.fr> References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> <mailman.1545.1186095368.22759.python-list@python.org> <1186096979.397596.36640@e16g2000pri.googlegroups.com> <eb4fb$46b2f7a6$d443bb3a$21643@news.speedlinq.nl> <f8uu5f$i3u$1@news2.u-psud.fr> Message-ID: <19e42$46b30d1e$d443bb3a$28080@news.speedlinq.nl> Laurent Pointal wrote: > Stef Mientki a ?crit : >> <Python> >> def Some_Function (const): >> print 'Ive been here', const >> return True >> >> A = True >> >> if A and Some_Function (4 ): >> print 'I knew it was True' >> else: >> print 'I''ll never print this' >> </Python> >> >> <Output> >> Ive been here 4 >> I knew it was True >> </Output >> >> I was expected that the function would not be called, >> because A is True. > > When using the *and* operator, the short-circuit evaluation is done if A > is False (no need to know the other operand, the result cannot be True). > But if A is True, the compiler must evaluate the second parameter to > know the expression result. Sorry you're completely right, and indeed I must have something very stupid !! thanks very much Stef Mientki From deets at nospam.web.de Wed Aug 29 08:39:23 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 29 Aug 2007 14:39:23 +0200 Subject: encoding problems References: <46d5215b$0$411$426a74cc@news.free.fr> <fb3au1$v9m$1@lust.ihug.co.nz> <mailman.98.1188388302.28954.python-list@python.org> Message-ID: <5jl7nrF4ouqU1@mid.uni-berlin.de> Ricardo Ar?oz wrote: > Lawrence D'Oliveiro wrote: >> In message <46d5215b$0$411$426a74cc at news.free.fr>, tool69 wrote: >> >>> p2.content = """Ce poste poss?de des accents : ? ? ? ?""" >> >> My guess is this is being encoded as a Latin-1 string, but when you try >> to output it it goes through the ASCII encoder, which doesn't understand >> the accents. Try this: >> >> p2.content = u"""Ce poste poss?de des accents : ? ? ? ?""".encode("utf8") >> > > is there a way to sort this string properly (sorted()?) > I mean first 'a' then '?' then 'e' etc. (sorted puts accented letters at > the end). Or should I have to provide a comparison function to sorted? First of all: please don't hijack threads. Start a new one with your specific question. Second: this might be what you are looking for: http://jtauber.com/blog/2006/01/27/python_unicode_collation_algorithm/ Didn't try it myself though. Diez From steve at REMOVE-THIScybersource.com.au Sun Aug 26 00:27:21 2007 From: steve at REMOVE-THIScybersource.com.au (Steven D'Aprano) Date: Sun, 26 Aug 2007 04:27:21 -0000 Subject: accessing keys in dict References: <1187143106.021325.104690@l22g2000prc.googlegroups.com> <fap7sk$tr0$2@lust.ihug.co.nz> <1188068707.273263.200450@x35g2000prf.googlegroups.com> Message-ID: <13d2099f0fp4fb4@corp.supernews.com> On Sat, 25 Aug 2007 19:05:07 +0000, Dustan wrote: > Never assume. A better approach would be to experiment: I assume that you would not like it if I poked you in the eye with a sharp stick, but perhaps I better experiment... *wink* More seriously, if you wish to compare dict.keys() and dict.iterkeys(), iterating over them doesn't help you because it shows only the similarities, not the differences. But this will: >>> d = {1:"one", 2:"two"} >>> d.keys() [1, 2] >>> d.iterkeys() <dictionary-keyiterator object at 0xb7ecd280> dict.keys() retrieves all the keys at once, up front, whether you need them all or not. dict.iterkeys() returns an iterator which retrieves the keys lazily, only when needed. Iterating over the dict itself is the same as using iterkeys: >>> iter(d) <dictionary-keyiterator object at 0xb7ecd4a0> Performance-wise, the difference for small dicts may be trivial: >>> d = dict(zip(xrange(1000), xrange(1000))) >>> import timeit >>> timeit.Timer("for key in d: pass", "from __main__ import d").repeat() [71.805022954940796, 71.10006308555603, 70.985043048858643] >>> timeit.Timer("for key in d.keys(): pass", ... "from __main__ import d").repeat() [80.323757886886597, 76.463414907455444, 76.681307792663574] A six second difference on a million iterations of the loop is probably not worth losing sleep over. But if your dict is very big, things may be different: >>> d = dict(zip(xrange(1000000), xrange(1000000))) >>> timeit.Timer("for key in d: pass", ... "from __main__ import d").repeat(number=100) # I don't have all day... [9.2374939918518066, 8.3636147975921631, 8.3667001724243164] >>> timeit.Timer("for key in d.keys(): pass", ... "from __main__ import d").repeat(number=100) [13.776750087738037, 12.756224155426025, 12.697851181030273] A four second difference on a hundred iterations of the loop _is_ something worth worrying about. Fortunately, Python makes it no worry at all: just iterate on the dict regardless of whether your dict is small or large, and you won't go wrong. -- Steven. From ldo at geek-central.gen.new_zealand Fri Aug 31 23:38:46 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 01 Sep 2007 15:38:46 +1200 Subject: Automation and scheduling of FrontPage publishing using Python References: <1188517723.279932.299400@x40g2000prg.googlegroups.com> Message-ID: <fbamnh$r7q$7@lust.ihug.co.nz> In message <1188517723.279932.299400 at x40g2000prg.googlegroups.com>, andrew.arobert at gmail.com wrote: > We have numerous web sites which are currently being manually > published via Front Page. > > Doing one or two sites on an ad-hoc basis was not too bad but we are > now over 20 or thirty at set times during a business day. Let me open the bidding by suggesting that you stop using FrontPage. From ptmcg at austin.rr.com Sat Aug 25 21:48:33 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 25 Aug 2007 18:48:33 -0700 Subject: Joining Big Files In-Reply-To: <1188090939.364787.296630@r34g2000hsd.googlegroups.com> References: <1188035844.616831.205350@i38g2000prf.googlegroups.com> <1188090939.364787.296630@r34g2000hsd.googlegroups.com> Message-ID: <1188092913.645157.15370@o80g2000hse.googlegroups.com> On Aug 25, 8:15 pm, Paul McGuire <pt... at austin.rr.com> wrote: > On Aug 25, 4:57 am, mosscliffe <mcl.off... at googlemail.com> wrote: > > > I have 4 text files each approx 50mb. > > <yawn> 50mb? Really? Did you actually try this and find out it was a > problem? > > Try this: > import time > > start = time.clock() > outname = "temp.dat" > outfile = file(outname,"w") > for inname in ['file1.dat', 'file2.dat', 'file3.dat', 'file4.dat']: > infile = file(inname) > outfile.write( infile.read() ) > infile.close() > outfile.close() > end = time.clock() > > print end-start,"seconds" > > For 4 30Mb files, this takes just over 1.3 seconds on my system. (You > may need to open files in binary mode, depending on the contents, but > I was in a hurry.) > > -- Paul My bad, my test file was not a text file, but a binary file. Retesting with a 50Mb text file took 24.6 seconds on my machine. Still in your working range? If not, then you will need to pursue more exotic approaches. But 25 seconds on an infrequent basis does not sound too bad, especially since I don't think you will really get any substantial boost from them (to benchmark this, I timed a raw "copy" command at the OS level of the resulting 200Mb file, and this took about 20 seconds). Keep it simple. -- Paul From wildemar at freakmail.de Wed Aug 22 17:44:50 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Wed, 22 Aug 2007 23:44:50 +0200 Subject: Import question In-Reply-To: <eb79828c0708221351v5aab6849pc38fce55f4f7eea@mail.gmail.com> References: <eb79828c0708221351v5aab6849pc38fce55f4f7eea@mail.gmail.com> Message-ID: <46CCAE52.3000800@freakmail.de> Lamonte Harris wrote: > can I import more then one modules like this: > > import module,module2 So your'e basically saying that you haven't tried it? /W From Roland.Puntaier at br-automation.com Wed Aug 29 09:50:15 2007 From: Roland.Puntaier at br-automation.com (Roland Puntaier) Date: Wed, 29 Aug 2007 15:50:15 +0200 Subject: strange list comprehension on generator Message-ID: <OF8C63DC06.9B916754-ONC1257346.004B21AE-C1257346.004C0592@br-automation.com> def changeOne(aa,idx): aa[idx]=not aa[idx] yield aa for i in range(idx): for x in changeOne(aa,i): yield x def changeOneOrder(aa): yield aa for i in range(len(aa)): for x in changeOne(aa,i): yield x a=[False]*3 og=changeOneOrder(a) #this does not return the way I would expect. why? list(og) #returns #[[False, False, True], [False, False, True], [False, False, True], [False, False, True], [False, False, True], [False, False, True], [False, False, True], [False, False, True]] #this works as expected a=[False]*3 og=changeOneOrder(a) og.next() og.next() ... #this works as expected def ty(): yield 1 yield 2 yield 3 tg=ty() list(tg) cheers, Roland From ldo at geek-central.gen.new_zealand Fri Aug 31 19:19:37 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 01 Sep 2007 11:19:37 +1200 Subject: fcntl problems References: <1188512377.441241.107900@q4g2000prc.googlegroups.com> <1188515889.352267.220790@q5g2000prf.googlegroups.com> <mailman.186.1188541398.28954.python-list@python.org> <1188568022.988154.188230@y42g2000hsy.googlegroups.com> <mailman.200.1188571375.28954.python-list@python.org> Message-ID: <fba7hk$vkr$2@lust.ihug.co.nz> In message <mailman.200.1188571375.28954.python-list at python.org>, Miles wrote: > except IOError, e: > if e.args[0] == 35: Why not except IOError, (ErrNo, Msg) : if ErrNo == errno.EAGAIN : From __peter__ at web.de Sun Aug 12 06:00:14 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 12 Aug 2007 12:00:14 +0200 Subject: Fatest standard way to sum bytes (and their squares)? References: <NPmdnVwqHa74TyPbnZ2dnUVZ_uKpnZ2d@speakeasy.net> Message-ID: <f9mlne$k0k$02$2@news.t-online.com> Erik Max Francis wrote: > For a file hashing system (finding similar files, rather than identical > ones), I need to be able to efficiently and quickly sum the ordinals of > the bytes of a file and their squares. Because of the nature of the > application, it's a requirement that I do it in Python, or only with > standard library modules (if such facilities exist) that might assist. > > So far the fastest way I've found is using the `sum` builtin and > generators:: > > ordinalSum = sum(ord(x) for x in data) > ordinalSumSquared = sum(ord(x)**2 for x in data) > > This is about twice as fast as an explicit loop, but since it's going to > be processing massive amounts of data, the faster the better. Are there > any tricks I'm not thinking of, or perhaps helper functions in other > modules that I'm not thinking of? Two ideas: Use a lookup-table for ord(c)**2 Use array.array() $ cat summit.py import array data = "dere gewizzede bizzede bizz" * 1000 + chr(255) lookup = dict((i, i**2) for i in range(256)) def summit_str(data=data): return sum(ord(x) for x in data), sum(ord(x)**2 for x in data) def summit_array(data=data, lookup=lookup): a = array.array("B") a.fromstring(data) return sum(a), sum(lookup[x] for x in a) if __name__ == "__main__": assert summit_array() == summit_str() $ python -m timeit -s'from summit import summit_str as summit' 'summit()' 10 loops, best of 3: 32.2 msec per loop $ python -m timeit -s'from summit import summit_array as summit' 'summit()' 100 loops, best of 3: 13.4 msec per loop Your actual code may be even faster because you can read the bytes directly from the file. Peter From mtobis at gmail.com Mon Aug 20 01:52:53 2007 From: mtobis at gmail.com (Michael Tobis) Date: Mon, 20 Aug 2007 05:52:53 -0000 Subject: yet another indentation proposal In-Reply-To: <_49yi.9351$3x.6614@newssvr25.news.prodigy.net> References: <fEZxi.8855$9W6.6492@fe103.usenetserver.com> <13ci0oesdtlh871@corp.supernews.com> <_49yi.9351$3x.6614@newssvr25.news.prodigy.net> Message-ID: <1187589173.410862.132580@o80g2000hse.googlegroups.com> On Aug 19, 11:51 pm, James Stroud <jstr... at mbi.ucla.edu> wrote: > What's wrong with just saying the current indent level? I'd much rather > hear "indent 4" than "tab tab tab tab". Alternatively, you might also consider writing a simple pre and postprocessor so that you could read and write python the way you would prefer In that you could cope with the existing code base and the existing compiler could cope with code you write. mt From ldo at geek-central.gen.new_zealand Tue Aug 28 01:33:54 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 28 Aug 2007 17:33:54 +1200 Subject: include folder References: <mailman.43.1188251054.28954.python-list@python.org> Message-ID: <fb0bve$lhc$1@lust.ihug.co.nz> In message <mailman.43.1188251054.28954.python-list at python.org>, Raul Araya wrote: > Today while trying to install a python based program I got an > error regarding the Python.h file that should be in the /include/Phyton2.3 > folder. So I went looking for the file but it wasn't there, I mean the > whole folder /Phyton2.3 inside the /usr/include directory was not there. Perhaps that should be "/usr/include/python2.3"? If you try the command dpkg -L python-dev it should list all the files and directories that were installed as part of the python-dev package, including the bits that go in /usr/include. From jim724 at gmail.com Wed Aug 22 15:18:44 2007 From: jim724 at gmail.com (Jimmy) Date: Wed, 22 Aug 2007 19:18:44 -0000 Subject: NOW WATCH Satellite TV on your PC without Paying Monthly FEES Message-ID: <1187810324.107527.267460@z24g2000prh.googlegroups.com> Fed Up With Paying a Monthly Fee For A Handful of Channels That Don't Satisfy Your Needs? Most people pay $19 to $90 a month for a very limited number of TV channels. If you fall into this category and want out, you can get solution at the link below.... http://satellitetvonpc.yoll.net/ From pict100 at gmail.com Sun Aug 26 09:16:45 2007 From: pict100 at gmail.com (DarkBlue) Date: Sun, 26 Aug 2007 06:16:45 -0700 Subject: Kinterbasdb needs new maintainer Message-ID: <1188134205.788503.63960@l22g2000prc.googlegroups.com> Sorry to interrupt the regular programming here . As has been reported on some websites the maintainer of kinterbasdb David Rushby has died last month after a diving accident. Kinterbasdb is the python wrapper around the Firebird database api and an excellent opensource project. The hope is , that this message will reach someone in the opensource developer community , who is willing to step up and continue the great work done by David . Thank you http://www.firebirdnews.org/?p=1252 http://kinterbasdb.sourceforge.net/ From steven.bethard at gmail.com Thu Aug 16 17:55:30 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 16 Aug 2007 15:55:30 -0600 Subject: advice about `correct' use of decorator In-Reply-To: <mailman.2074.1187294411.22759.python-list@python.org> References: <mailman.2074.1187294411.22759.python-list@python.org> Message-ID: <2vydnTio1a9IWlnbnZ2dnUVZ_jKdnZ2d@comcast.com> Gerardo Herzig wrote: > Hi all. I guess i have a conceptual question: > Im planing using a quite simple decorator to be used as a conditional > for the execution of the function. I mean something like that: > > @is_logued_in > def change_pass(): > bla > bla > > And so on for all the other functions who needs that the user is still > loged in. > > where obviosly the is_logued_in() function will determine if the dude is > still loged in, and THEN execute change_pass(). If the dude is not loged > in, change_pass() is NOT executed at all. Instead, it will be redirected > to the `login' screen. > > Something in my mind tells me that this is not the pythonic way...But i > like the idea, so please tell me that im in the right way :) Django does it almost exactly this way: http://www.djangoproject.com/documentation/authentication/#the-login-required-decorator STeVe From twisted0n3 at gmail.com Mon Aug 20 20:54:54 2007 From: twisted0n3 at gmail.com (Twisted) Date: Tue, 21 Aug 2007 00:54:54 -0000 Subject: Latest models of Gibson guitars In-Reply-To: <9K6dnY8HnIUNHlTbnZ2dnUVZ_gGdnZ2d@comcast.com> References: <1187544898.289948.322160@22g2000hsm.googlegroups.com> <1187548916.909340.37420@k79g2000hse.googlegroups.com> <1187579396.285862.186860@e9g2000prf.googlegroups.com> <9K6dnY8HnIUNHlTbnZ2dnUVZ_gGdnZ2d@comcast.com> Message-ID: <1187657694.106990.266830@z24g2000prh.googlegroups.com> On Aug 20, 8:05 am, Lew <l... at lewscanon.com> wrote: > Twisted wrote: > > On Aug 19, 2:41 pm, vedrandeko... at v-programs.com wrote: > >> This is a newsgroup of programming language Python, stop with this! > > > Python?! Python is as off-topic here as guitars, unlike, say, Java... > > When referring to "this" newsgroup or "here", one must remember that this is a > cross-posted thread You assume it was obvious to me that it was in the first place. But I didn't see it in any other group that I read, and the news interface that I use just, by default, shows me the subject, from, and date and the name of the one newsgroup that I'm reading. If the message then says something absurd, like "this is a newsgroup about Python" when I'm reading it in cljp, well, what do you expect? :P Again you seem to assume I have more context than I actually do when I read postings. At least when it's cross-posted if I for some reason decided to look closely at all of the headers that it was cross-posted would become quickly apparent. Previously, though, you even expected me to know at a glance when a message was multi-posted separately to various groups, though nothing in the headers would indicate this. Only doing a Google search for every message's content would reliably detect multi-posting, and I'm not about to start doing that just to satisfy *you*. :P From ivoras at __fer.hr__ Fri Aug 31 13:09:58 2007 From: ivoras at __fer.hr__ (Ivan Voras) Date: Fri, 31 Aug 2007 19:09:58 +0200 Subject: Biased random? In-Reply-To: <1188506180.227794.20030@q5g2000prf.googlegroups.com> References: <favd0c$fcu$1@ss408.t-com.hr> <mailman.80.1188332647.28954.python-list@python.org> <fb77bq$jtk$1@ss408.t-com.hr> <1188506180.227794.20030@q5g2000prf.googlegroups.com> Message-ID: <fb9i18$sgv$1@ss408.t-com.hr> Mark Dickinson wrote: > That's because the call to abs() usually collapses two values to one > (e.g. -2 and 2 both end up being 2), > but there's only one integer n for which abs(n) == 0. Ah. Need to sleep more. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 258 bytes Desc: OpenPGP digital signature URL: <http://mail.python.org/pipermail/python-list/attachments/20070831/aecc5abb/attachment.sig> From jstroud at mbi.ucla.edu Thu Aug 16 23:37:57 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 16 Aug 2007 20:37:57 -0700 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: <1187320510.165621.224150@l22g2000prc.googlegroups.com> References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> <fa2m4s$k1g$1@daisy.noc.ucla.edu> <1187311999.880853.135780@j4g2000prf.googlegroups.com> <mailman.2091.1187317979.22759.python-list@python.org> <1187320510.165621.224150@l22g2000prc.googlegroups.com> Message-ID: <fa356l$urr$1@daisy.noc.ucla.edu> beginner wrote: > On Aug 16, 9:32 pm, Carsten Haese <cars... at uniqsys.com> wrote: > >>On Fri, 2007-08-17 at 00:53 +0000, beginner wrote: >> >>>$b is supposed to be a hash-table of hash-table. If a key exists in >>>$b, it points to another hash table. The $a=$b->{"A"} ||={} pattern is >>>useful when you want to add records to the double hash table. >> >>>For example, if you have a series of records in the format of (K1, K2, >>>V), and you want to add them to the double hash-table, you can do >>>$a=$b->{K1} || ={} >>>$a->{K2}=V >> >>What is the best solution in Perl need not be the best solution in >>Python. In Python you should just use a tuple as your dict key, i.e. >>a[k1,k2] = v, unless you have some other constraints you're not telling >>us. >> >>HTH, >> >>-- >>Carsten Haesehttp://informixdb.sourceforge.net > > > I use tuples this way all the time. It is indeed very neat. But it is > not a replacement for double hash-table. If I want to retrieve > information just by K1, it is not efficient to index on (K1, K2). > Define "efficient". As in typing? Lookup should be the same speed for all keys because its a hash-table. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From wolf_tracks at invalid.com Fri Aug 17 13:59:19 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Fri, 17 Aug 2007 17:59:19 GMT Subject: Python and Tkinter Programming--Expensive! Message-ID: <Xllxi.9066$3x.1781@newssvr25.news.prodigy.net> Why is the book in Subject (author is Grayson) so expensive? $100 on Amazon and $195 on ABE. Aren't there alternatives? -- Wayne Watson (Nevada City, CA) Web Page: <speckledwithStars.net> From kguan at corp.netease.com Thu Aug 16 22:32:26 2007 From: kguan at corp.netease.com (Kyo Guan) Date: Fri, 17 Aug 2007 10:32:26 +0800 Subject: why psyco using more memery in liunx? Message-ID: <005c01c7e076$da20e4a0$811ba8c0@kyom> Hi all: When you import psyco in python2.5, you can see the memery grow up near 40MB in linux. but the same version python and psyco, is only grow up 1MB under windows. kyo From larry.bates at websafe.com Thu Aug 23 16:45:21 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 23 Aug 2007 15:45:21 -0500 Subject: How would I go about making a file open. Not the way you might think. In-Reply-To: <mailman.159.1187857019.32294.python-list@python.org> References: <eb79828c0708221959t18dd4024m251c1eac7732ec1f@mail.gmail.com> <mailman.159.1187857019.32294.python-list@python.org> Message-ID: <ntSdnapifutBbFDbnZ2dnUVZ_tWtnZ2d@comcast.com> Hendrik van Rooyen wrote: > Lamonte Harris wrote: > >> Basically you can open a file by double clicking, and by default it would open > w/ what every program you have it set >to. Most text files would open in > notepad. How can I make a txt open so that notepad opens w/ the content in it > by >using just python. > > I asked this question just yesterday - and Tim Golden answered: > > os.startfile() > > - Hendrik > Actually os.startfile('filename.txt') will open the file with whatever application is associated with .txt files on that machine. That could be different from notepad if the user has chosen to override the defaults. os.system('notepad.exe c:\\junk.txt') will force notepad.exe to load and it will load the file specified. All depends on what you want to do. -Larry From __peter__ at web.de Wed Aug 22 06:04:28 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Aug 2007 12:04:28 +0200 Subject: Dispatching default application for file, cross platform. References: <01e101c7e48d$e0e9f860$03000080@hendrik> <mailman.106.1187774244.32294.python-list@python.org> Message-ID: <fah1nc$cqq$02$1@news.t-online.com> Tim Golden wrote: > Hendrik van Rooyen wrote: >> How do I do the equivalent of clicking (in SuSe) or double clicking (in >> Windows) on a file? >> >> In effect I want to tell the OS - take this file and feed it to the >> application that is registered for it. > os.startfile Unfortunately this is Windows-only. For KDE you can use $ kfmclient exec yourfile Peter From dale at riverhall.nospam.co.uk Sun Aug 5 20:10:19 2007 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Mon, 06 Aug 2007 01:10:19 +0100 Subject: MIMEText breaking the rules? References: <rFZri.84932$ml1.74260@fe16.usenetserver.com> <h7j5b3dv43hgu7qrvg3anprat4pq86jfsg@4ax.com> Message-ID: <MFtti.88126$ml1.2189@fe16.usenetserver.com> Tim Roberts wrote: > Dale Strickland-Clark <dale at riverhall.nospam.co.uk> wrote: >> >>The email module's mimetext handling isn't what you might expect from >>something that appears to behave like a dictionary. >>... >>Having apparently REPLACED my recipient, what I've ended up with is both >>of them. > > This behavior is documented in Message.Message, from which MIMEText > eventually inherits. If you want to start over, delete the item: > > del Msg["To"] > > I would have to say that the existing behavior is more intuitive for an > email object. Thanks for the info. -- Dale Strickland-Clark Riverhall Systems - www.riverhall.co.uk From frikker at gmail.com Thu Aug 16 13:58:53 2007 From: frikker at gmail.com (frikk) Date: Thu, 16 Aug 2007 10:58:53 -0700 Subject: Accessing Windows Network Share? Message-ID: <1187287133.737105.169960@19g2000hsx.googlegroups.com> I previously posted about accessing SharePoint over the web. Well I have since given up any easy means of doing this, since something else has perked my interest. Instead of going to http://sharepoint/site, why not just access \\sharepoint\site\ directly? So my question is this - How do I access that network share? If I go to start -> run, and type in "\\SharPointServer\Site\Folder", windows explorer will pop up with it. I suppose I could have a little batch script that python runs to map the drive to a local letter, like J:, but this does not seem necessary. Suggestions? This does not work, for obvious reasons: >>> import glob.glob >>> glob.glob("\\\\server\\folder\\*") [] Thanks guys! Blaine From xavier.martinezhidalgo at gmail.com Wed Aug 29 04:58:52 2007 From: xavier.martinezhidalgo at gmail.com (xavim) Date: Wed, 29 Aug 2007 08:58:52 -0000 Subject: Error handling in file generation (Pythonic way: with / decorators?) Message-ID: <1188377932.955314.104570@r29g2000hsg.googlegroups.com> Hi everyone, I am writing a small tool that generates a file from a list of sources. The function dictgen(dictfile, *sources) takes a list of sources path and an open file object and does the processing. I am having some problems with how to do proper error handling. One of the requirements is that the destination file should not be created if there is any error in the processing. I have come out with the following code:: dictfile = file(dictpath, 'w') try: try: dictgen(dictfile, *sources) finally: dictfile.close() except error, e: os.remove(dictpath) sys.exit(str(e)) except: os.remove(dictpath) but it appears to me as somewhat ugly. Is there any more Pythonic way to abstract this kind of error handling? Maybe 'with' or decorators could be useful here? Thanks, Xavi From david at asdf.asdf Sun Aug 26 21:54:37 2007 From: david at asdf.asdf (bambam) Date: Mon, 27 Aug 2007 11:54:37 +1000 Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com><1187898049.734696.9500@l22g2000prc.googlegroups.com><13csi2tn49esmc3@corp.supernews.com> <mailman.230.1187928865.32294.python-list@python.org> <13csqk47j0c56b0@corp.supernews.com> <CqSdnRl2x8928FPbnZ2dnUVZ_jSdnZ2d@speakeasy.net> <13ct7v3qn2v5206@corp.supernews.com> <13d00hu2mflt01b@corp.supernews.com> Message-ID: <13d4bn9kchd9u94@corp.supernews.com> c = sorted(set(a)-set(b)) although for me :~( that is another step more obscure than c = list(set(a)-set(b)) c.sort() Bags don't seem to be built in to my copy of Python, and although I'm interested in why lists don't support the difference operation, I don't want to get away from standard Python. Steve. "Scott David Daniels" <daniels at dsl-only.net> wrote in message news:13d00hu2mflt01b at corp.supernews.com... > bambam wrote: >>> The reason that lists don't have set-like methods is because >>> lists aren't sets -- lists can contain duplicate elements > and they are ordered. I'd have used sets if I was sure you > meant [1,2,3] to mean the same thing as [3,1,2] and no duplicates. > >> Interesting point -- if that's all there is in it, then lists should >> have difference and intersection methods. Not because they >> are the same as sets -- because they are slightly different than >> sets. In this case it doesn't matter - my lists don't contain >> duplicate elements this time - but I have worked with lists in >> money market and in inventory, and finding the intersection >> and difference for matching off and netting out are standard >> operations. > Here you seem to be talking about multisets (also called bags). > They have more fully defined algebraic properties analogous to sets. > > bag([1,2,3,3,4]) == bag([3,1,2,4,3]) != bag([1,2,3,4]) > bag([1,2,2,3]) - bag([1,2]) == bag([2,3]) > bag([1,2,3]) - bag([3,4]) == bag([1]) > >>>> Excellent. By symmetry, I see that "list" casts the set back into a >>>> list. > Some will say 'sorted' is a better conversion of a set to list, since > the result is well-defined. > > --Scott David Daniels > Scott.Daniels at Acm.Org From horpner at yahoo.com Tue Aug 14 14:27:16 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 14 Aug 2007 18:27:16 GMT Subject: curses library References: <mailman.1980.1187115104.22759.python-list@python.org> Message-ID: <slrnfc3t7e.1p0.horpner@FIAD06.norwich.edu> On 2007-08-14, Ghirai <ghirai at ghirai.com> wrote: > I need to write a console application. > > Are there any wrappers around curses/ncurses? > Or any other similar libraries? The answer depends on your chosen platform. Python hasn't got a cross-platform console library as one of its included batteries. First try the curses module. It does come with Python on systems with a curses port. For Windows, there's the Effbot's console module. http://effbot.org/zone/console-index.htm Or go to plan B: Use a Tkinter or other GUI interface's text widget. -- Neil Cerutti From http Thu Aug 2 16:27:57 2007 From: http (Paul Rubin) Date: 02 Aug 2007 13:27:57 -0700 Subject: __call__ considered harmful or indispensable? References: <mailman.1527.1186079415.22759.python-list@python.org> Message-ID: <7xfy31smuq.fsf@ruckus.brouhaha.com> skip at pobox.com writes: > In this particular case it was clearly unnecessary and just obfuscated the > code. I'm wondering, are there some general cases where __call__ methods of > a user-defined class are simply indispensable? I don't know about "indispensable" but __call__ is convenient sometimes and I do use it. I've wished that modules supported call, so I could say import foo x = foo(3) instead of having to say x=foo.foo(3) or something like that. From ronpro at cox.net Tue Aug 28 16:11:11 2007 From: ronpro at cox.net (Ron Provost) Date: Tue, 28 Aug 2007 16:11:11 -0400 Subject: Tix HList missing at least one method Message-ID: <003901c7e9af$94e25d00$6501a8c0@aristotle> According to the Tix documentation online, HList has an info_bbox() method which returns the bounding box of a given item in the HList. However, when I try to call this method, I get an attribute error. Looking at Tix.py I see that info_bbox() is not implemented. Hazarding a chance (mostly by looking at the other method implementation) I see if I can define it myself. def info_bbox( self, entry ): return [ int(pos) for pos in self.tk.call( self._w, 'info', 'bbox', entry).split() ] When I use this implementation it works. Why's info_bbox() been left out of HList? I can't formulate a work-around for what I'm trying to do. I need info_bbox(). Here's why: I'm currently working on a project which involves some fairly complex GUIs. It displays data in the form of an outline which the user can edit, it also generates web pages. To allow a natural feel to editing the order of the items in the outline, I decided to make use of the Tkinter drag and drop module: Tkdnd. To do this correctly, I need to do a bit of arithmetic with screen coordinates while in a drag operation (so I can change the cursor during the drag) so that I can determine if my current drag position (potential drop position) is above, below or as a child of some other item in the outline. The easiest way to do this is to get the bounding box of the nearest items. Thanks, Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070828/6fc5c204/attachment.html> From gmcalendar at gmail.com Thu Aug 23 11:31:44 2007 From: gmcalendar at gmail.com (gmcalendar at gmail.com) Date: Thu, 23 Aug 2007 15:31:44 -0000 Subject: simple spider in python In-Reply-To: <1187880988.813113.20350@l22g2000prc.googlegroups.com> References: <1187876014.845912.236690@e9g2000prf.googlegroups.com> <1187879398.007797.128510@i13g2000prf.googlegroups.com> <1187880988.813113.20350@l22g2000prc.googlegroups.com> Message-ID: <1187883104.337285.270910@q4g2000prc.googlegroups.com> Well, it turned out that google since Dec 2006 is not giving out SOAP api keys anymore. What a shame! any tip? ;-) From countblabula at yahoo.com Mon Aug 6 14:24:53 2007 From: countblabula at yahoo.com (Lee Fleming) Date: Mon, 06 Aug 2007 11:24:53 -0700 Subject: Something in the function tutorial confused me. In-Reply-To: <slrnfbeofu.20s.horpner@FIAD06.norwich.edu> References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <slrnfbe1fd.n4.horpner@FIAD06.norwich.edu> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <slrnfbeofu.20s.horpner@FIAD06.norwich.edu> Message-ID: <1186424693.529497.217040@w3g2000hsg.googlegroups.com> Thanks for all the help, everyone. I guess I was confused with default arguments that were mutable and immutable. I will continue to look over these posts until I understand what is happening. I cannot believe the number of helpful responses I got! From programmer.py at gmail.com Fri Aug 17 08:55:45 2007 From: programmer.py at gmail.com (programmer.py at gmail.com) Date: Fri, 17 Aug 2007 12:55:45 -0000 Subject: Naming dictionaries recursively In-Reply-To: <1187354296.177606.273300@22g2000hsm.googlegroups.com> References: <1187354296.177606.273300@22g2000hsm.googlegroups.com> Message-ID: <1187355345.874107.64160@r34g2000hsd.googlegroups.com> On Aug 17, 7:38 am, TYR <a.harrow... at gmail.com> wrote: > I'd like to do something like this; iterate through a file which > consists of data stored in dictionary format, one dict on each line, > and read each line into a new dict using one of the values in the dict > as its name... > > for example: > > stuff = open('data.txt') > for eachLine in stuff: > name{} > name = eachLine > ....and then do something clever to extract the value of the key > (name) from the line and use it as the dictionary's name. > > A line from data.txt would look like this: {'name' : Bob, 'species' : > Humboldt, 'colour' : red, 'habits' : predatory}. Aim is to call one of > them by name, and merge the values in that dictionary into a string > pulled from another source. I'm not sure I follow exactly what you want to do, but you can always use eval for each line in that file. But, if the line you provided for testing is one that actually comes from the file, you'll have to patch it before you eval the line. I think this regexp will work. Be careful though, it assumes that all values are whole words, that is they don't have spaces in them. # This is far from ideal, but you get what you pay for :). re.sub(r':\s*(\w+)(,|})', r"': '\1'\2", line) Anyway, after you've cleaned up your input line this ought to work: d = eval(line) Also, if you're building the input file from within a python program, maybe you should consider the pickle module. That ought to give you a good start... jw From nytrokiss at gmail.com Mon Aug 20 10:58:27 2007 From: nytrokiss at gmail.com (James Matthews) Date: Mon, 20 Aug 2007 07:58:27 -0700 Subject: Problem with Thread.join() In-Reply-To: <op.txcl3yoox6zn5v@a98gizw.cpe.telecentro.net.ar> References: <496954360708131610i62c0a63aneb7c39d23a052ac0@mail.gmail.com> <op.txcl3yoox6zn5v@a98gizw.cpe.telecentro.net.ar> Message-ID: <8a6b8e350708200758w640fd7c4w5bd19fb53decde71@mail.gmail.com> Post some code so we can see the issue! I would say that the issue is where your function that you are calling isn't exiting! On 8/20/07, Gabriel Genellina <gagsl-py2 at yahoo.com.ar> wrote: > > En Mon, 13 Aug 2007 20:10:53 -0300, Robert Dailey <rcdailey at gmail.com> > escribi?: > > > I have a class that derives from threading.Thread. To signal the thread > > to > > exit its infinite loop, I set an Event. Once the thread checks > > Event.isSet() > > and it is true, it proceeds to break out of the loop and exit the > > function. > > In the main thread, right after calling Event.set(), I call > > Thread.join() to > > wait on the thread to exit. However, if I call Thread.join() the > > application > > locks up because for some reason calling Thread.join() prevents the > > thread > > from exiting. I don't know why. Any help? Thanks... > > Conceptually you're doing it the right way. Post some code demonstrating > the problem... > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list -- http://www.goldwatches.com/ http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070820/c1e77856/attachment.html> From grflanagan at yahoo.co.uk Wed Aug 1 17:28:39 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: Wed, 01 Aug 2007 14:28:39 -0700 Subject: Awkward format string In-Reply-To: <1185984697.605529.157110@g12g2000prg.googlegroups.com> References: <1185984697.605529.157110@g12g2000prg.googlegroups.com> Message-ID: <1186003719.783219.104200@r34g2000hsd.googlegroups.com> On Aug 1, 6:11 pm, beginner <zyzhu2... at gmail.com> wrote: > Hi, > > In order to print out the contents of a list, sometimes I have to use > very awkward constructions. For example, I have to convert the > datetime.datetime type to string first, construct a new list, and then > send it to print. The following is an example. > > x=(e[0].strftime("%Y-%m-%d"), e[1].strftime("%Y-%m-%d"))+e[2:] > print >>f, "%s\t%s\t%d\t%f\t%f\t%f\t%d" % x > > e is a tuple. x is my new tuple. > > Does anyone know better ways of handling this? > YEARMONTHDAY = "%Y-%m-%d" def strftime(dt): return dt.strftime(YEARMONTHDAY) def tostring(data): return tuple(strftime(x) for x in data[:2]) + data[2:] From jstroud at mbi.ucla.edu Wed Aug 22 18:54:54 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 22 Aug 2007 15:54:54 -0700 Subject: introspection and functions In-Reply-To: <1187819949.515982.15450@r23g2000prd.googlegroups.com> References: <1187819949.515982.15450@r23g2000prd.googlegroups.com> Message-ID: <B33zi.4126$Oo.317@newssvr17.news.prodigy.net> yagyala wrote: > Hi. I would like to be able to tell, at run time, how many parameters > a function requires. Ideally I would like to be able to tell which are > optional as well. I've tried looking at the functions attributes, but > haven't found one that helps in this. How can I do this? > > Thanks > py> def doit(a, b, c, x=14): ... pass ... py> doit.func_code.co_argcount 4 py> doit.func_code.co_varnames ('a', 'b', 'c', 'x') py> doit.func_defaults (14,) James From m.elston at advantest-ard.com Mon Aug 27 14:35:17 2007 From: m.elston at advantest-ard.com (Mark Elston) Date: Mon, 27 Aug 2007 11:35:17 -0700 Subject: convert non-delimited to delimited In-Reply-To: <1188237563.889663.228970@o80g2000hse.googlegroups.com> References: <1188237563.889663.228970@o80g2000hse.googlegroups.com> Message-ID: <13d66b6b0fnke49@corp.supernews.com> * RyanL wrote (on 8/27/2007 10:59 AM): > I'm a newbie! I have a non-delimited data file that I'd like to > convert to delimited. > > Example... > Line in non-delimited file: > 0139725635999992000010100534+42050-102800FM-15+1198KAIA > > Should be: > 0139,725635,99999,2000,01,01,00,53,4,+42050,-102800,FM-15,+1198,KAIA > > What is the best way to go about this? I've looked all over for > examples, help, suggestions, but have not found much. CSV module > doesn't seem to do exactly what I want. Maybe I'm just missing > something or not using the correct terminology in my searches. Any > assistance is greatly appreaciated! Using Python 2.4 > Since you have to know, a priori, how to break the input string I assume that these fields are of fixed length. You can use the following to do what you want: >>> a="0139725635999992000010100534+42050-102800FM-15+1198KAIA" >>> print "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s" % (a[0:4],a[4:10],a[10:15],a[15:19],a[19:21],a[21:23],a[23:25], a[25:27],a[27],a[28:34],a[34:41],a[41:46],a[46:51],a[51:]) which results in the following output: 0139,725635,99999,2000,01,01,00,53,4,+42050,-102800,FM-15,+1198,KAIA Mark From carsten at uniqsys.com Fri Aug 3 21:19:31 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 03 Aug 2007 21:19:31 -0400 Subject: How to pass a reference to the current module In-Reply-To: <f90im3$8ms$1@daisy.noc.ucla.edu> References: <f90gsg$ek4$1@zinnia.noc.ucla.edu> <f90im3$8ms$1@daisy.noc.ucla.edu> Message-ID: <1186190371.3263.17.camel@localhost.localdomain> On Fri, 2007-08-03 at 17:53 -0700, James Stroud wrote: > James Stroud wrote: > > Basically, what I am trying to acomplish is to be able to do this in any > > arbitrary module or __main__: > > > > > > funcname = determined_externally() > > ModuleUser.do_something_with(AModule, funcname) > > > > > > Ideally, it would be nice to leave out AModule if the functions were > > designed in the same namespace in which do_something_with is called. > > > Is this the preferred way? > > > import sys > def do_something_with(funcname, amodule=None): > if amodule is None: > function = sys._getframe(1).f_locals[funcname] > else: > function = getattr(amodule, funcname) > [etc.] This seems to confirm my suspicion that the do_something_with function doesn't actually need a reference to the module, it only needs a reference to the function to call. Maybe your hurdle is how to obtain a reference to a function from the current module when all you have is the name of the function in a string. The answer to that would be "globals()[funcname]". -- Carsten Haese http://informixdb.sourceforge.net From gandalf at shopzeus.com Fri Aug 17 15:34:35 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 17 Aug 2007 21:34:35 +0200 Subject: Encryption and hashing In-Reply-To: <1187377630.017794.36510@50g2000hsm.googlegroups.com> References: <1187377630.017794.36510@50g2000hsm.googlegroups.com> Message-ID: <46C5F84B.20109@shopzeus.com> > For who knows any of criptography I comment that you can use > algorithms as secure as Rijndael, Twofish, or Serpent with the CFB > cipher mode. And for hash you can use RIPEMD, SHA-2 or WHIRLPOOL. > As I recall, PyCrypto can also use these, and many others. And it can also do RSA. > And the best is that there are wrappers for Python [5] [6]. > One advantage of PyCrypto is that it works on many platforms. If standard C extensions are not available, it will fall back to a pure python implementation. Well yes, sometimes it is slow. But it is also much easier to use than pyOpenSSL, for example. (BTW you forgot to mention some other popular ones, like pyOpenSSL, mcrypto2 etc.) Laszlo From mccredie at gmail.com Thu Aug 16 12:45:46 2007 From: mccredie at gmail.com (Matt McCredie) Date: Thu, 16 Aug 2007 09:45:46 -0700 Subject: threads, mutual exclusion, and lists In-Reply-To: <46C3F78B.9080305@v.loewis.de> References: <1187206583.255588.57920@e9g2000prf.googlegroups.com> <mailman.2039.1187219345.22759.python-list@python.org> <46C3F78B.9080305@v.loewis.de> Message-ID: <9e95df10708160945h2bcaf978s50a4b390af7e4f5f@mail.gmail.com> > Why do you think they are not? Because they aren't. You even mentioned that a few operations that aren't atomic. If operations are atomic it isn't necessarily because of the design of the list, but the design of CPython. More specifically the GIL. I don't mean to imply that you can't get a multi-threaded app to communicate using lists, but the Queue is explicitly built for it and better suited. Matt From naga86 at gmail.com Mon Aug 20 08:58:52 2007 From: naga86 at gmail.com (Nagarajan) Date: Mon, 20 Aug 2007 12:58:52 -0000 Subject: Server-side scripting in python Message-ID: <1187614732.519547.296020@j4g2000prf.googlegroups.com> Hi group, I need to develop a web application. I am in a fix as to choose among the various server-side scripting options. I want to explore python (am a newbie) to gain expertise and upon search, I learnt about PSP(Python Server Pages) that uses Jython as its scripting language. Is it a better option over PHP or Perl? Could anyone point out the pros and cons of using PSP over others? Help much appreciated. From bgoldenberg at gmail.com Thu Aug 9 15:16:24 2007 From: bgoldenberg at gmail.com (Benjamin Goldenberg) Date: Thu, 09 Aug 2007 19:16:24 -0000 Subject: Querying Graphics Card Name Message-ID: <1186686984.160312.175270@i13g2000prf.googlegroups.com> Hello, I would like to find out the name of the graphics card of the machine my program is running on. I have looked into the pyopengl module, and using them to query the card, but it seems like there ought to be a simpler way to find this out without setting up a glcontext. Does anyone have any ideas? Thanks, Benjamin From david at nospam.spam Thu Aug 9 01:25:27 2007 From: david at nospam.spam (david) Date: Thu, 09 Aug 2007 15:25:27 +1000 Subject: wxPython before MainLoop Message-ID: <13bl9a75laqcm70@corp.supernews.com> I'd like to refresh the display before I start the main loop. I have code like this: app = App() app.Show() app.long_slow_init() app.MainLoop() The main frame partly loads at Show, but because the mainloop has not started yet, the display does not update until long_slow_init() finishes. Alternatively, I could code app = App() app.long_slow_init() app.Show() app.MainLoop() Which would give me a crisp Show, but there would be a long slow wait before the app showed any activity at all. I would need a splash screen. I'd rather not have a splash screen (and I don't know how anyway). I'd like to just make app.Show() finish correctly before running long_slow_init. Is there a wx internal method that I can use to give Windows the opportunity to finish painting the frame before I run long_slow_init()? Or is there a better idea? (david) From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Aug 21 07:51:13 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 21 Aug 2007 13:51:13 +0200 Subject: The folder a script is executed in References: <1187687436.476773.276550@22g2000hsm.googlegroups.com> <1187688437.358293.322460@22g2000hsm.googlegroups.com> <5ivqm3F3rg15jU1@mid.individual.net> <1187691170.820193.99270@r34g2000hsd.googlegroups.com> Message-ID: <5j01thF3sap0kU1@mid.individual.net> Ant wrote: > Fair point. On Win32 sys.argv[0] always seems to give the full > path rather than the relative path Strange. > - hadn't realised it was different for linux (?). Yes, I used GNU/Linux for the example. Regards, Bj?rn -- BOFH excuse #148: Insert coin for new game From michele.simionato at gmail.com Tue Aug 14 00:58:41 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 14 Aug 2007 04:58:41 -0000 Subject: decorators - more than just syntactic sugar In-Reply-To: <yfszm0v49as.fsf@gmail.com> References: <46be005e$0$13866$ba620e4c@news.skynet.be> <1186985383.303334.110230@19g2000hsx.googlegroups.com> <yfszm0v49as.fsf@gmail.com> Message-ID: <1187067521.661978.254100@22g2000hsm.googlegroups.com> On Aug 13, 7:46 pm, Alexander Schmolck <a.schmo... at gmail.com> wrote: > Michele Simionato <michele.simion... at gmail.com> writes: > > Well, I argued may times that syntactic sugar is important (all Turing > > complete languages differs by syntactic sugar only) > > Although I agree that "mere" syntactic sugar matters, I think you're > overstating the point. I would argue that most people would understand > syntactic sugar as equivalent to a (very) localized program transformation. > Things like first class continuations clearly aren't syntactic sugar in that > sense. > > 'as I don't think I am overstating my point. I am just pointing out a sloppiness in the definition of "syntactic sugar". You are right that most people understand it as ?a somewhat trivial program transformation". However most people tend to forget that by a succession of somewhat trivial program transformations you can get quite a lot. Look, a compiled language is just a whole big lot of syntactic sugar over assembly language! An even continuations can be implemented in terms of macros. the quintessence of syntactic sugar (as you know better than me). You are right that this require a global program transformation, it is a kind of heavy duty syntactic sugar, but still it is always syntactic sugar at the end. Then, you may decide that you want to use a different name from global program transformation, since syntactic sugar sounds diminutive, but then it is an issue of names ;) Michele Simionato From mroeloffs at gmail.com Mon Aug 20 10:17:03 2007 From: mroeloffs at gmail.com (mroeloffs at gmail.com) Date: Mon, 20 Aug 2007 07:17:03 -0700 Subject: datetime in microseconds In-Reply-To: <1187615746.655162.295570@z24g2000prh.googlegroups.com> References: <1187610776.755796.170990@r29g2000hsg.googlegroups.com> <1187615746.655162.295570@z24g2000prh.googlegroups.com> Message-ID: <1187619423.715120.293660@o80g2000hse.googlegroups.com> On Aug 20, 3:15 pm, John Machin <sjmac... at lexicon.net> wrote: > On Aug 20, 9:52 pm, mroelo... at gmail.com wrote: > > > Hi I have a time in microseconds, for example 0x8C905CBA7F84AF4. I > > want this to a normal view in hh:mm:ss DD:MM:YYYY. I tried with > > datetime, but it only takes a max of 1000000 microseconds is there > > another solution? > > Your question can be interpreted in two possible ways: > > 1. You have an interval or duration (independent of a calendar point) > and you want to express it in years, months, days, hours, etc. This is > not possible, due to the variable number of days in a month. The best > that you can do is express it as days, hours, etc. > > >>> microsecs = 0x8C905CBA7F84AF4 > >>> secs = microsecs // 1000000 # or round to nearest if you prefer > >>> mins, secs = divmod(secs, 60) > >>> hrs, mins = divmod(mins, 60) > >>> days, hrs = divmod(hrs, 24) > >>> days, hrs, mins, secs > > (7326893L, 11L, 1L, 16L) > > > > 2. You want to know the (Gregorian) calendar point that is > 0x8C905CBA7F84AF4 microseconds after some epoch. In this case you need > to specify what the epoch is. Then you can try something like: > > >>> datetime.datetime.fromordinal(1) + datetime.timedelta(microseconds=microsecs > > ) > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > OverflowError: date value out of range > > >>> # Whoops! > >>> years_approx = days / 365.25 > >>> years_approx > 20059.939767282682 > > Hmmm, one of us seems to be missing something ... Sorry, sorry, sorry it was the wrong value, it should be 0xE0E6FAC3FF3AB2. From evan at yelp.com Thu Aug 2 01:53:55 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 1 Aug 2007 22:53:55 -0700 Subject: calling superclass __init__ when superclass is object In-Reply-To: <cfb58d850708012215u24b8ce8aie7a02f99cd0d1137@mail.gmail.com> References: <cfb58d850708012215u24b8ce8aie7a02f99cd0d1137@mail.gmail.com> Message-ID: <cfb58d850708012253t4319ddadof16bd02dedf83a00@mail.gmail.com> On 8/1/07, Evan Klitzke <evan at yelp.com> wrote: > Hi list, > > I was reading this article: http://fuhm.net/super-harmful/ and didn't > understand the comment about calling super(Foo, self).__init__() when > Foo inherits only from object. Can someone on the list elaborate more > on why one should do this? I hate to reply to my own thread, but I read this article: http://www.python.org/download/releases/2.3/mro/ and I think I understand the rationale now. If you have: class Foo(object): # stuff here class Bar(object): # stuff here class Baz(Foo, Bar): # stuff here Then if Baz calls super(Baz, self).__init__() in its __init__, and Foo makes no call super(Foo, self).__init__(), then the constructor for Bar will never be called. -- Evan Klitzke <evan at yelp.com> From kyosohma at gmail.com Mon Aug 6 10:25:31 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 06 Aug 2007 07:25:31 -0700 Subject: Tkinter or wxpython? In-Reply-To: <mailman.1550.1186099225.22759.python-list@python.org> References: <op.tv98rva4wepdt4@ericb.pragmadev> <mailman.1550.1186099225.22759.python-list@python.org> Message-ID: <1186410331.905174.21370@q3g2000prf.googlegroups.com> On Aug 2, 7:00 pm, "wang frank" <f... at hotmail.co.jp> wrote: > Hi, > > I want to build a GUI to execut python script. I found TKinter and > wxpython. Which one is easier for a newbie? and which one is better? > > Thanks > > Frank > > _________________________________________________________________ > > http://clk.atdmt.com/GBL/go/msnjpqjl0060000010gbl/direct/01/ I've read that Tkinter doesn't scale well if you're writing complex GUIs. I haven't been able to test this hypothesis though. However, since I had to rewrite VBA apps into Python, to get the right "look and feel" I needed the widgets that wxPython provided. Since I started out with C++, I find wxPython better than Tkinter, but it's all pretty subjective. Try them both! Mike From erfc at caballista.org Wed Aug 1 22:33:37 2007 From: erfc at caballista.org (Art Deco) Date: Wed, 01 Aug 2007 20:33:37 -0600 Subject: What does this thread have to do with classical music, References: <7nnh7350b5h25ghocra72b23mmsnnkj8bh@4ax.com> <468e482b$0$97236$892e7fe2@authen.yellow.readfreenews.net> <4692df4a$0$4804$8f2e0ebb@news.shared-secrets.com> <469392cd$0$97226$892e7fe2@authen.yellow.readfreenews.net> <469445b3$0$4819$8f2e0ebb@news.shared-secrets.com> <4694e124$0$97214$892e7fe2@authen.yellow.readfreenews.net> <46957ef1$0$10227$8f2e0ebb@news.shared-secrets.com> <46963170$0$97261$892e7fe2@authen.yellow.readfreenews.net> <46981df7$0$12095$8f2e0ebb@news.shared-secrets.com> <46990784$0$97223$892e7fe2@authen.yellow.readfreenews.net> <4699297c$0$4706$4c368faf@roadrunner.com> <140720071431044860%erfc@caballista.org> <46a3a1a7$0$15115$8f2e0ebb@news.shared-secrets.com> <220720072148091069%erfc@caballista.org> <46a5385d$0$4832$8f2e0ebb@news.shared-secrets.com> <250720071834457296%erfc@caballista.org> <46aceaa5$0$13281$8f2e0ebb@news.shared-secrets.com> <290720071853200863%erfc@caballista.org> <46b12539$0$4807$8f2e0ebb@news.shared-secrets.com> Message-ID: <010820072033374341%erfc@caballista.org> ah <splifingate at gmail.com> wrote: >Art Deco wrote: >> ah <splifingate at gmail.com> wrote: >>>Art Deco wrote: >>>> ah <splifingate at gmail.com> wrote: >>>>>Art Deco wrote: >>>>>> ah <splifingate at gmail.com> wrote: >>>>>>>Art Deco wrote: >>>>>>>> Who wrote? >>>>>>>> >>>>>>>> >>>>>>>>>What does that have to do with classical music, snuhwolf? >>>>>>>> >>>>>>>>>What does that have to do with classical music, snuhwolf? >>>>>>>> >>>>>>>> How many more times will you be asking the same tired, lame questions, >>>>>>>> Tholen? >>>>>>> >>>>>>>Till 2056? >>>>>> >>>>>> At that point, he will have made the Thirty Years Pset War look like >>>>>> 1967 in the Sinai. >>>>> >>>>>It must have been Hell to keep a garden during those times. >>>>> >>>>>Did they all eat jerky, or what? >>>> >>>> Worse -- worm-laden hardtack. >>> >>>Luxury! >>> >>>Why, I remember when I was a lad . . . we used to watch the local churls >>>across the fences eating that well. >>> >>>We only had millings (and (occasionally) water) on Tuesdays and Fridays. >> >> Grog and hardtack, life is good! > >?Viva la basura! Vivat les ordures! -- Official Overseer of Kooks and Saucerheads for alt.astronomy Trainer and leash holder of: Honest "Clockbrain" John nightbat "fro0tbat" of alt.astronomy Tom "TommY Crackpotter" Potter <http://www.caballista.org/auk/kookle.php?search=deco> "You really are one of the litsiest people I know, Mr. Deco." --Kali, quoted endlessly by David Tholen as evidence of "something" From naga86 at gmail.com Thu Aug 23 05:21:40 2007 From: naga86 at gmail.com (Nagarajan) Date: Thu, 23 Aug 2007 09:21:40 -0000 Subject: Raw strings to normal strings conversion? In-Reply-To: <Xrbzi.21051$eY.3412@newssvr13.news.prodigy.net> References: <1187851660.209024.59860@l22g2000prc.googlegroups.com> <Xrbzi.21051$eY.3412@newssvr13.news.prodigy.net> Message-ID: <1187860900.740674.87180@e9g2000prf.googlegroups.com> On Aug 23, 1:21 pm, James Stroud <jstr... at mbi.ucla.edu> wrote: > Nagarajan wrote: > > Is there a way by which I could obtain normal string form of a raw > > string. > > XML CDATA is returned as raw string. But I need the string to actually > > escape special chars. > > > Any idea? > > This doesn't seem clear. Perhaps an example of what you get and what you > want it converted to. Here is an example: >> rawstr = r'a\nb' >> print rawstr a\nb Now I need this newstr to actually interpret '\n', in other words, to behave like a normal string. > > In the meantime, see if urllib.unquote() doesn't do what you need. > > James And yes, unquote doesn't help. From mccredie at gmail.com Fri Aug 24 19:01:59 2007 From: mccredie at gmail.com (Matt McCredie) Date: Fri, 24 Aug 2007 16:01:59 -0700 Subject: Problem w/ Tkinter In-Reply-To: <eb79828c0708241510g4decf9d8kb90c76d0b067c6c6@mail.gmail.com> References: <eb79828c0708241400n7d83028eh5ae4a2dd4c463f06@mail.gmail.com> <9e95df10708241432t2b974bd8n1168672cadaace22@mail.gmail.com> <eb79828c0708241510g4decf9d8kb90c76d0b067c6c6@mail.gmail.com> Message-ID: <9e95df10708241601v56e2908eh3b08eb1b8f3483be@mail.gmail.com> On 8/24/07, Lamonte Harris <pyth0nc0d3r at gmail.com> wrote: > How to fix my code, wth that doesn't help solve anything really.the Tkinter > tutorial doesn't even explain radio buttons correctly, let alone, everything > else. gah. can you give a answer that I can work from. You asked, "what can I do to fix this problem?". You stated this in the singular, implying that there was one problem with your code to fix. In reality, to fix your code you have to totally re-write it. You need to slowly work your way through tutorials and go through all the pain everyone else who has learned Python and Tkinter has had to go through if you want to be a compitent coder. I know these may seem like harsh words, so let me give you an example of working Radiobutton code. [code] import Tkinter as tk choices = {1:"One", 2:"Two", 3:"Three", 4:"Four"} def main(): root = tk.Tk() global v v = tk.IntVar() for i, name in choices.iteritems(): b = tk.Radiobutton(root, text=name, variable=v, value=i) b.pack(anchor='w') tk.Button(root, text="Action?", command=print_val).pack(anchor='w') root.mainloop() def print_val(): k = v.get() print k, choices[k] if __name__ == "__main__": main() [/code] I'm curious, what do you feel is incorrect about the Radiobutton explanation? It seemed to work for me. Matt From http Mon Aug 6 15:14:45 2007 From: http (Paul Rubin) Date: 06 Aug 2007 12:14:45 -0700 Subject: Tkinter or wxpython? References: <op.tv98rva4wepdt4@ericb.pragmadev> <mailman.1550.1186099225.22759.python-list@python.org> <1186410331.905174.21370@q3g2000prf.googlegroups.com> <7xps204tin.fsf@ruckus.brouhaha.com> <46B73DE4.6040405@codebykevin.com> <1186421115.402000.88080@x35g2000prf.googlegroups.com> <46B75F31.9070208@codebykevin.com> <1186425241.246492.144340@d30g2000prg.googlegroups.com> Message-ID: <7x4pjcqxui.fsf@ruckus.brouhaha.com> kyosohma at gmail.com writes: > Yeah...I would assume I would enjoy Tkinter more if I knew more tcl. > Until that day arrives though, it will probably still be fairly > confusing for me to figure out. I do like it's "pythonic" style > though. I've managed to program tkinter without knowing anything about tcl. This manual is good: http://infohost.nmt.edu/tcc/help/pubs/tkinter/ From steve at holdenweb.com Fri Aug 17 19:55:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 17 Aug 2007 19:55:24 -0400 Subject: Question about 'for' loop In-Reply-To: <496954360708171545m6a0eff61la5fe270145246eab@mail.gmail.com> References: <496954360708171545m6a0eff61la5fe270145246eab@mail.gmail.com> Message-ID: <fa5ch4$bel$1@sea.gmane.org> Robert Dailey wrote: > Hi, > > I noticed that the 'for' loop can be used inline with a list definition. > For example: > > print [i for i in mylist] > > My first question is what is the name for this? I couldn't find this > usage in the python docs; I only managed to learn about it through code > samples on the internet. > That there is a "list comprehension". > Secondly, I'm wondering how I can use this method of a for loop to > append strings to strings in a list. For example: > > mylist = [ > "Hello ", > "Hello again " > ] > > I should be able to do this: > > print [ i + "World" for i in mylist ] > > Which should yield the output: > > ["Hello World", "Hello again world"] > Who says you should? Beside you, that is. I am afraid the interpreter isn't psychic, and it doesn't have a DWIM [1] mode. > However, instead I get an error message saying "TypeError: cannot > concatenate 'str' and 'list' objects" > > How can I achieve the above? Thanks for reading. > It's just a matter of understanding the syntax in a little more depth. In a week's time it will be blindingly obvious. >>> nicknames = ["bozo", "newbie", "newless cloob", "and welcome to c.l.py"] >>> [("hello " + name) for name in nicknames] ['hello bozo', 'hello newbie', 'hello newless cloob', 'hello and welcome to c.l.py'] >>> So, treat item [-1] from that list as the real sentiment of this message: >>> [("hello " + name) for name in nicknames][-1] 'hello and welcome to c.l.py' regards Steve [1]: Do What I Mean [and never mind what I say ...] -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From steve at holdenweb.com Mon Aug 13 19:45:46 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 13 Aug 2007 19:45:46 -0400 Subject: Assignments and Variable Substitution In-Reply-To: <cfb58d850708131223y37ccb61y465fc2f964ad05e4@mail.gmail.com> References: <f9q2qn$i4v$1@solaris.cc.vt.edu> <cfb58d850708131223y37ccb61y465fc2f964ad05e4@mail.gmail.com> Message-ID: <f9qqf7$355$2@sea.gmane.org> Evan Klitzke wrote: > On 8/13/07, brad <byte8bits at gmail.com> wrote: >> I'd like to do something like this: >> >> var = '123' >> %s = [], %var >> >> So that, in the end, var is '123' and an empty list is named '123' as >> well. The list assignments are created during a loop. > > You can't assign a variable whose name is 123, but you can do this > sort of thing with setattr. > And why would you want a variable whose name is '123'? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bbxx789_05ss at yahoo.com Fri Aug 24 14:28:09 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 24 Aug 2007 11:28:09 -0700 Subject: I can't get value of entry box, Tinker In-Reply-To: <mailman.268.1187975584.32294.python-list@python.org> References: <eb79828c0708240816o182b1e75o67fc9b27b6475051@mail.gmail.com> <mailman.268.1187975584.32294.python-list@python.org> Message-ID: <1187980089.367178.81060@e9g2000prf.googlegroups.com> Matt McCredie wrote: > > What/should I, can I do? > > Fix your code? > > > def login(): > > global e2,e1 > > print e2.get() > > print e1.get() > > That should work. > > Matt Try something like this: import Tkinter as tk root = tk.Tk() entry = tk.Entry(root) button = tk.Button(root, text="print text in textbox") def on_button_click(event): print entry.get() button.bind("<Button-1>", on_button_click) entry.pack() button.pack() root.mainloop() From sjmachin at lexicon.net Thu Aug 2 19:30:39 2007 From: sjmachin at lexicon.net (John Machin) Date: Thu, 02 Aug 2007 16:30:39 -0700 Subject: (no) fast boolean evaluation ? In-Reply-To: <mailman.1546.1186096771.22759.python-list@python.org> References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> <mailman.1546.1186096771.22759.python-list@python.org> Message-ID: <1186097439.944587.165650@m37g2000prh.googlegroups.com> On Aug 3, 9:19 am, "Evan Klitzke" <e... at yelp.com> wrote: > On 8/2/07, Stef Mientki <S.Mientki-nos... at mailbox.kun.nl> wrote: > > > hello, > > > I discovered that boolean evaluation in Python is done "fast" > > (as soon as the condition is ok, the rest of the expression is ignored). > > > Is this standard behavior or is there a compiler switch to turn it on/off ? > > This is standard behavior in every language I've ever encountered. If > you are evaluating an and/or with side effects and you need both side > effects to occur, you can trivially write functions implementing this > behavior, e.g. > If each operand is of type bool (or, more generally, isinstance(operand, int) is true), you could trivially use the & and | operators. From tylerca at jeld-wen.com Wed Aug 15 11:30:03 2007 From: tylerca at jeld-wen.com (Azazello) Date: Wed, 15 Aug 2007 08:30:03 -0700 Subject: Python Book Recommendations In-Reply-To: <mailman.2015.1187189280.22759.python-list@python.org> References: <d5506a9f0708141439v6a30d4c8l5092b30d269c1af4@mail.gmail.com> <Pine.LNX.4.44.0708141556370.5396-100000@violet.rahul.net> <1b31ae500708141638w77614014o6f382d0389bc69df@mail.gmail.com> <mailman.2015.1187189280.22759.python-list@python.org> Message-ID: <1187191803.845011.30400@x35g2000prf.googlegroups.com> On Aug 15, 7:47 am, "Shawn Milochik" <Sh... at Milochik.com> wrote: > If I could have only one book, I would buy "Core Python, Second > Edition," by Wesley Chun. > > For the record, I own: > Core Python, Second Edition (great) > wxPython in Action (haven't used yet) > Beginning Python (barely used) > Python in a Nutshell (use as a reference, although interactive python > dir() is more useful) > Dive into Python (great book) > Python Cookbook (great book) > Python Pocket Reference (not very useful) > Python Phrasebook (I love the Phrasebook series, but this isn't a > necessary book) I would like to add: Foundations of Python Network Programming I also use the Python Essential Reference. (although all of the information is probably online it's nice to have a solid paper reference) From gagsl-py2 at yahoo.com.ar Mon Aug 13 01:13:42 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 13 Aug 2007 02:13:42 -0300 Subject: Ligmail bug? References: <20070812005057.GA15805@ob41.org> <f9l3m2$hb0$1@sea.gmane.org> <20070812182439.GA2427@ob41.org> <46BEE9B8.8080904@holdenweb.com> <E9171170-9581-42C5-B68F-6F1442433246@leafe.com> Message-ID: <op.twzfg4hxx6zn5v@a98gizw.cpe.telecentro.com.ar> En Sun, 12 Aug 2007 22:14:08 -0300, Ed Leafe <ed at leafe.com> escribi?: > On Aug 12, 2007, at 7:06 AM, Steve Holden wrote: > >> [Please reply via the list when a response is made via the list. > > The default behavior for this list should be to reply to the list, > as you have pointed out. Yet for some unfathomable reason, the > keepers of the list have set it up to default to reply to the > original sender. This is nothing short of stupid, and I cast my vote > (if I even have one) for changing this default to a more intelligent > one, if for no other reason than to not have to constantly read > comments like this chiding someone for acting in a predictable fashion. Please read this <URL:http://woozle.org/~neale/papers/reply-to-still-harmful.html> -- Gabriel Genellina From exarkun at divmod.com Wed Aug 22 09:32:47 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 22 Aug 2007 09:32:47 -0400 Subject: Fast socket write In-Reply-To: <1187787707.377952.322280@57g2000hsv.googlegroups.com> Message-ID: <20070822133247.8162.1682243074.divmod.quotient.740@ohm> On Wed, 22 Aug 2007 13:01:47 -0000, Greg Copeland <gtcopeland at gmail.com> wrote: >On Aug 21, 9:40 pm, Bikal KC <nepbabucxspamf... at yahoo.ca> wrote: >> Greg Copeland wrote: >> > I'm having a brain cramp right now. I can't see to recall the name of >> >> Is your cramp gone now ? :P > > >I wish. If anyone can remember the name of this module I'd realy >appreciate it. Perhaps you are thinking of the sendfile(2) call available on Linux. "Fast socket write" is quite vague though, so perhaps not. If this isn't what you had in mind, maybe you can try to provide more details about the functionality to narrow the field a bit. Jean-Paul From thomas at jollans.com Fri Aug 17 07:17:37 2007 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 17 Aug 2007 13:17:37 +0200 Subject: clarification In-Reply-To: <aa405c1f0708162332t7b6dbdd6o2cc0f512dc821d7b@mail.gmail.com> References: <aa405c1f0708162332t7b6dbdd6o2cc0f512dc821d7b@mail.gmail.com> Message-ID: <200708171317.39072.thomas@jollans.com> On Friday 17 August 2007, Beema shafreen wrote: > hi everybody, > i have a file with data separated by tab > mydata: > fhl1 fkh2 > dfp1 chk1 > mal3 alp14 > mal3 moe1 > mal3 spi1 > mal3 bub1 > mal3 bub3 > mal3 mph1 > mal3 mad3 > hob1 nak1 > hob1 wsp1 > hob1 rad3 > cdr2 cdc13 > cdr2 cdc2 > shows these two are separated by tab represented as columns > i have to check the common data between these two coloumn1 an coloumn2 > my code: > data = [] > data1 = [] > result = [] > fh = open('sheet1','r') > for line in fh.readlines(): > splitted = line.strip().split('\t') > data.append(splitted[0]) > data1.append(splitted[1]) > for k in data: > if k in data1: > result.append(k) > print result > fh.close() > > can you tell me problem with my script and what should is do for this No, I have not tested it. You tell us the problem, and we might understand the situation better than you. -- Regards, Thomas Jollans GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu Hacker key <http://hackerkey.com/>: v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6 From kyosohma at gmail.com Wed Aug 15 14:02:48 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 15 Aug 2007 11:02:48 -0700 Subject: Hijack! Different book: (was: Opinions about this new Python book? In-Reply-To: <13c6fb3pntv6n13@corp.supernews.com> References: <mailman.1957.1187093157.22759.python-list@python.org> <1187096231.194685.86030@m37g2000prh.googlegroups.com> <20070814154913.D8C3C1E400A@bag.python.org> <8a6b8e350708141020q495b22der4c362ee3df618d82@mail.gmail.com> <mailman.1979.1187113641.22759.python-list@python.org> <1187117012.088495.247890@q4g2000prc.googlegroups.com> <1187191950.037749.8050@z24g2000prh.googlegroups.com> <13c6fb3pntv6n13@corp.supernews.com> Message-ID: <1187200968.181602.310320@g12g2000prg.googlegroups.com> On Aug 15, 12:52 pm, Dennis Lee Bieber <wlfr... at ix.netcom.com> wrote: > On Wed, 15 Aug 2007 08:32:30 -0700, kyoso... at gmail.com declaimed the > following in comp.lang.python: > > > More on the subject...the writer is very conversational in tone and it > > makes for a light read in the first 1 1/2 chapters that I've > > completed. I've noticed a couple of sentence errors, but nothing in > > the code. > > Hopefully it isn't quite as annoying as some of what I've found in > the Turbogears book that recently arrived from Amazon. (Rapid Web > Applications with TurboGears) > > I've so far found a couple of pages where editing rewrites of > paragraphs left redundancies. Example -- section 4.3: > > second paragraph > > """ > ... We set up some variables, and then create a new /Bookmark/ object > with the exact same syntax we used earlier in the chapter when we > created our first bookmark through /tg-admin shell/. > """ > > sentence/sample code/next paragraph > > """ > This method sets up a few variables, and then creates a new /Bookmark/ > object using the exact same syntax we used earlier in the chapter when > we created out first bookmark through /tg-admin shell/. ... > """ > > That's the most blatant, so far, but I've found a few other examples > where a paragraph below a code sample basically restates the paragraph > above it; and the paragraph above seems confusing because it reads as if > it is commenting on prior material, not following material. > > It's as if the book had been first written using, say, "describe, show > code", then edited by someone favoring "show code, explain" style... And > the two versions were then merged by a third person... Hmmm, there are > three authors... > > -- > 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 have this book, but I haven't read it. However, I think the user reviews on Amazon complained quite a bit about the TurboGears book's writing and how it was pretty lousy. Even the code was broken. I look forward to seeing just how truly awful it is. As for this book, "Python Power!", I haven't noticed anything like what you describe. An example issue I've noticed is stuff like this sentence: "There are a few catches and caveats work mentioning, however" Obviously, "work" should be "worth". There are instances like that where a real editor should have caught it, but a Word Processor wouldn't. Mike From llasram at gmail.com Wed Aug 15 15:58:03 2007 From: llasram at gmail.com (Marshall T. Vandegrift) Date: Wed, 15 Aug 2007 15:58:03 -0400 Subject: Coroutines and argument tupling Message-ID: <87zm0so9is.fsf@seneca.iss.local> Hi, I'm trying to write a decorator which allows one to produce simple coroutines by just writing a function as a generator expression which re-receives it's arguments as a tuple from each yield. For example: @coroutine def nextn(n=1): values = [] for i in itertools.count(): while n <= 0: (n,) = (yield values) values = [] values.append(i) n = n - 1 print nextn() # => [0] print nextn(3) # => [1, 2, 3] print nextn(n=2) # => [4, 5] print nextn() # => [6] I've got this working, but have two questions. First, is there a better way to generically transform function arguments into a tuple than I'm doing now? That way being with this pretty hideous chunk of code: class ArgPacker(object): def __init__(self, function): args, varargs, varkw, defaults = inspect.getargspec(function) self.args = args or [] self.varargs = (varargs is not None) and 1 or 0 self.varkw = (varkw is not None) and 1 or 0 self.nargs = len(self.args) + self.varargs + self.varkw defaults = defaults or [] defargs = self.args[len(self.args) - len(defaults):] self.defaults = dict([(k, v) for k, v in izip(defargs, defaults)]) def pack(self, *args, **kwargs): args = list(args) result = [None] * self.nargs for i, arg in izip(xrange(len(self.args)), self.args): if args: result[i] = args.pop(0) elif arg in kwargs: result[i] = kwargs[arg] del kwargs[arg] elif arg in self.defaults: result[i] = self.defaults[arg] else: return None if self.varargs: result[len(self.args)] = args elif args: return None if self.varkw: result[-1] = kwargs elif kwargs: return None return tuple(result) I also tried a version using exec, which was much tighter, but used exec. Second, am I trying to hammer a nail with a glass bottle here? The ugliness of the ArgPacker class makes me suspect that I should perhaps just manually create and track a generator when I need a function with generator-like properties. Thanks! -Marshall From kw at codebykevin.com Mon Aug 6 11:27:32 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 06 Aug 2007 11:27:32 -0400 Subject: Tkinter or wxpython? In-Reply-To: <7xps204tin.fsf@ruckus.brouhaha.com> References: <op.tv98rva4wepdt4@ericb.pragmadev> <mailman.1550.1186099225.22759.python-list@python.org> <1186410331.905174.21370@q3g2000prf.googlegroups.com> <7xps204tin.fsf@ruckus.brouhaha.com> Message-ID: <46B73DE4.6040405@codebykevin.com> Paul Rubin wrote: > > Tkinteger (dang, I always end up typing it that way, I won't even > bother fixing the error) is easy to use for simple gui's, and it's > part of the standard python distro which for me is a big advantage (no > extra crap to download). However, the widget set is rather ugly and > doesn't blend in well with anyone's native widgets; the widget > selection itself is rather narrow, and I think kyosohma may be right > that it doesn't scale well to complex gui's. I've looked at the code > for IDLE's gui and it's terrifying. It's entirely possible to make sophisticated GUI's in Tkinter, but you are right, most people don't. Part of the issue is that Tkinter developers haven't kept up with what's going on in Tk and instead use outdated, ugly widget sets like Tix, PMW, and so on. Making use of the available wrappers for current Tk libraries such as BWidgets, Tile, Tablelist, TkTreeCtrl, and so on allows you to make UI's every bit as polished as what comes with wxPython: tree views, multi-column lists, notebook tabs, comboboxes, etc., with platform-specific theming (XP/Vista, Aqua/OS X, and X11). For more references, see: http://tkinter.unpythonic.net/wiki/TileWrapper http://tkinter.unpythonic.net/wiki/TableListWrapper http://tkinter.unpythonic.net/wiki/TableListTileWrapper http://tkinter.unpythonic.net/wiki/PyLocate http://tkinter.unpythonic.net/wiki/PyLocateTile http://tkinter.unpy.net/bwidget/ http://tkinter.unpy.net/wiki/NoteBook http://klappnase.zexxo.net/TkinterTreectrl/index.html > > At this point I think nobody should write desktop gui apps without a > good reason. There is a fairly flexible and easy to program gui > already running on almost every desktop, namely the web browser. > Before you write a gui using some client side toolkit, ask yourself > whether you can instead embed a web server in your application and > write an HTML gui. That approach is not always the answer, but it has > considerable advantages when you can do it that way. Given a choice between a rich desktop client and a web app, I'd choose the desktop client in most cases. It's just much more pleasant to work with . -- Kevin Walzer Code by Kevin http://www.codebykevin.com From steve at holdenweb.com Thu Aug 2 00:54:29 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 02 Aug 2007 00:54:29 -0400 Subject: beginner in python In-Reply-To: <aa405c1f0708012127j471c9b2dl35b74cda9f595d09@mail.gmail.com> References: <aa405c1f0708012127j471c9b2dl35b74cda9f595d09@mail.gmail.com> Message-ID: <f8ro29$gl2$1@sea.gmane.org> Beema shafreen wrote: > hi everybody, > I am beginner in python > I have to calculate the euclidean distance between the atoms from a pdb > file > i have written the the code and its shows me some error , > the code: > import re > import string > import math > ab =[] > x_value = [] > y_value = [] > z_value = [] > fh = open("1K5N.pdb",'r') > for atom in fh.readlines(): > a = atom.strip() > pattern= re.compile('^ATOM.*') > atom_file= pattern.search(a) > if atom_file: > atom_data = atom_file.group() > x_coordinate = atom_data[31:38] > y_coordinate = atom_data[39:46] > z_coordinate = atom_data[47:54] > x_value.append(x_coordinate) > y_value.append(y_coordinate) > z_value.append(z_coordinate) > for x in range(len(x_value)): > x_co = float(x_value[x])-float(x_value[x+1]) > y_co = float(y_value[x])-float(y_value[x+1]) > z_co = float(z_value[x])-float(z_value[x+1]) > data = math.sqrt(x_co)*(x_co)+(y_co)*(y_co)+(z_co)*(z_co) > print data > ~ > and the error ,message > File "pdb_fetching.py", line 22, in ? > x_co = float(x_value[x])-float(x_value[x+1]) > IndexError: list index out of range > > > can you suggest me the mistake i have made > suppose you have an x_value list of length 6. Valid indexes go from 0 to 5. Then x is going to start at 0 and go up to 5. The last time around the loop the expression "x_value[x+1]" is going to try and use 6 as an index, thus trying to address past the end of the list. Since the data values are the RMS differences between successive points, there are only five differences for a six-element list. Try using for x in range(len(x_value)-1): instead. By the way, you presented your question very well - all necessary information was there, and you didn't put in any mistaken guesses about what might be going wrong. Well done, and welcome to Python! You will find you can learn it very quickly. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From steve at holdenweb.com Fri Aug 31 15:24:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 31 Aug 2007 15:24:52 -0400 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188585630.539835.242460@i38g2000prf.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> <mailman.181.1188527203.28954.python-list@python.org> <1188537516.622167.115080@z24g2000prh.googlegroups.com> <mailman.217.1188577500.28954.python-list@python.org> <1188585630.539835.242460@i38g2000prf.googlegroups.com> Message-ID: <fb9pu6$55a$1@sea.gmane.org> Russ wrote: > Steve Holden wrote: > >> Frankly I am getting a little tired of they way you are unable to even >> recognize that your readers may well have a sensible appreciation of the >> difficulties about which you write. As has been pointed out already, >> many readers here are extremely experienced programmers. > >> You said in an earlier post "that's not an insult", but that isn't >> really up to you to decide. If it gives offense then it probably is, >> whether it was intended to do so or not. You don't seem to appreciate >> the insulting nature of your tone, and calling people bozos is not >> likely to endear you to most c.l.py readers since it comes off as arrogant. > > You quoted what I wrote in reply to a personal attack against me, but > you conveniently > neglected to quote the original insult that I was replying to. OK, > I'll concede that I shouldn't > have replied to a personal insult with another insult, but why am I > the only one at fault here > rather than the guy who started it? > You aren't, and if I wasn't being even-handed I apologize. > Frankly, Mr. Holden, I'm getting a bit tired of the clannish behavior > here, where > "outsiders" like me are held to a higher standard than your "insider" > friends. I don't know > who you are, nor do I care what you and your little group think about > me. > Well that's a healthy attitude, but I am concerned that the Python community should be as welcoming as possible, so I don't like the fact that you feel you are being treated differently from anyone else. > As for DbC or what I call "self-testing code," I have come to the > (tentative) realization that > it is easy to implement in current Python -- without resorting to the > "decorators" hack. > OK, maybe this should have been obvious to me from the > start, but here goes: > > All you really need to test the pre-conditions of a function > is a call at the top of the function to another function that checks > the inputs. To test the > post-conditions, you just need a call at the bottom of the function, > just before the return, > that checks the return values. Those functions can also check the > invariants. Then you > define a global variable to switch all the self-test functions on or > off at once. > It does constrain functions to return only from the bottom of their code, though, which not all Python functions currently do. Though there's nothing to stop you putting the calls before every return. > An advantage of this approach is that all the self tests can be put at > the bottom of the file > (or perhaps in another file) to reduce "clutter" in the primary code. > > I'd still prefer PEP 316, but this seems like a reasonable > alternative. > > One suggestion I have for PEP 316 is to provide a way to place the > self-test > checks in a separate file to reduce clutter. > That would be a sensible suggestion. It would also be possible to guard the lengthier tests with "if debug" to allow them to be omitted (presumably along with their imports with a little further effort in code organization) in (optimized) production mode where timings were critical. This could allow the benefits of DbC and unit testing at the same time. Putting the verification code into external functions does assume that global variables aren't used in the pre- and post-conditions, but I presume that's a part of the regime anyway. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From mail at microcorp.co.za Wed Aug 8 04:01:12 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 8 Aug 2007 10:01:12 +0200 Subject: Issues of state (was: Tkinter or wxpython?) References: <op.tv98rva4wepdt4@ericb.pragmadev><mailman.1680.1186416061.22759.python-list@python.org><7x3aywr4tc.fsf@ruckus.brouhaha.com><mailman.1684.1186422197.22759.python-list@python.org><gg9mo4-p2m.ln1@lairds.us> <7x8x8mpn37.fsf@ruckus.brouhaha.com> Message-ID: <014101c7d992$b1a23a00$03000080@hendrik> "Paul Rubin" <http:/...nvalid> wrote: > claird at lairds.us (Cameron Laird) writes: > > >application in the web app model (I haven't even touched on the whole > > >stateless HTTP being mapped to a stateful environment issue, or the > > >need to manage the local web server) actually buys you anything. I > > . > > Go ahead: touch on statefulness. I've been pondering the topic > > lately, and wonder what's new on the subject. I find it plenty > > difficult to cast this as anything but a big liability for the > > Web app team. > > I'm not sure what you're getting at in this context. You can write a > desktop app where the window system communicates with a gui toolkit > through a socket (at least that's how X windows works), or you can > write a web app where a browser communicates with an http listener > through a socket. What's the difference, as far as application state > is concerned? > > I haven't used wxpython but for tkinter you'd typically have a gui > event loop in its own thread, communicating with the application > through queues. Similarly you can use BaseHTTPServer to collect > browser hits and get the data out of them with the cgi module > functions before passing them to the app. If you want to handle > multiple concurrent users you get into the usual issues of web > servers, but if you're just doing a single user web implementation as > an alternative to a desktop gui, some rudimentary locking is probably > enough to stop accidental simultaneous connections. > > If the application is simple enough, you can just write it as a cgi > and keep the state in disk files. Something that is often overlooked is keeping some state in the buttons. It involves changing the text, colour and the command binding, and possibly setting up a callback using .after for time outs, if necessary. You can do quite complicated sequences like this, if you have a mind to. Its a bit of a PITA - but then all state machines are, no matter how you implement them. Their chief advantage is that they force you to think of all the possibilities. - Hendrik -- Enrol now in Heavy Henry's Wholesome Hackadamy, for a course in single button GUI design. The sacred crocodiles are for the moment leashed. From newsreturns at biszumknie.de Thu Aug 23 11:06:40 2007 From: newsreturns at biszumknie.de (Andreas Lobinger) Date: Thu, 23 Aug 2007 17:06:40 +0200 Subject: expat error, help to debug? Message-ID: <fak7q4$ahn$1@daniel-new.mch.sbs.de> Aloha, i'm trying to write an xml filter, that extracts some info about an .xml document (with external entities), esp. start elements and external entities. The document is a DOCBOOK xml and afacs well formed and passes our docbook toolchain (dblatex etc.). My parser is (very simple): [115] scylla(scylla)> more pbxml.py class xmlhandle: def __init__(self): self.parser_stack = []; self.parser = None; def se(self,name,attr): print "s", self.parser.CurrentLineNumber, name, attr def ex(self,context,baseid,n1,n2): print "x",context,n1,n2 def fromxml(fname): import xml.parsers.expat p = xml.parsers.expat.ParserCreate() xl = xmlhandle() p.StartElementHandler = xl.se p.ExternalEntityRefHandler = xl.ex xl.parser = p p.ParseFile(file(fname)) return if __name__ == "__main__": import sys fromxml(sys.argv[1]) my document (in 2 parts): [116] scylla(scylla)> more s3.xml <?xml version="1.0"?> <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" "/usr/share/xml/docbook/xml/4.2/docbookx.dtd" [ <!ENTITY bookinfo SYSTEM "bookinfo.xml"> ]> <book> &bookinfo; <chapter id="technicalDescription"><title>technical description This chapter includes specification of the main simulation loop. [118] scylla(scylla)> more bookinfo.xml BookTitle A B The run produces: [120] scylla(scylla)> python pbxml.py s3.xml s 7 book {} x bookinfo bookinfo.xml None s 9 chapter {u'id': u'technicalDescription'} s 9 title {} s 10 para {} Traceback (most recent call last): File "pbxml.py", line 25, in ? fromxml(sys.argv[1]) File "pbxml.py", line 20, in fromxml p.ParseFile(file(fname)) TypeError: an integer is required Anyone any idea where the error is produced? Anyone any idea how to debug(? if it's really a bug or missunderstanding of expate) this? Hoping for an answer and wishing a happy day, LOBI From llasram at gmail.com Thu Aug 30 10:28:33 2007 From: llasram at gmail.com (Marshall T. Vandegrift) Date: Thu, 30 Aug 2007 10:28:33 -0400 Subject: strings (dollar.cents) into floats References: <12B58F2B-2F4F-4F6A-9F75-7444427B8CA8@email.it> Message-ID: <87ejhlp04u.fsf@seneca.iss.local> luca bertini writes: > i have strings which look like money values (ie 34.45) > is there a way to convert them into float variables? > everytime i try I get this error: "numb = float(my_line) ValueError: > empty string for float()" > " You actually have problems here -- the immediate, and the one which will get you later :-). First, that error message indicates that you passed an empty string to `float()`: >>> float("") Traceback (most recent call last): File "", line 1, in ? ValueError: empty string for float() Second, if you the values your script is handling are actually monetary values, you really don't want to represent them with `float`s anyway: >>> float("34.45") 34.450000000000003 Binary floating point values are necessarily inexact. I'm not 100% sure what the best-practices are for representing monetary values in Python, but the `decimal` module is probably a good start. HTH, -Marshall From arkanes at gmail.com Mon Aug 6 12:00:47 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 6 Aug 2007 11:00:47 -0500 Subject: Tkinter or wxpython? In-Reply-To: <7xlkcopu4r.fsf@ruckus.brouhaha.com> References: <1186410331.905174.21370@q3g2000prf.googlegroups.com> <7xps204tin.fsf@ruckus.brouhaha.com> <7xlkcopu4r.fsf@ruckus.brouhaha.com> Message-ID: <4866bea60708060900u15c2223erd8858064095a858e@mail.gmail.com> On 06 Aug 2007 08:20:20 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > "Chris Mellon" writes: > > No native look and feel - constrained by the browser. > > Might or might not matter for the application, especially considering > that tkinter is part of the discussion. > The point is that you have no option with the browser - even Tkinter has platform theming support now. > > No control over browser UI idioms. I had to write this post twice > > because the text control lost focus and I hit backspace, going back in > > the history and losing my work. > > Sounds weird, I'm used to having stuff in text boxes stay in the > browser, and why did backspace have that effect anyway? > On Windows, backspace is a browser global hotkey that means "go back once in the history". When the text box lost focus, hitting backspace navigated back. Gmail uses ajax instead of a page load when you start typing a reply, and the fragile tricks it uses to try to keep the browser history and the ajax state in sync don't work in this case. It's a specific example of the general problems of the browser as application platform. > > No native integration - no "open file", no "browse the filesystem", no > > rich drag and drop, no copy/paste. > > File i/o and file system browsing are available from javascript if the > user grants permission. Which they won't (I don't even know how, from Firefox), so you can't rely on it working. You can mitigate with your own browser host, or if you write all your own file browsing in HTML and move it into your local browser. Poor solutions all around. > File system browsing for the limited purpose > of file upload is available in regular html. >Copy/paste of ordinary > text is always available. But not of anything else. I've often wanted to drag & drop a file onto the file upload box in gmail, for example. >However, this type of requirement is what I > mean by a "good reason" to write a desktop gui. It applies to some > applications, not all. > How about something as simple as context menus? You can't reliably override the browser context menu from a web page unless, again, you provide your own browser host. This is a good thing, because a browser needs to be wary of arbitrary malicious web pages. They aren't good application hosts. Keyboard shortcuts that happen to conflict with whatever the browser or any of its plugins happen to use, too. Although I notice that Firefox now allows web pages to override that, which is a little sad. > > No or poor dialogs. Poor multiple window support. > > Might or might not matter depending on the application. Most dialogs > can be done with html. Multiple windows are evil most of the time, > and should instead by done with multiple panes or cells in a single > window. > Multiple windows are the common case on the mac. They're not rare on other platforms as well. The fact that your windows are constrained to the browser and can't be torn off is a large limitation. No toolbars, no palettes, no modal dialogs (except on IE, or if you constrain them to the browser). Lots of unnecessary chrome on your extra windows, too (see below). > > More platforms to develop on and test with. > > Compared to a desktop app? I don't think so. > Did you ever try counting? X browsers * Y browser versions * Z platforms. There are javascript and CSS bugs and differences between all of these. From my own professional experience, it's not any easier to account for browser differences than it is for platform differences. It's getting better as more people jump on the web bandwagon and CSS and JS abstraction libraries show up, but it's not even good as the available platform abstraction libraries like wxWidgets or Qt. > > Limited to CSS box model for layout. > > Might or might not matter depending on the application. If you're > doing a consumer app that has to look slick, you have no choice but to > use something like wxwidgets (tkinter won't cut it either). If you're > doing a special purpose office or industrial app, slickness isn't > important. > I'm not talking about chrome and slickness. I'm talking about basic usability concerns like "will this work with a higher font size" and "will it reflow in a sensible way if I change the window size". The CSS box model works okay for text, it's not so good for widgets. More than a few web apps end up writing their own layout engines in dynamic javascript. This is sad. While I'm talking about chrome, add "wasted screenspace due to browser chrome" to a limitation of web apps, again unless you write your own browser host. This is another example of a feature that makes a good browser (don't let arbitrary web pages mess with my web browser functionality) clashing with the desires of a good application (don't waste screen space with irrelevant functionality). > > The web is a terrible application platform. There is not a single web > > application in existence which has even half the UI functionality of a > > rich client application. > > Some of us consider simple interfaces with consistent, familiar > (i.e. web) elements to be a good thing. Fancy client interfaces are > ok if you feel you need to make a style statement, but are often > unnecessary if you just want to get something done. > Man, you should be in PR with the way you spin things. You can't implement anything except the most trivial of applications using only the simple, familiar web elements like HTML forms. Anything more complicated than that needs to be done with DHTML and probably AJAX, and those UI elements don't look anything like the familiar ones. You go in one breath from saying that you can implement dialogs in HTML to saying that the rich client is the *less* familiar of the interfaces? > > There are some (even many) applications for which the benefit of > > global access and easy deployment makes up for the lack in > > functionality, but statements like "At this point I think nobody > > should write desktop gui apps without a good reason" are simply > > ludicrously misguided. > > Well, I don't say that good reasons don't exist, I just see a lot of > desktop apps that could be done just as well as web apps, i.e. for > those, the good reason didn't exist. > -- If you'd said "if you're making something really simple that has limited rich UI or data entry needs, consider a web application instead" I wouldn't have posted. A web application is something you make because the deployment and access benefits outweigh the UI and integration limitations, not as your default "go to" whenever you create an application. I'd like an example you have of a desktop application that could have just as easily been a web application. Bonus points if it's not a CRUD screen, and double bonus if you don't just handwave away things like file browsing. Although there are benefits even for the crud screen - I've written screens and applications for data entry professionals and they almost always prefer the speed optimizations you can make in a client application. From josh at tcbug.org Tue Aug 7 08:38:50 2007 From: josh at tcbug.org (Josh Paetzel) Date: Tue, 7 Aug 2007 07:38:50 -0500 Subject: ensuring GNU readline isn't used Message-ID: <20070807123850.GV83613@tcbug.org> Is there a way to ensure that GNU readline isn't used (even though support may have been compiled in?). I'm experiencing a licensing problem, I'd like to use the "cmd" module, for example, but my code is proprietary and hence, if cmd uses readline, I can't use cmd. Unfortunately, I can't control if the Python interpreter my customers may be using has readline compiled in. So, I'm wondering if there is anyway to tell Python libraries like "cmd" to not use GNU's readline? Alternatively, could we just include pyreadline as readline instead? -- Thanks, Josh Paetzel -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 194 bytes Desc: not available URL: From sjoerd at intercue.nl Wed Aug 8 10:43:25 2007 From: sjoerd at intercue.nl (Sjoerd Op 't Land) Date: Wed, 08 Aug 2007 16:43:25 +0200 Subject: Stop a thread on deletion Message-ID: Hello all, I'm using threading for generating video content. The trouble is how to kill the thread, because there are multiple (simultaneous) owners of a thread. Ideally, a flag would be set when the reference count of the thread becomes zero, causing the run() loop to quit. Example: import threading import time import gc class myThread(threading.Thread): def __init__(self): self.passedOut = threading.Event() threading.Thread.__init__(self) def __del__(self): self.passedOut.set() def run(self): i = 0 while not self.passedOut.isSet(): i += 1 print "Hi %d" % i time.sleep(0.25) a = myThread() a.start() time.sleep(2.5) a = None time.sleep(2.5) Unfortunately, this doesn't work. When I remove the while-loop, __del__ is called, actually. Appearantly there is still some reference to the thread while it is running. I tried gc.get_referrers(self), but it seems to need some parsing. I'm not sure how to implement that and I'm not sure whether it will work always or not. Thanks in advance for any suggestion, Sjoerd Op 't Land From steve at holdenweb.com Mon Aug 13 21:43:27 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 13 Aug 2007 21:43:27 -0400 Subject: wxPython before MainLoop In-Reply-To: <13c1v79hs0dob3@corp.supernews.com> References: <13bl9a75laqcm70@corp.supernews.com> <13bnh5bs4b9h427@corp.supernews.com> <5i3b1jF3n5bdtU1@mid.individual.net> <13c1v79hs0dob3@corp.supernews.com> Message-ID: [david] wrote: > Well yes, I have tried this app with native windows, > and I know how to do it. > > But if all wxPython can offer is a poor imitation > of MFC, I'm better off using MFC aren't I? > > And too all those people who wrote back to insist > that users MUST explicitly build a multi-threaded > framework for wxPython: > > It's supposed to already be a framework :~) > The answer is simple. If you don't see any advantage to using wxPython then don't use it. Personally I believe wxPython is far from a poor imitation of MFC, but if you are already familiar with MFC then go ahead and use it. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From rebel-6-out at planet.nl Wed Aug 22 12:14:30 2007 From: rebel-6-out at planet.nl (marco Starglider) Date: Wed, 22 Aug 2007 18:14:30 +0200 Subject: porting vc++ project to python? Message-ID: <46cc611f$0$25500$ba620dc5@text.nova.planet.nl> hi, i have a very large project in visual studio2005->visual c++ in windowsxp. i'd like to port it, or my next project, over to python. is this possible without rewriting all my code? are there multiple options to do this? my project is so large, that entirely rewriting it is actually no option. regards, m ps i guess, it's an option to transform my current code into one or more python extensions/modules, and then calling them from a python core module? From gherzig at fmed.uba.ar Fri Aug 10 08:57:53 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Fri, 10 Aug 2007 09:57:53 -0300 Subject: Question about properties. In-Reply-To: <1186742730.729034.256800@i13g2000prf.googlegroups.com> References: <1186741289.074717.174370@e16g2000pri.googlegroups.com> <5i2t7dF3kqc46U3@mid.uni-berlin.de> <1186742730.729034.256800@i13g2000prf.googlegroups.com> Message-ID: <46BC60D1.50405@fmed.uba.ar> king kikapu wrote: >On Aug 10, 1:33 pm, Marc 'BlackJack' Rintsch wrote: > > >>On Fri, 10 Aug 2007 03:21:29 -0700, king kikapu wrote: >> >> >>>Hi, >>> >>> >>>i read in a book the following code snippet that is dealing with >>>properties: >>> >>> >>>class ProtectAndHideX(object): >>> def __init__(self, x): >>> assert isinstance(x, int), '"x" must be an integer!"' >>> self.__x = ~x >>> >>> >>> def get_x(self): >>> return ~self.__x >>> >>> >>> x = property(get_x) >>> >>> >>>Can anyone please help me understand what the symbol "~" does here ?? >>> >>> >>This has nothing to do with properties. For integer objects ``~`` is the >>bitwise negation or invertion operator. >> >>Ciao, >> Marc 'BlackJack' Rintsch >> >> > >Xmmm...ok then but what is actually doing there ?? I removed it and >things seems to work the same way... > > > I guess it is the `Hide' part of the Protectand*Hide* class. Gerardo From jgodoy at gmail.com Fri Aug 31 21:18:09 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Fri, 31 Aug 2007 22:18:09 -0300 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> <7xwsvcc9yz.fsf@ruckus.brouhaha.com> <1i3p8lm.19738kn1q0gkouN%aleax@mac.com> <1188587846.687895.69240@q5g2000prf.googlegroups.com> Message-ID: <38rmq4-cq.ln1@strongwill.g2ctech> Russ wrote: > Alex, I think you are missing the point. Yes, I'm sure that web > searches are critical to > Google's mission and commercial success. But the point is that a few > subtle bugs cannot > destroy Google. If your search engines and associated systems have > bugs, you fix them > (or simply tolerate them) and continue on. And if a user does not get > the results he wants, > he isn't likely to die over it -- or even care much. But if this pattern of not getting wanted results is common, then the user will migrate to alternative search engines and this will *kill* the business. Wrong results won't impact ONE search, but many will impact the company business and will be part of the recipe to take it out of business. > Online financial transactions are another matter altogether, of > course. User won't die, but > they will get very irate if they lose money. But I don't think that's > what you are talking about > here. Lets make someone loose his job and have all his money commitments compromised because of this money lost and we might be talking about people taking their lives. Again, this isn't 100% sure to happen, but it *can* happen. As it happens with a peacemaker: the user won't die if his heart skips one beat, but start skipping a series of them and you're incurring in serious problems. Just because the result isn't immediate it doesn't mean it isn't critical. From jjl at pobox.com Sun Aug 5 11:13:01 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 05 Aug 2007 15:13:01 GMT Subject: A question on plugin design References: Message-ID: <87fy2yrp4y.fsf@pobox.com> Grzegorz S?odkowicz writes: [...] > I'd also be grateful for pointers to a well designed Pythonic plugin > architecture but I'd much prefer a small project with a simple API. Google for setuptools and Python eggs. Search for "entry point" on the setuptools page. John From paul.sijben at xs4all.nl Wed Aug 22 08:07:22 2007 From: paul.sijben at xs4all.nl (Paul Sijben) Date: Wed, 22 Aug 2007 14:07:22 +0200 Subject: python 2.5.1 segfault, multithreading & dual core issue? In-Reply-To: <87r6lxx8qk.fsf@mulj.homelinux.net> References: <46caf049$0$239$e4fe514c@news.xs4all.nl> <87r6lxx8qk.fsf@mulj.homelinux.net> Message-ID: <46cc26f9$0$245$e4fe514c@news.xs4all.nl> thanks very much! I am currently compiling python with the patch and will test it over the coming days. Paul Hrvoje Niksic wrote: > Paul Sijben writes: > >> I am running a multi-threaded python application in a dual core >> intel running Ubuntu. > [...] > > Judging from the stack trace, this patch has a good chance of fixing > your problem: > > http://mail.python.org/pipermail/python-dev/2007-August/074232.html From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Aug 15 16:30:50 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 15 Aug 2007 22:30:50 +0200 Subject: Coroutines and argument tupling References: Message-ID: <5ih63mF3pvnt7U1@mid.individual.net> Marshall T. Vandegrift wrote: > I'm trying to write a decorator which allows one to produce simple > coroutines by just writing a function as a generator expression > which re-receives it's arguments as a tuple from each yield. May I ask why? Passing it the same arguments over and over is no use; and there is the send method. > The ugliness of the ArgPacker class makes me suspect that I should > perhaps just manually create and track a generator when I need a > function with generator-like properties. What do you mean? I don't quite understand why you'd have to "track" a generator for getting generator-like properties. Regards, Bj?rn -- BOFH excuse #103: operators on strike due to broken coffee machine From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Aug 2 12:10:30 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 02 Aug 2007 18:10:30 +0200 Subject: Pythonic way for missing dict keys In-Reply-To: <1i27mku.1sc8l3x1dda3crN%aleax@mac.com> References: <1185041243.323915.161230@x40g2000prg.googlegroups.com> <87lkd0eprj.fsf@pobox.com> <46b0ed0b$0$2257$426a74cc@news.free.fr> <46b1b0ba$0$25340$426a74cc@news.free.fr> <1i27mku.1sc8l3x1dda3crN%aleax@mac.com> Message-ID: <46b201f4$0$13464$426a74cc@news.free.fr> Alex Martelli a ?crit : > Bruno Desthuilliers > wrote: > >> Alex Popescu a ?crit : >>> Bruno Desthuilliers wrote in >>> news:46b0ed0b$0$2257$426a74cc at news.free.fr: >> (snip) >>>> if hasattr(obj, '__call__'): >>>> # it's a callable >>>> >>>> but I don't find it so Pythonic to have to check for a __magic__ >>>> method. >>> It looks like Python devs have decided it is Pythonic, because it is >>> already in the PEP. >> I do know, and I disagree with this decision. >> >> FWIW, repr(obj) is mostly syntactic sugar for obj.__repr__(), >> getattr(obj, name) for obj.__getattr__(name), type(obj) for >> obj.__class__ etc... IOW, we do have a lot of builtin functions that >> mostly encapsulate calls to __magic__ methods, and I definitively don't >> understand why this specific one (=> callable(obj)) should disappear. I > > Maybe because it DOESN'T "encapsulate a call" to a magic method, but > rather the mere check for the presence of one? Yes, true. But it doesn't make such a big difference IMHO : it's about decoupling API (the builtin funcs) from implementation (accessing | calling | checking for the presence of a given implementation attribute). >> usually have lot of respect for Guido's talent as a language designer >> (obviously since Python is still MFL), but I have to say I find this >> particular decision just plain stupid. Sorry. > > The mere check of whether an object possesses some important special > method is best accomplished through the abstract-base-classes machinery > (new in Python 3.0: see ). At > this time there is no Callable ABC, but you're welcome to argue for it > on the python-3000 mailing list (please do check the archives and/or > check privately with the PEP owner first to avoid duplication). I'll have a look. Thanks for the pointers. From jeremy+complangpython at jeremysanders.net Fri Aug 10 07:24:45 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Fri, 10 Aug 2007 12:24:45 +0100 Subject: Smoother Lines in Turtle Graphics References: <1186703789.695265.52390@e9g2000prf.googlegroups.com> <5i2tnaF3mgsofU1@mid.uni-berlin.de> <1186744055.367994.61850@g12g2000prg.googlegroups.com> Message-ID: Ant wrote: > Python: Batteries and Turtles included! I didn't know that! It looks like turtle is based on Tk, which doesn't have antialiasing yet (see http://wiki.tcl.tk/10101 ), so it can't really be made nice and smooth (unless you could somehow use tkzinc/tkpath to draw with). I suppose turtle wouldn't be that hard to reimplement it to use Qt/Gtk instead. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Aug 31 05:10:28 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 31 Aug 2007 11:10:28 +0200 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188523589.736146.263510@l22g2000prc.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> Message-ID: <46d7daf4$0$6451$426a74cc@news.free.fr> Russ a ?crit : >> FWIW, the "Eiffel and SPARK Ada folks" also "brilliantly explained" why >> one can not hope to "write reliable programs" without strict static >> declarative type-checking. > > And they are probably right. And they are obviously wrong, by empiric experience. > I don't think you understand what they mean by "reliable > programs." I think you should stop over-estimating yourself, and start realizing that there are quite a lot of experimented programmers here. > The important question is this: why do I waste my time with bozos like > you? The same question is probably crossing the mind of quite a lot of people here - but the 'bozo' might not be who you think. From rhauff at gmail.com Fri Aug 31 14:11:58 2007 From: rhauff at gmail.com (gsxg) Date: Fri, 31 Aug 2007 18:11:58 -0000 Subject: Is there a simple way to exit a while loop on keystroke? In-Reply-To: <1188581623.588967.78050@z24g2000prh.googlegroups.com> References: <1188578827.809840.90100@r29g2000hsg.googlegroups.com> <1188581623.588967.78050@z24g2000prh.googlegroups.com> Message-ID: <1188583918.747640.300850@22g2000hsm.googlegroups.com> Thanks, The curses library doesn't look to helpful to me. However using CTRL- C is fine and is working nicely. BTW, it should be "time.sleep(1)" in the example above, instead of just "sleep(1)" (Just in case any other newbies like me read this) Thanks again From gherron at islandtraining.com Tue Aug 21 12:09:13 2007 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 21 Aug 2007 09:09:13 -0700 Subject: Python is removing my quotes! In-Reply-To: <496954360708210900p6da42670o3a28d6b0dbd4c524@mail.gmail.com> References: <496954360708210900p6da42670o3a28d6b0dbd4c524@mail.gmail.com> Message-ID: <46CB0E29.2010306@islandtraining.com> Robert Dailey wrote: > Hi, > > Note: I'm using Python on Windows > > I have an application that allows a user to submit a password as a > command line parameter. The password of choice may contain any > characters the user wishes, including quotes. If I do the following: > > python password.py "9999"MyPassword > > The resulting output when I print this inside the script is: > > 9999MyPassword > > Notice how the quotations have been stripped. Is it DOS doing this, or > Python? Is there a way I can fix it? > > Thanks. Not Python. It never even sees those quotes. Whatever system you are using for entering the text is stripping them. Is it the command prompt (cmd.exe)? If so then you can escape the quote by preceding it with a backslash. (This is true of the DOS prompt and all the unix shells, and their windows ports, that I know about.) Gary Herron From bdesth.quelquechose at free.quelquepart.fr Thu Aug 30 09:35:06 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 30 Aug 2007 15:35:06 +0200 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188518054.298017.90610@x35g2000prf.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> Message-ID: <46d76595$0$4013$426a74cc@news.free.fr> Russ a ?crit : > Bruno Desthuilliers wrote: > >>Russ a ?crit : >> >>>On Aug 28, 10:58 pm, Michele Simionato >>>wrote: >>> >>> >>> >>>>Why do you think that would ad a strong positive capability? >>>>To me at least it seems a big fat lot of over-engineering, not >>>>needed in 99% of programs. In the remaining 1%, it would still not >>>>be needed since Python provides out of the box very powerful >>>>metaprogramming capabilities so that you can implement >>>>yourself the checks you need, if you really need them. >>> >>> >>>I get the strong impression you don't really understand what >>>programming by contract is. >> >>I get the strong impression you don't really understand how >>condescending you are. > > > When someone writes something as ignorant as that, they need to be > called on it. When someone writes something as arrogant as that, they need to be called on it. Michele obviously knows what DbC is (probably better than you do), and he also knows Python enough to know why you don't need to add anything to Python to have it. > So you can implement everything you need already in Python? Talking about DbC ? > Yes, of > course, "Yes, of course". A couple of decorator functions and you're done. It's pretty trivial, and that's why Michele told you could implement it by yourself. (snip) >>>I have not yet personally used it, >> >>You have no working experience with the concept, but you think it should >>make it into Python's core ??? > > I don't need to use it to understand the concept. That has been > explained > brilliantly by the Eiffel and SPARK Ada folks. FWIW, the "Eiffel and SPARK Ada folks" also "brilliantly explained" why one can not hope to "write reliable programs" without strict static declarative type-checking. One needs to have working experience with a concept to know what it's really worth. Too bad for you, you're too "smart" to understand this. > I am also smart enough Yes, obviously really smart. From DustanGroups at gmail.com Tue Aug 28 07:20:17 2007 From: DustanGroups at gmail.com (Dustan) Date: Tue, 28 Aug 2007 11:20:17 -0000 Subject: an eval()-like exec() In-Reply-To: References: <1188241165.418263.165730@k79g2000hse.googlegroups.com> Message-ID: <1188300017.844037.129590@19g2000hsx.googlegroups.com> On Aug 27, 6:06 pm, "Matt McCredie" wrote: > > A python interactive interpreter works by having the user type in some > > code, compiling and running that code, then printing the results. For > > printing, the results are turned into strings. > > > I would like make an interpreter which does this, without the last > > part: i.e. where the results are returned as objects, instead of as > > strings. I.e. have I would like to see something that behaves like > > this: > > > >>> ip = MyInterpreter() > > # this started a new interpreter > > >>> ip.run("import math") is None > > True > > >>> ip.run("math.pi") is math.pi > > True > > > Neither exec() or eval() is usable for this, as far as I see, because > > eval can't handle arbitrary python code (eval("import math") ), and > > exec() doesn't return the results. > > > Subclassing an code.InteractiveInterpreter or code.InteractiveConsole > > seems like a usable idea, but I couldn't find out what to do to get > > the results before they are turned into strings. > > > Using compile() and then eval() didn't seem usable either. > > > Any ideas? > > Well, my first thought is that exec and eval serve two different > purposes, and you should just have both of them and use the > appropriate one based on the situation. However, I think it is > possible to enable the behavior you want: > > [code] > def myeval(statement, globals_=None, locals_=None): > try: > return eval(statement, globals_, locals_) > except SyntaxError: > if locals_ is None: > import inspect > locals_ = inspect.currentframe().f_back.f_locals > exec statement in globals_, locals_ > [/code] > > It seems to work for me. > > Matt Unless it's something like: raise_(SyntaxError) where raise_ is a function equivalent to the corresponding statement. From f.guerrieri at gmail.com Tue Aug 28 03:11:08 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Tue, 28 Aug 2007 09:11:08 +0200 Subject: How to free memory ( ie garbage collect) at run time with Python 2.5.1(windows) In-Reply-To: References: <1188224306.863247.127890@50g2000hsm.googlegroups.com> <1i3hujk.ulsjt32wqtq0N%aleax@mac.com> Message-ID: <79b79e730708280011m7aa6a136m21ef149b0fbc9041@mail.gmail.com> On 8/27/07, Peter Otten <__peter__ at web.de> wrote: > Peter Otten wrote: > > > Alex Martelli wrote: > > > >> Integer objects that are once generated are kept around in a "free list" > >> against the probability that they might be needed again in the future (a > > > > Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) > > [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> x = 1000 > >>>> y = 1000 > >>>> x is y > > False > > Why don't x and y point to the same object then? > > Peter > Oops, I think I got it now. The actual objects are freed, only the memory is > kept around for reuse with other ints... On my (windows) machine, only integer up to 256 are cached... I made two dictionaries with mapping from i to id(i) and then compared. They were equal up to 256. In short, try your example with 256 and 257 and see what happens :-) francesco From __peter__ at web.de Thu Aug 16 13:42:37 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 16 Aug 2007 19:42:37 +0200 Subject: ploting issues in program References: <1187250500.571837.196940@19g2000hsx.googlegroups.com> Message-ID: Steve Holden wrote: > I might ask just exactly what is being plotted to give those answers. It > sounds like field strength, but I am having difficulty envisaging a > field that is weakest at its center - is this some sort of alternative > universe you are plotting :-) ? I believe the OP is trying to plot a radiation pattern like Figure 4.5 on the following page: http://www.vias.org/wirelessnetw/wndw_06_05_05.html Peter From steve at holdenweb.com Wed Aug 8 18:20:48 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 08 Aug 2007 18:20:48 -0400 Subject: How to reset sys.exec_prefix? In-Reply-To: References: Message-ID: Bryan wrote: > Bryan wrote: >> Somehow on my linux box I scrood things up and I lost my python path info. >> >> If I check sys.exec_prefix or sys.prefix it shows '/usr/local/', where >> it should show '/usr/'. >> >> Is there a config file somewhere that I can change to fix this, or do I >> need to do a rebuild/reinstall? Hope not. >> >> Thanks, >> B > > Actually to clarify a bit here's what I see: > > >>> sys.prefix > '/usr/local' > >>> sys.path > ['', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', > '/usr/local/lib/python2.5/plat-linux2', > '/usr/local/lib/python2.5/lib-tk', > '/usr/local/lib/python2.5/lib-dynload', > '/usr/local/lib/python2.5/site-packages', > '/usr/local/lib/python2.5/site-packages/PIL'] > > I am thinking that the prefix is prepended to all the paths. > > All my stuff lives in 'usr/lib/python2.5', so I was hoping by just > changing my prefix it would set the rest of the paths accordingly. > It looks like you've installed a local copy. By default, I seem to remember, Python installs with a prefix of /usr/local, so if you have /usr/local/bin on your PATH variable you will pick up a local copy in preference to the standard version installed with the OS. Try running /usr/bin/python and see if that original one is still there (which it probably will be). Id so, all you need to do is uninstall the local version and things will magically return to normal. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From nagle at animats.com Thu Aug 16 11:40:15 2007 From: nagle at animats.com (John Nagle) Date: Thu, 16 Aug 2007 15:40:15 GMT Subject: Who told str() to round my int()'s!!! In-Reply-To: References: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> <9qmvi.47364$s5.1537219@phobos.telenet-ops.be> <3ZudnUuJ68lcxl7bnZ2dnUVZ_t_inZ2d@comcast.com> Message-ID: A.T.Hofkamp wrote: > On 2007-08-15, Larry Bates wrote: > >>or the mildy >>amusing "how do I write bytes not characters to a file" questions at least once >>a week on this forum. Actually, that's a reasonable question, and one that Python didn't do quite right. Remember, in the beginning, Python had only ASCII strings, which were equivalent to arrays of bytes. Then came Unicode strings. Then came the restriction of ASCII chars to 0..127. Except that you can still store binary bytes in ASCII strings, subject to some limitations. The next logical step is a complete separation of binary data handling from text string handling, probably using some type in "numarray" for arrays of bytes. John Nagle From bj_666 at gmx.net Wed Aug 1 05:18:03 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Aug 2007 09:18:03 GMT Subject: access the name of my method inside it References: <1185959202.302467.276080@x35g2000prf.googlegroups.com> Message-ID: <5hb1ebF3inuf2U6@mid.uni-berlin.de> On Wed, 01 Aug 2007 09:06:42 +0000, james_027 wrote: > for example I have this method > > def my_method(): > # do something > > # how do I get the name of this method which is my_method here? Why do you need this? There are ways but those are not really good for production code. Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Fri Aug 31 21:45:01 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 31 Aug 2007 21:45:01 -0400 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <38rmq4-cq.ln1@strongwill.g2ctech> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> <7xwsvcc9yz.fsf@ruckus.brouhaha.com> <1i3p8lm.19738kn1q0gkouN%aleax@mac.com> <1188587846.687895.69240@q5g2000prf.googlegroups.com> <38rmq4-cq.ln1@strongwill.g2ctech> Message-ID: Jorge Godoy wrote: > Russ wrote: > >> Alex, I think you are missing the point. Yes, I'm sure that web >> searches are critical to >> Google's mission and commercial success. But the point is that a few >> subtle bugs cannot >> destroy Google. If your search engines and associated systems have >> bugs, you fix them >> (or simply tolerate them) and continue on. And if a user does not get >> the results he wants, >> he isn't likely to die over it -- or even care much. > > But if this pattern of not getting wanted results is common, then the user > will migrate to alternative search engines and this will *kill* the > business. Wrong results won't impact ONE search, but many will impact the > company business and will be part of the recipe to take it out of business. > >> Online financial transactions are another matter altogether, of >> course. User won't die, but >> they will get very irate if they lose money. But I don't think that's >> what you are talking about >> here. > > Lets make someone loose his job and have all his money commitments > compromised because of this money lost and we might be talking about people > taking their lives. > > Again, this isn't 100% sure to happen, but it *can* happen. > > As it happens with a peacemaker: the user won't die if his heart skips one > beat, but start skipping a series of them and you're incurring in serious > problems. > > Just because the result isn't immediate it doesn't mean it isn't critical. > > We probably need to distinguish between "mission-critical", where a program has to work reliably for an organization to meet its goals, and "safety-critical" where people die or get hurt if the program misbehaves. The latter are the ones where you need to employ all possible techniques to avoid all possible failure modes. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From mail at microcorp.co.za Thu Aug 23 03:09:02 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 23 Aug 2007 09:09:02 +0200 Subject: How would I go about making a file open. Not the way you might think. References: Message-ID: <010101c7e555$49577e00$03000080@hendrik> Lamonte Harris wrote: >Basically you can open a file by double clicking, and by default it would open w/ what every program you have it set >to. Most text files would open in notepad. How can I make a txt open so that notepad opens w/ the content in it by >using just python. I asked this question just yesterday - and Tim Golden answered: os.startfile() - Hendrik From phil at riverbankcomputing.co.uk Sun Aug 5 13:38:12 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sun, 5 Aug 2007 18:38:12 +0100 Subject: PyQt v4.3 (Python Bindings for Qt) Released Message-ID: <200708051838.12519.phil@riverbankcomputing.co.uk> Riverbank Computing is pleased to announce the release of PyQt v4.3 available from http://www.riverbankcomputing.co.uk/pyqt/. The highlights of this release include: - Full support for Qt v4.3.0. - Partial functions can be used as slots. - Many Qt classes now support the standard Python pickle protocol for data serialisation. PyQt is a comprehensive set of Qt bindings for the Python programming language and supports the same platforms as Qt (Windows, Linux and MacOS/X). Like Qt, PyQt is available under the GPL and a commercial license. See http://www.riverbankcomputing.com/Docs/PyQt4/html/classes.html for the class documentation. PyQt v4 supports Qt v4 (http://www.trolltech.com/products/qt/index.html). PyQt v3 is still available to support earlier versions of Qt. PyQt v4 is implemented as a set of 11 extension modules containing approximately 400 classes and 6,000 functions and methods. QtCore The non-GUI infrastructure including event loops, threads, i18n, Unicode, signals and slots, user and application settings. QtGui A rich collection of GUI widgets. QtNetwork A set of classes to support TCP and UDP socket programming and higher level protocols (eg. HTTP, SSL). QtOpenGL A set of classes that allows PyOpenGL to render onto Qt widgets. QtScript A set of classes that implements a JavaScript interpreter. QtSql A set of classes that implement SQL data models and interfaces to industry standard databases. Includes an implementation of SQLite. QtSvg A set of classes to render SVG files onto Qt widgets. QtTest A set of classes to automate unit testing of PyQt applications and GUIs. QtXML A set of classes that implement DOM and SAX parsers. QtAssistant A set of classes that enables the Qt Assistant online help browser to be integrated with an application. QAxContainer A set of classes for Windows that allows the integration of ActiveX controls and COM objects. A Windows installer is provided for the GPL version of PyQt which contains everything needed for PyQt development (including Qt, Qwt, QScintilla and the eric IDE). PyQt includes the pyuic4 utility which generates Python code to implement user interfaces created with Qt Designer in the same way that the uic utility generates C++ code. It is also able to load Designer XML files dynamically. From ldo at geek-central.gen.new_zealand Fri Aug 31 23:37:19 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 01 Sep 2007 15:37:19 +1200 Subject: So what exactly is a complex number? References: <451mq4-les.ln1@ozzie.tundraware.com> <46d89ba9$0$30380$9b4e6d93@newsspool4.arcor-online.net> Message-ID: In message <46d89ba9$0$30380$9b4e6d93 at newsspool4.arcor-online.net>, Wildemar Wildenburger wrote: > Tim Daneliuk wrote: >> >> One of the most common uses for Complex Numbers is in what are >> called "vectors". In a vector, you have both an amount and >> a *direction*. For example, I can say, "I threw 23 apples in the air >> at a 45 degree angle". Complex Numbers let us encode both >> the magnitude (23) and the direction (45 degrees) as a "number". >> > 1. Thats the most creative use for complex numbers I've ever seen. Or > put differently: That's not what you would normally use complex numbers > for. But that's how they're used in AC circuit theory, as a common example. From thermostat at gmail.com Wed Aug 29 15:51:41 2007 From: thermostat at gmail.com (Dan) Date: Wed, 29 Aug 2007 19:51:41 -0000 Subject: re compiled object result caching? Message-ID: <1188417101.936530.182480@50g2000hsm.googlegroups.com> I find myself often using regular expressions in the following pattern: foo_re = re.compile(r"foo(bar)") # . . . re_result = foo_re.search(line) if re_result: bar = re_result.group(1) # . . . But, I keep thinking this is awkward, and I would kind of like to have the re object to cache its result; along the lines of: foo_re = re.compile(r"foo(bar)") # . . . if foo_re.search(line): foo_re.last_result().group(1) I realize I could do this with a wrapper object (I'm not sure if I can subclass the re object..), but I was wondering what the community thought of this. Good idea? Bad? Would it be difficult to add to the standard re module? The only real downside I can think of is thread safety. The other practical benefit I can think of is situations like the following: if unlikely_condition and foo_re.search(line): # . . . With the current implementation I think you would either have to do the search even if unlikely_condition is False, or you would have to do an annoying nested if. Is there another way to achieve this that I'm not thinking of? -Dan From pepper at rumbalski.com Tue Aug 21 14:07:11 2007 From: pepper at rumbalski.com (pepper at rumbalski.com) Date: Tue, 21 Aug 2007 11:07:11 -0700 Subject: confused about why i get a type error when i call an object's method Message-ID: <1187719631.092657.158410@d55g2000hsg.googlegroups.com> I'm confused about why i get a type error when i call an object's method. Here's the example code: >>> class Foo: def __init__(self): self.foo = [] def foo(self): print "in foo!" >>> f = Foo() >>> dir(f) ['__doc__', '__init__', '__module__', 'foo'] >>> f.foo() Traceback (most recent call last): File "", line 1, in f.foo() TypeError: 'list' object is not callable >>> From gigs at hi.t-com.hr Wed Aug 29 15:18:01 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Wed, 29 Aug 2007 21:18:01 +0200 Subject: cgi In-Reply-To: <46d5c01b$0$36438$4fafbaef@reader5.news.tin.it> References: <46d5c01b$0$36438$4fafbaef@reader5.news.tin.it> Message-ID: Fabio Z Tessitore wrote: > Il Wed, 29 Aug 2007 19:24:54 +0200, Gigs_ ha scritto: > >> i have simple page and form that ask for name and color and cgi script >> that print that name in another page and background in chosen color >> >> all the time this error pop: >> Error response >> >> Error code 501. >> >> Message: Can only POST to CGI scripts. >> > > I think this should be your problem, > > change GET with POST in the form > > bye it is post in form. From lists at liquidtrust.org Thu Aug 23 17:11:48 2007 From: lists at liquidtrust.org (Charlie) Date: Thu, 23 Aug 2007 15:11:48 -0600 Subject: How would I compile a Python file to a exe In-Reply-To: References: Message-ID: <20070823151148.1ahhvo6ha8gowgow@mail.liquidtrust.org> Quoting Lamonte Harris : > Been a while and I'm wondering how I would go about doing it. > py2exe seems to be a fairly good option for this, at least in the world of Windows. From bjourne at gmail.com Fri Aug 31 10:19:53 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Fri, 31 Aug 2007 16:19:53 +0200 Subject: list index() In-Reply-To: <1188474616.3257.18.camel@localhost.localdomain> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188474616.3257.18.camel@localhost.localdomain> Message-ID: <740c3aec0708310719r5493fa57i21b31b237b7e63a7@mail.gmail.com> On 8/30/07, Carsten Haese wrote: > Is the Pythonic way > > try: > i = somelist.index(thing) > # Do something with i > except IndexError: > # Do something if thing not found That is not the Pythonic way. "# Do something with i" might also raise an IndexError and they you are screwed. The Pythonic way is something like: try: i = somelist.index(thing) except IndexError: print "Oh noes!" else: # Do the thing with i And for many cases this actually is worse/less readable than the alternative would have been if list.index() returned -1. -- mvh Bj?rn From steve at holdenweb.com Sun Aug 12 11:23:26 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 12 Aug 2007 11:23:26 -0400 Subject: Puzzled by "is" In-Reply-To: References: <20070809194105.39BD11E400A@bag.python.org> <87zm1042f0.fsf@benfinney.id.au> <87ir7l5bv4.fsf@benfinney.id.au> Message-ID: Dick Moores wrote: > On 8/12/07, *Ben Finney* > wrote: > > Dick Moores > writes: > > > At 06:13 PM 8/9/2007, Ben Finney wrote: > > >it's entirely left to the language implementation which > > >optimisation trade-offs to make, and the language user (that's you > > >and I) should *not* expect any particular behaviour to hold between > > >different implementations. > > > > I'm not clear on the meaning of "implementations" here. Would 2.5 > > for Windows, Mac, Linux all be different implementations? Would Iron > > Python be another? ActivePython? > > For the purpose of the above statement, you should consider even the > same Python on two different machines to be "different > implementations". As a programmer writing Python code, you should not > expect any "implementation-dependent" behaviour to operate in any > particular way. > > > So would a programmer EVER use "is" in a script? Sure. For example, the canonical test for None uses x is None because there is only ever one instance of type Nonetype, so it's the fastest test. Generally speaking you use "is" to test for identity (do these two expressions reference the same object) rather than equality (do these two expressions evaluate to equivalent objects). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From kyosohma at gmail.com Thu Aug 23 09:14:13 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 23 Aug 2007 06:14:13 -0700 Subject: Question: wxpython and 3d engine example with model load ? In-Reply-To: <1187860306.533382.248430@j4g2000prf.googlegroups.com> References: <1187860306.533382.248430@j4g2000prf.googlegroups.com> Message-ID: <1187874853.965182.133630@e9g2000prf.googlegroups.com> On Aug 23, 4:11 am, OpenPavilion wrote: > Hello, > > did anyone succeed in combining wxpython and a 3d engine (pyogre, > crystalblend, panda3d, soya etc.) ? > > I would like to create an application, which uses wxpython tree, menu > and grid elements and embedds a 3d view of some of the listed objects > in an own detail window, so showing the object as a 3d model. > I know there is PyOpenGL as well, but I need to load complete models > (meshes done with cinema4d or blender) into the 3d view. > > So it would be very nice, if someone could post me a link to an > example, where someone has successfully glued wxpython UI and a 3d > engine view loading meshes into the 3d view. > > Regards > Bernd I recommend that you post this question to the wxPython group. If it's been done, they should know. http://www.wxpython.org/maillist.php Mike From mhearne808 at gmail.com Thu Aug 30 18:19:37 2007 From: mhearne808 at gmail.com (mhearne808[insert-at-sign-here]gmail[insert-dot-here]com) Date: Thu, 30 Aug 2007 15:19:37 -0700 Subject: fcntl problems Message-ID: <1188512377.441241.107900@q4g2000prc.googlegroups.com> I'm having a number of problems with the fcntl module. First off, my system info: Mac OS X Darwin igskcicglthearn.cr.usgs.gov 8.10.1 Darwin Kernel Version 8.10.1: Wed May 23 16:33:00 PDT 2007; root:xnu-792.22.5~1/RELEASE_I386 i386 i386 Python 2.5.1 (built from source) OK, the weirdness: First of all, if I try this: file = open("counter.txt","w+") fcntl.flock(file.fileno(), fcntl.LOCK_NB) I get this: --------------------------------------------------------------------------- Traceback (most recent call last) /Users/mhearne/src/python/ in () : [Errno 9] Bad file descriptor However, if I try this: fcntl.flock(file.fileno(), fcntl.LOCK_EX) I get no errors. Proceeding forward with the locked file, let's say I do the above in Python interactive Process A. Then in python interactive Process B, I repeat the "open" function on the same file with the same permissions. Then, in each process, I write some text to the file using the write() method. After closing the file in both processes, the only text I see in the file is from Process B! According to my Python Cookbook: "Exclusive lock: This denies all _other_ processes both read and write access to the file." I seem to be experiencing the reverse of that description. Is this my lack of understanding, or have I discovered a bug? Thanks, Mike From antroy at gmail.com Tue Aug 21 05:27:17 2007 From: antroy at gmail.com (Ant) Date: Tue, 21 Aug 2007 02:27:17 -0700 Subject: The folder a script is executed in In-Reply-To: <1187687436.476773.276550@22g2000hsm.googlegroups.com> References: <1187687436.476773.276550@22g2000hsm.googlegroups.com> Message-ID: <1187688437.358293.322460@22g2000hsm.googlegroups.com> On Aug 21, 10:10 am, aine_ca... at yahoo.com wrote: ... > myLocation = GetMyLocation() > print myLocation > > >> C:/folder Do you mean the folder containing the script? Or the current working directory? If the former, then look at os.path.split(sys.argv[0])[0] If the latter, try something like: os.path.abspath(os.curdir) -- Ant... http://antroy.blogspot.com/ From ladaan at iptel.org Thu Aug 23 13:25:03 2007 From: ladaan at iptel.org (Ladislav Andel) Date: Thu, 23 Aug 2007 19:25:03 +0200 Subject: comparing two lists In-Reply-To: <1187888594.076531.163410@l22g2000prc.googlegroups.com> References: <1187888594.076531.163410@l22g2000prc.googlegroups.com> Message-ID: <46CDC2EF.9030702@iptel.org> kyosohma at gmail.com wrote: > On Aug 23, 11:27 am, Ladislav Andel wrote: > >> Hi, >> what would be the most efficient way to do following? >> >> I have a list of dictionaries taken from DB e.g. >> dblist = [{'id:1, 'host':'google.com','ip_address':'1.2.3.4'}, >> {'id:3, 'host':'yahoo.com','ip_address':'5.6.7.8'}, >> {'id:9, 'host':'msn.com','ip_address':'11.3.2.3'}] >> >> and list of object instances in memory(it's just for example) >> which are looping within itself and testing particular hosts >> >> memlist = [,] >> memlist[0].id is 1 and memlist[0].host is google.com etc. >> memlist[1].id is 9 and memlist[1].host is msn.com etc. >> >> Now I want to add a new instance to memlist since id=3(in dblist) is not >> in memlist. >> How would you iterate through it and insert a new instance? >> >> The result should be: >> memlist = [,, ] >> memlist[0].id is 1 and memlist[0].host is google.com etc. >> memlist[1].id is 3 and memlist[1].host is yahoo.com etc. >> memlist[2].id is 9 and memlist[2].host is msn.com etc. >> >> Furthermore, I can have the opposite situation. >> This time I need to remove from memlist a host which is not in dblist. >> How would you do this? >> >> The way how it works is that DBlist is loaded every 10 minutes and >> compares with memlist. >> The memlist should be the same as dblist. >> >> Could you help me, please? >> I'm working on my version of this but somebody might be quicker than me. >> In case I have it done I will post it. >> >> Thanks, >> Lada >> >> There is >> >> and wt >> > > On lists that change in memory, I use the following looping structure: > > for i in range(len(in_memory_list)-1,-1,-1) > > well, actually I will need to iterate over 2 sequences which are not the same length and synchronize it against the dblist i have. But I will look at your post. Thanks a lot. Lada > This loops over the list backwards. I found this method here: > http://mail.python.org/pipermail/python-list/1999-September/012451.html > > Hopefully this will fulfill your needs. I've used it to great effect! > > Mike > > From roman.yakovenko at gmail.com Sun Aug 26 02:21:41 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Sun, 26 Aug 2007 09:21:41 +0300 Subject: Any python Module for generating DocBook? In-Reply-To: References: Message-ID: <7465b6170708252321n13757d50l6b996345049e7a27@mail.gmail.com> On 8/25/07, Tommy Nordgren wrote: > Do anyone on this list know of a Python module for generating DocBook > programlisting elements for programming language source code > merked with special comments. > I want to write a programming book, and want to mark significant > lines in the > source code for reference. My DocBook processing software xmlint, > xsltproc, and fop, > don't support numbering lines, when including source files via > References: <1187076816.432607.7960@d55g2000hsg.googlegroups.com> Message-ID: <46C161F7.40900@jessikat.plus.net> ......... > polar(power,theta) > title.....? > how can i show the step on the polar plot plot(-40, -30,-20,-10,0) > I think you need to consider why you want to plot negative values. The decibel scales are actually logarithmic ie all power is actually positive. Zero power corresponds to -infinity. In practice, I think your radiation pattern plot might correspond to gain (or attenuation). Just relabel your plot and change the values to positive. If you do that and the plots look familiar then you have an answer. -- Robin Becker From richardjones at optushome.com.au Sun Aug 26 17:46:45 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Mon, 27 Aug 2007 07:46:45 +1000 Subject: New UI Toolkit References: <1188146822.129605.160560@22g2000hsm.googlegroups.com> Message-ID: <46d1f4c5$0$15276$afc38c87@news.optusnet.com.au> Gerdus van Zyl wrote: > I am halfway to a first release of a new GUI library for python. It > will be cross platform and follows the Swing philosophy of user > experience and interface fidelity above "but it doesn't look like > windows!" (aside: neither does office 2007 or windowsmediaplayer). > > The library is built on top of CairoGraphics (cairographics.org) and > currently has a rather stable backend for Win32 and experimental > backends for GTK,Pyglet,pygame. I am also developing a gui toolkit (for somewhat similar reasons to you, though unrelated to Swing) but it's for pyglet only. If you're interested, you can find it in the pyglet SVN under contrib/wydget. It's under heavy development and is fairly advanced (in terms of widgets, layouts, dialogs etc implemented) already. > Please reply and let your thoughts be known. Is there a need for a new > GUI library for python? Clearly you felt there was :) Richard From wildemar at freakmail.de Wed Aug 15 08:09:53 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Wed, 15 Aug 2007 14:09:53 +0200 Subject: Combinatorial of elements in Python? In-Reply-To: <9e2f512b0708142203m782b0e10s817fb4d061ba0e46@mail.gmail.com> References: <9e2f512b0708142203m782b0e10s817fb4d061ba0e46@mail.gmail.com> Message-ID: <46C2ED11.70904@freakmail.de> Sebastian Bassi wrote: > I have 2 (or more) groups of elements, and I want to get all possible > unique combinations from all of them. Is there a build-in method to do > it? > > ADictionary={"one":["A","B","C","D"],"two":["H","I"]} > > I want to have all possible combinations from "one" and "two", that is: > > AH > BI > CH > DI > AI > BH > CI > DH > > Sounds easy, but is not :) > > Oh but it is: >>> ADictionary={"one":["A","B","C","D"],"two":["H","I"]} >>> result = set() >>> for one in ADictionary["one"]: ... for two in ADictionary["two"]: ... result.add(one + two) ... >>> result set(['CI', 'CH', 'DH', 'DI', 'AI', 'AH', 'BH', 'BI']) /W From kyosohma at gmail.com Sun Aug 12 21:03:18 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 13 Aug 2007 01:03:18 -0000 Subject: C++ Runtime Library error message - Pythonwin? In-Reply-To: <1186872506.132154.61610@x35g2000prf.googlegroups.com> References: <1186872506.132154.61610@x35g2000prf.googlegroups.com> Message-ID: <1186966998.758238.46810@q3g2000prf.googlegroups.com> On Aug 11, 5:48 pm, goldtech wrote: > Hi, > > Doing GIS [Geographic Information Systems] scripts. > > I was running a batch clip script that worked OK for 126 iterations > then I got the following message: > > "Microsoft Visual C++ Runtime Library > > program: C:\python21\pythonwin\pythonwin.exe > > This application has requested the runtime to terminate in an unusual > way. Please contact the applications support team for more > information." > > What does this mean? Using XP. Is there a log on my system that gives > more info? > > Thanks Dunno. You should redirect the stdout/stderr to a log file and stick some informative print statements in your code. Then when it crashes, you might be able to track this down. Mike From kyosohma at gmail.com Thu Aug 23 16:53:37 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 23 Aug 2007 13:53:37 -0700 Subject: How would I go about making a file open. Not the way you might think. In-Reply-To: References: Message-ID: <1187902417.718046.105910@z24g2000prh.googlegroups.com> On Aug 23, 3:45 pm, Larry Bates wrote: > Hendrik van Rooyen wrote: > > Lamonte Harris wrote: > > >> Basically you can open a file by double clicking, and by default it would open > > w/ what every program you have it set >to. Most text files would open in > > notepad. How can I make a txt open so that notepad opens w/ the content in it > > by >using just python. > > > I asked this question just yesterday - and Tim Golden answered: > > > os.startfile() > > > - Hendrik > > Actually os.startfile('filename.txt') will open the file with whatever > application is associated with .txt files on that machine. That could be > different from notepad if the user has chosen to override the defaults. > > os.system('notepad.exe c:\\junk.txt') > > will force notepad.exe to load and it will load the file specified. > > All depends on what you want to do. > > -Larry That's true, but technically you should use the subprocess.Popen module with Shell=True rather than the os.system method. At least, in the newer Python versions, that seems to be the recommendation. Mike From steve at holdenweb.com Wed Aug 22 00:35:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 22 Aug 2007 00:35:17 -0400 Subject: Chaining programs with pipe In-Reply-To: <13cnbi87neru8c3@corp.supernews.com> References: <1187734166.384152.178040@o80g2000hse.googlegroups.com> <13cnbi87neru8c3@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2007-08-21, avishay wrote: > >> I'm trying to chain two programs with a pipe (the output of >> one feeding the input of the other). I managed to capture the >> output and feeding the input of each program independently >> with popen, but how do I tie them together? > > On Unix, you do the same thing you would in C. Create a pipe > using os.pipe(), then run one program with stdout connected to > the "write" end of the pipe and the other program with stdin > connected to the "read" end of the pipe. > > Or you can take a bit of a shortcut by letting the subprocess > module create the pipe for you: > > http://docs.python.org/lib/node536.html > >> Is there a solution that works equally on all platforms? > > The doc page for subprocess doesn't say what platforms support > it. I've had a lot of problems trying to use the subprocess > module on windows. As is typical for Windows, there are all > sorts of special cases that either don't work at all or don't > work the way they should. You pays your money and you takes > your chances. > Grant: I will shortly have to write some training material on using subprocess under Windows, so if you have any pointers to where your accumulated knowledge can be gleaned I would be grateful for the time saving. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From stephane.larouche at polymtl.ca Mon Aug 13 11:36:20 2007 From: stephane.larouche at polymtl.ca (=?utf-8?b?U3TDqXBoYW5l?= Larouche) Date: Mon, 13 Aug 2007 15:36:20 +0000 (UTC) Subject: Mixing Python and C threads References: Message-ID: Aahz pythoncraft.com> writes: > > In article python.org>, > =?utf-8?b?U3TDqXBoYW5l?= Larouche polymtl.ca> wrote: > >Aahz pythoncraft.com> writes: > >> > >> Can you reproduce your problem with stub code that only creates threads? > >> If yes, that indicates that you're messing with a thread structure > >> somewhere. Note that because you're using gcc, it's possible there's a > >> thread bug on Windows with your tool chain. You might want to check for > >> bug reports. > > > >Here's the simplest piece of code I could think of to reproduce the problem: > > Good work. This is about as far as my expertise can take you; if nobody > responds, you might try the new C/API mailing list (capi-sig). If anybody followed this thread, you'll be pleased to know that the mingw gcc 4.2.1 "technology preview" release available from the official mingw website and Python threads interact perfectly well together. You also have to pass the -mthread option to the linker. Sincerely, St?phane From antroy at gmail.com Fri Aug 10 08:38:48 2007 From: antroy at gmail.com (Ant) Date: Fri, 10 Aug 2007 12:38:48 -0000 Subject: py2exe with python 2.5 In-Reply-To: <1186742871.144805.163450@q4g2000prc.googlegroups.com> References: <1186731595.139576.107660@e9g2000prf.googlegroups.com> <1186736574.092633.196100@d30g2000prg.googlegroups.com> <1186742871.144805.163450@q4g2000prc.googlegroups.com> Message-ID: <1186749528.645498.27440@i13g2000prf.googlegroups.com> On Aug 10, 11:47 am, vedrandeko... at v-programs.com wrote: > On 10 kol, 11:02, Ant wrote: ... > yes,Python 2.5 is on the path, but how can I remove panda3d from that > path? Hit Win - Break to bring up the System Properties dialog (you can also get here through the Control Panel). Go to the Advanced tab, and click the "Environment Variables" button. Find the PATH variable in one of the two lists, and edit it. Just remove the Panda3D entry. Note you'll have to restart your console to pick up any changes. -- Ant... http://antroy.blogspot.com/ From kyosohma at gmail.com Fri Aug 31 09:46:25 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 31 Aug 2007 06:46:25 -0700 Subject: How to use "Resource Editor" in wxPython ? In-Reply-To: <1188564589.573864.86980@x40g2000prg.googlegroups.com> References: <1188564589.573864.86980@x40g2000prg.googlegroups.com> Message-ID: <1188567985.942023.83540@o80g2000hse.googlegroups.com> On Aug 31, 7:49 am, codemania wrote: > Disappointing me extremely, with the "generate python" function within > Resource Editor, I only get a segment of python code which load > xrc(xml format) file, rather than real python code in which I could > append my own code. > > Does that mean RE(Resource Editor) is of little use? > > I hope not, maybe the way I use it is wrong? Tell me please. You can use the code generated with your wxPython code; but when using XRCed, you need to do two-stage creation, which the generated code mentions. It even provides a link: http://wiki.wxpython.org/index.cgi/TwoStageCreation I thought this one was good reading too: http://wiki.wxpython.org/index.cgi/UsingXmlResources I like it depending on the complexity of the project. It can seriously reduce GUI code clutter. Mike From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Aug 17 15:25:43 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 17 Aug 2007 21:25:43 +0200 Subject: Can python threads take advantage of use dual core ? References: <1187366443.621295.97020@e9g2000prf.googlegroups.com> Message-ID: <5imb1lF3pdisdU1@mid.individual.net> nikhilketkar wrote: > What are the implications of the Global Interpreter Lock in Python > ? Please have a look at the archives. This topic is brought up anew every few weeks. > Does this mean that Python threads cannot exploit a dual core > processor and the only advantage of using threads is in that > computation and IO-bound operations can continue in parallel ? Not generally, no. Regards, Bj?rn -- BOFH excuse #93: Feature not yet implemented From rrs at researchut.com Mon Aug 13 14:10:27 2007 From: rrs at researchut.com (Ritesh Raj Sarraf) Date: Mon, 13 Aug 2007 23:40:27 +0530 Subject: Module imports during object instantiation References: <46c00f2d$0$298$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Ritesh Raj Sarraf a ?crit : >> >> if lock is None or lock != 1: >> self.DispLock = False >> else: >> self.DispLock = threading.Lock() >> self.lock = True >> >> if os.name == 'posix': >> self.platform = 'posix' >> self.color = get_colors() >> >> elif os.name in ['nt', 'dos']: >> self.platform = 'microsoft' >> >> try: >> import SomeModule >> except ImportError: >> self.Set_Flag = None >> >> if self.Set_Flag is not None: >> self.color = SomeModule.get_colors_windows() >> >> else: >> self.platform = None >> self.color = None >> >> When I create an object the "import" part never gets executed. Is there a >> reason behind it ? > > what does "print os.name" yields ? On Windows: nt On Linux: posix > >> I mean I'd like to keep my class as independent as I want. So that when >> later I need to use it somewhere else, I don't need to know if it depends >> on any modules. > > > > Then pass the module to the initializer. Python's modules are objects... > Yes, that's an option. But is that the only one? To me it looks like an ugly way of doing. Ritesh -- If possible, Please CC me when replying. I'm not subscribed to the list. From steveo at syslang.net Sat Aug 25 18:02:20 2007 From: steveo at syslang.net (Steven W. Orr) Date: Sat, 25 Aug 2007 18:02:20 -0400 (EDT) Subject: Need a better understanding on how MRO works? Message-ID: Given the following code: (I hope it's as simple as possible) :-) #! /usr/bin/python import new class BASE: def __init__( self ): print 'Hello from BASE init' def m1( self ): print 'M1 Base: Self = ', self def m1replace( self ): print 'm1replace:Self = ', self class D1(BASE): def __init__(self): BASE.__init__(self) def __InitDS101Classes(): name = 'C1' nclass = new.classobj(name,(D1,),globals()) globals()[name] = nclass name = 'C2' nclass = new.classobj(name,(D1,),globals()) globals()[name] = nclass globals()[name].m1 = m1replace __InitDS101Classes() s = C1() s.m1() t = C2() t.m1() I get the following output: 1100 > ./foo1.py Hello from BASE init m1replace:Self = <__main__.C1 instance at 0xb7e637cc> Hello from BASE init m1replace:Self = <__main__.C2 instance at 0xb7e6388c> But if I make BASE inherit from object class BASE(object): then I get this: 1100 > ./foo1.py Hello from BASE init m1replace:Self = <__main__.NewClass instance at 0xb7f5070c> Hello from BASE init M1 Base: Self = <__main__.D1 instance at 0xb7f5088c> Can someone please explain why the assignment to C2.m1 would overwrite BASE.m1? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From aleax at mac.com Sat Aug 18 12:26:10 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 18 Aug 2007 09:26:10 -0700 Subject: clarification References: <13cb7frnqs8f6d9@corp.supernews.com> Message-ID: <1i31aop.2ing3h1hcfz0dN%aleax@mac.com> samwyse wrote: ... > Finally, does anyone familar with P3K know how best to do the reduction > without using 'reduce'? Right now, sets don't support the 'add' and > 'multiply' operators, so 'sum' and (the currently ficticious) 'product' > won't work at all; while 'any' and 'all' don't work as one might hope. > Are there an 'intersection' and 'union' built-ins anywhere? For intersection and union of a sequence of sets, I'd use: def union_all(sos): result = set() for s in sos: result.update(s) return result def intersect_all(sos): it = iter(sos) result = set(it.next()) for s in it: result.intersection_update(s) return result The latter will raise an exception if sos is empty -- I don't think the "intersection of no sets at all" has a single natural interpretation (while the "union of no sets at all" appears to be naturally interpreted as an empty set)... if you disagree, just wrap a try/except around the initialization of result, and return whatever in the except clause. Of course, hoisting the unbound method out of the loops can afford the usual small optimization. But my point is that, in Python, these operations (like, say, the concatenation of a sequence of lists, etc) are best performed "in place" via loops calling mutator methods such as update and intersection_update (or a list's extend, etc), rather than "functionally" (building and tossing away many intermediate results). E.g., consider: brain:~ alex$ python -mtimeit -s'sos=[set(range(x,x+4)) for x in range(0, 100, 3)]' 'r=set()' 'for x in sos: r.update(x)' 100000 loops, best of 3: 18.8 usec per loop brain:~ alex$ python -mtimeit -s'sos=[set(range(x,x+4)) for x in range(0, 100, 3)]' 'r=reduce(set.union, sos, set())' 10000 loops, best of 3: 87.2 usec per loop Even in a case as tiny as this one, "reduce" is taking over 4 times longer than the loop with the in-place mutator -- and it only gets worse, as we're talking about O(N squared) vs O(N) performance! Indeed, this is part of what makes reduce an "attractive nuisance"...;-). [[And so is sum, if used OTHERWISE than for the documented purpose, computing "the sum of a sequence of numbers": a loop with r.extend is similarly faster, to concatenate a sequence of lists, when compared to sum(sol, [])...!!!]] Alex From touch_my_underwear at hotmail.com Sat Aug 18 22:34:49 2007 From: touch_my_underwear at hotmail.com (michael maver) Date: Sun, 19 Aug 2007 12:34:49 +1000 Subject: Searching for pixel color Message-ID: Hello, I was just wondering if anyone knew of a way to search the screen for a certain color in Python. I know it is possible to do this in other languages, but I'm not sure how I'd go about doing this in Python. Just to let you know, I'm running windows XP and I don't really need it to be a cross platform solution, but if it was that'd be an extra bonus. Thanks very much for taking the time to read this and, hopefully, respond! _________________________________________________________________ Advertisement: Win Dad the Footy Final with Cadbury Favourites! http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fbs%2Eserving%2Dsys%2Ecom%2FBurstingPipe%2FadServer%2Ebs%3Fcn%3Dtf%26c%3D20%26mc%3Dclick%26pli%3D243221%26pi%3D0%26ord%3D%25%25RANDOM%25%25&_t=765445318&_r=hotmail_email_tagline_Aug07_Cadburys&_m=EXT From jmcmonagle at velseis.com.au Wed Aug 1 23:54:46 2007 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Thu, 02 Aug 2007 13:54:46 +1000 Subject: Error with Tkinter and tkMessageBox In-Reply-To: <46af71b7$0$10619$4fafbaef@reader2.news.tin.it> References: <46af71b7$0$10619$4fafbaef@reader2.news.tin.it> Message-ID: <46B15586.1050703@velseis.com.au> Fabio Z Tessitore wrote: > hi all, > > this Tkinter very simple code work fine: > > ########################## > from Tkinter import * > > win = Tk() > win.mainloop() > ########################## > > but if I try to open a message box, it happens: > > Exception in Tkinter callback > Traceback (most recent call last): > File "lib-tk/Tkinter.py", line 1348, in __call__ > return self.func(*args) > File "/home/fabio/Desktop/prova.py", line 5, in reply > showinfo(title='ciao', message='hello') > File "lib-tk/tkMessageBox.py", line 84, in showinfo > return _show(title, message, INFO, OK, **options) > File "lib-tk/tkMessageBox.py", line 75, in _show > res = Message(**options).show() > File "lib-tk/tkCommonDialog.py", line 52, in show > s = w.tk.call(self.command, *w._options(self.options)) > TclError: bad pad value "2m": must be positive screen distance > > > ############################## > from Tkinter import * > from tkMessageBox import * > > def reply(): > showinfo(title='ciao', message='hello') > > win = Tk() > but = Button(win, text='press me', command=reply) > but.pack() > win.mainloop() > ############################## > > these are versions: > > python: 2.4.4 or 2.5.1 > Tkinter.TclVersion: 8.4 > Tkinter.TkVersion: 8.4 > > can anyone help me? > thanks > What window manager are you using ? From seancron at gmail.com Thu Aug 30 15:45:43 2007 From: seancron at gmail.com (seancron) Date: Thu, 30 Aug 2007 19:45:43 -0000 Subject: Python weather application Message-ID: <1188503143.724438.309580@x40g2000prg.googlegroups.com> Does anybody have any suggestions for getting started on desigining a desktop weather application in Python? I've been looking for access to weather data and while I have found several including the weather.com service I've decided to use the Yahoo! Rss Weather feed since it doesn't have a license like the weather.com service does. However one problem I have with it is that it only accepts zip codes or locations ids. So if a user was to enter the name of the city instead of those two there would be an error. I could make it so they could only enter in the location code or zip code but I would really prefer to have it be automatically corrected. Does anyone have ideas on how to go about this or have an other suggestions? Thanks, Sean From zyzhu2000 at gmail.com Fri Aug 24 09:26:22 2007 From: zyzhu2000 at gmail.com (beginner) Date: Fri, 24 Aug 2007 13:26:22 -0000 Subject: List Comprehension Question: One to Many Mapping? In-Reply-To: <1187934290.472868.36770@q3g2000prf.googlegroups.com> References: <1187929443.636690.287450@i13g2000prf.googlegroups.com> <1187934068.998593.201240@x40g2000prg.googlegroups.com> <1187934290.472868.36770@q3g2000prf.googlegroups.com> Message-ID: <1187961982.055403.244000@r23g2000prd.googlegroups.com> On Aug 24, 12:44 am, beginner wrote: > On Aug 24, 12:41 am, Davo wrote: > > > > > > > On Aug 23, 9:24 pm, beginner wrote: > > > > Hi All, > > > > How do I map a list to two lists with list comprehension? > > > > For example, if I have x=[ [1,2], [3,4] ] > > > > What I want is a new list of list that has four sub-lists: > > > > [[1,2], [f(1), f(2)], [3,4], [f(3), f(4)]] > > > > [1,2] is mapped to [1,2] and [f(1), f(2)] and [3,4] is mapped to > > > [3,4], [f(3), f(4)]. > > > > I just can't find any way to do that with list comprension. I ended up > > > using a loop (untested code based on real code): > > > > l=[] > > > for y in x: > > > l.append(y) > > > l.append([f(z) for z in y]) > > > > Thanks, > > > Geoffrey > > > This may be what you want: > > > l = [[y, [f(z) for z in y]] for y in x] > > > But It's a bit dense. How about: > > l=[] > > for y in x: > > Fy = [f(z) for z in y] > > l.extend([y, Fy]) > > > -- David- Hide quoted text - > > > - Show quoted text - > > This is exactly what I was looking for. Thanks.- Hide quoted text - > > - Show quoted text - On second thought, that will generate one additional level. So it is not what I am looking for. From zzbbaadd at aol.com Thu Aug 30 12:41:00 2007 From: zzbbaadd at aol.com (zzbbaadd at aol.com) Date: Thu, 30 Aug 2007 09:41:00 -0700 Subject: list index() In-Reply-To: <87hcmhebwv.fsf@benfinney.id.au> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <87hcmhebwv.fsf@benfinney.id.au> Message-ID: <1188492060.983148.90000@r34g2000hsd.googlegroups.com> On Aug 30, 12:09 am, Ben Finney wrote: > zzbba... at aol.com writes: > > What's with the index() function of lists throwing an exception on not > > found? > > It's letting you know that the item isn't in the list. There's no > sensible return value from an "index" function in that condition. for str: find( sub[, start[, end]]) Return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. -1 is used in other languages as well. From aisaac at american.edu Thu Aug 30 14:37:03 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 30 Aug 2007 18:37:03 GMT Subject: create Powerpoint via com Message-ID: Can someone point me to a simple example or better yet tutorial for creating a Powerpoint using Python. Thanks, Alan Isaac From ladynikon at gmail.com Fri Aug 3 22:08:21 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Fri, 3 Aug 2007 22:08:21 -0400 Subject: Eclipse and Python In-Reply-To: <46B394CC.6080904@gazeta.pl> References: <59f9c5160708030922m2f4f5179nf384135214246d14@mail.gmail.com> <46B394CC.6080904@gazeta.pl> Message-ID: <59f9c5160708031908v700dc2f4sfb83b6912b272433@mail.gmail.com> Thanks to all! Danyelle On 8/3/07, Lukasz wrote: > U?ytkownik Danyelle Gragsone napisa?: > > Does anyone have any suggested websites for learning Eclipse the python way? > > > > thanks, > > Danyelle > > http://www.showmedo.com/videos/series?name=PyDevEclipseList > > > -- > Opole - Miasto Bez Granic. > http://www.opole.pl - tu znajdziesz nowe miejsca, nowe mozliwosci, nowe inspiracje... > > > -- > http://mail.python.org/mailman/listinfo/python-list From nicksavill at googlemail.com Mon Aug 27 12:56:38 2007 From: nicksavill at googlemail.com (nicksavill at googlemail.com) Date: Mon, 27 Aug 2007 09:56:38 -0700 Subject: sorting a list of lists Message-ID: <1188233798.684136.263640@22g2000hsm.googlegroups.com> Hi, i would like to sort a list of lists. The list is first sorted on the second item in the sub-lists (which I can do), then on the third item (which I can't). eg. records = [['dog',1,2], ['chair',2,1], ['cat',1,3], ['horse',3,4], ['table',3,2], ['window',3,5]] I want sorted to [['dog',1,2], ['cat',1,3], ['chair',2,1], ['table', 3,2], ['horse',3,4], ['window',3,5]] To sort on the second item in the sub-lists I do the following pass1 = itemgetter(1) sorted(records, key=pass1) How can I then sort on the third item in the sub-lists whilst keeping the order on the second item? Nick From laurent.pointal at limsi.fr Fri Aug 17 07:43:03 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 17 Aug 2007 13:43:03 +0200 Subject: clarification In-Reply-To: References: Message-ID: Thomas Jollans a ?crit : > On Friday 17 August 2007, Beema shafreen wrote: >> hi everybody, >> i have a file with data separated by tab >> mydata: >> fhl1 fkh2 >> shows these two are separated by tab represented as columns >> i have to check the common data between these two coloumn1 an coloumn2 >> my code: >> data = [] >> data1 = [] >> result = [] >> fh = open('sheet1','r') >> for line in fh.readlines(): >> splitted = line.strip().split('\t') >> data.append(splitted[0]) >> data1.append(splitted[1]) >> for k in data: >> if k in data1: >> result.append(k) >> print result >> fh.close() Use set data type for data and data1 (you fill them with an algo like th one you wrote - just use add() in place of appen()) then use set intersection to get common data. See doc for set data type: http://docs.python.org/lib/types-set.html Would look like (not tested): data = set() data1 = set() fh = open('sheet1','r') for line in fh.readlines(): splitted = line.strip().split('\t') data.add(splitted[0]) data1.add(splitted[1]) result = data.intersection(data1) From horpner at yahoo.com Thu Aug 30 09:31:18 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 30 Aug 2007 13:31:18 GMT Subject: Python doesn't see the directories I create References: <46d6856b$0$17674$426a74cc@news.free.fr> Message-ID: On 2007-08-30, Bruno Desthuilliers wrote: > mr_gadget a ?crit : >> When I create a subfolder, python is not seeing it. Can someone please >> explain this behaviour ? I just started with python, read the tutorial over >> the weekend and am writing my very first script. So I may not be seeing >> something. Both os.path and glob.glob seem not to see a folder I created. >> Other sibling folders seem to work fine. On a whim I tried paths with \\ >> double slashes and that worked. But why should single slashes work for some >> folders and not for others ?? > > s/slash/antislash/g > > It's a very well known gotcha due to MS's choice to use the > antislash as path separator. In most languages - Python > included - the antislash is used for escape sequences > (non-printable characters). Keeping in mind which came first, isn't it at least as accurate to attribute this problem to Python's choice of escape character? There were probably advantages to adopting the same escape character as other well-known languages/codes, but the choice has caused some trouble over the years. To me, Python's collection of special-purpose string literal notations is one of its little warts. Of course, I'm not smart enough to have delivered the ONE TRUE string literal notation either, but I do have a computer and an internet connection, so there you are. -- Neil Cerutti From deets at nospam.web.de Thu Aug 9 09:03:13 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 09 Aug 2007 15:03:13 +0200 Subject: Jython - variables are stored somehow In-Reply-To: <1186662600.413645.25430@22g2000hsm.googlegroups.com> References: <1186662600.413645.25430@22g2000hsm.googlegroups.com> Message-ID: <5i0hkjF3l6rsqU1@mid.uni-berlin.de> nmin at freenet.de schrieb: > Hi, > > I'm using Jython in combination with java. > > I wrote a jython skript, which calls a function from another jython > module called library.py. > > So, executing the function genData() in skript .py runs without > problem but if I execute the same function again, the data from the > first run is stored somehow and is added to the new data. > > So, if you look at the result: > #1 in DatenTypen.py return an empty list each time the program runs. > Ok ... clear so far > #2 in library.py returns an empty list, when the program runs for the > first time ... but when the function is > called again, the list contains an element. Each time you call the > function again, one element is added! > Why?? out.abschnitte should be the same as printed in #1 or not? > > Here is the code: > > skript.py > ====== > from library import * > > def genData(): > > > out=DMS_sendFiles_ein_Abschnitt([["testdata1.test","testdata2.test","testdata3.test"]]) > > return out > > library.py > ======= > from DatenTypen import AusgangsDatenDeichMonitor > from DatenTypen import DMS_Abschnitt > from DatenTypen import DMS_GeoData > from DatenTypen import DMS_GeoDataFile > > def DMS_sendFiles_ein_Abschnitt(filelist): > > out=AusgangsDatenDeichMonitor() > > print "out.abschnitte: "+str(out.abschnitte) #2 > > abschnitt=DMS_Abschnitt() > > for f in filelist: > data=DMS_GeoData() > > for layer in f: > > datalayer=DMS_GeoDataFile() > > datalayer.dateiname=layer > > datalayer.dateiinhalt="TEST" > > data.layerFiles.append(datalayer) > > abschnitt.bildSequenze.append(data) > > out.abschnitte.append(abschnitt) > > return out > > DatenTypen.py > =========== > > class AusgangsDatenDeichMonitor: > > abschnitte=[] > > def __init__(self): > abschnitte=[] > print "Abschnitt in DatenTypen: "+str(abschnitte) #1 > > class DMS_Abschnitt: > > bildSequenze=[] > > def __init__(self): > abschnittsNummer=0 > bildSequenze=[] > > class DMS_GeoData: > > layerFiles=[] > > def __init__(self): > layerFiles=[] > > class DMS_GeoDataFile: > > dateiinhalt="dateiinhalt" > > dateiname="dateiname" > > zipped=False > > def __init__(self): > dateiinhalt="dateiinhalt" > dateiname="dateiname" > zipped=False > > So, I read about deleting Instances with "del" ... but it does not > work at all. > > Any Ideas? I think you should read a python-tutorial. The above code looks as if you believe that class Foo: name = value def __init__(self): name = other_value will create a class Foo, which then has instances with the property "name", and that this is bound to other_value. Python isn't doing that. name in the above example (and e.g. abschnitte in yours) are class-attributes. That means that ALL instances of Foo share that name!!! What you have to do is this: class Foo: def __init__(self, other_value): self.name = other_value please note the self in front of name! Or, within your example: class AusgangsDatenDeichMonitor: def __init__(self): self.abschnitte=[] print "Abschnitt in DatenTypen: "+str(abschnitte) #1 There are a great many tutorials for python + OO out there - go read one (or several). Regards, Diez From uymqlp502 at sneakemail.com Tue Aug 28 21:04:00 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Tue, 28 Aug 2007 18:04:00 -0700 Subject: status of Programming by Contract (PEP 316)? Message-ID: <1188349440.309634.182800@z24g2000prh.googlegroups.com> I just stumbled onto PEP 316: Programming by Contract for Python (http://www.python.org/dev/peps/pep-0316/). This would be a great addition to Python, but I see that it was submitted way back in 2003, and its status is "deferred." I did a quick search on comp.lang.python, but I don't seem to see much on it. Does anyone know what the real status is of getting this into standard Python? Thanks. From steve at holdenweb.com Thu Aug 9 16:38:18 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 09 Aug 2007 16:38:18 -0400 Subject: Puzzled by "is" In-Reply-To: <1186691088.090783.93810@z24g2000prh.googlegroups.com> References: <20070809194105.39BD11E400A@bag.python.org> <1186691088.090783.93810@z24g2000prh.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: [...] > > Steve, > > I thought you'd probably weigh in on this esoteric matter. Very > illuminating, as usual. > Thank you! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From hg at nospam.org Wed Aug 1 21:27:46 2007 From: hg at nospam.org (hg) Date: Wed, 01 Aug 2007 20:27:46 -0500 Subject: Wing IDE for Python v. 3.0 beta1 released References: <46AF8ED7.2070206@wingware.com> <20070801212840.GA25065@spookie1.spookiegate> <1186016981.502313.268700@r34g2000hsd.googlegroups.com> Message-ID: Fuzzyman wrote: > On Aug 2, 1:46 am, "Greg Donald" wrote: >> On 8/1/07, John K Masters wrote: >> >> > If their support for paid customers is anything like their support for >> > prospective customers then I would leave well alone. >> >> I had no problems with their support whatsoever, really good in my >> opinion. They were very responsive and addressed all my questions >> over about a 3 or 4 day email conversation. >> >> -- >> Greg Donaldhttp://destiney.com/ > > I'll third that. I have had excellent and extended support from the > Wing guys. Definitely recommended. > > Fuzzyman > http://www.voidspace.org.uk/python/articles.shtml I sent a bug report 10 minutes ago and already have received an answer with a possible way out ! hg From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Aug 8 06:10:57 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 08 Aug 2007 12:10:57 +0200 Subject: Seek the one billionth line in a file containing 3 billion lines. In-Reply-To: References: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> <7xzm12o7o7.fsf@ruckus.brouhaha.com> Message-ID: <46b996b1$0$12384$426a74cc@news.free.fr> Jay Loden a ?crit : (snip) > If we just want to iterate through the file one line at a time, why not just: > > count = 0 > handle = open('hugelogfile.txt') > for line in handle.xreadlines(): > count = count + 1 > if count == '1000000000': > #do something for count, line in enumerate(handle): if count == '1000000000': #do something NB : files now (well... since 2.3) handle iteration directly http://www.python.org/doc/2.3/whatsnew/node17.html From michele.petrazzo at TOGLIunipex.it Wed Aug 1 03:20:03 2007 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Wed, 01 Aug 2007 09:20:03 +0200 Subject: Strange problems with subprocess Message-ID: Hi all. I have a simple "ping tester" program that, every 1 minute (execute by linux crontab), create, with subprocess, a "ping -c 1 my_addrs". All work, but sometime (about 1/2 times at a day), I receive this error message: File "/exports/srv-wipex/net_test/ping_tester.py", line 88, in pyPing cmd_p = Popen(cmd, stdout=PIPE, stderr=PIPE) File "subprocess.py", line 543, in __init__ errread, errwrite) File "subprocess.py", line 970, in _execute_child data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB What can be that raise this? Python 2.4 in deb etch Thanks, Michele From Graham.Dumpleton at gmail.com Mon Aug 27 18:12:50 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Mon, 27 Aug 2007 22:12:50 -0000 Subject: some problems with mod_python In-Reply-To: <1188245587.129794.258250@z24g2000prh.googlegroups.com> References: <1188245587.129794.258250@z24g2000prh.googlegroups.com> Message-ID: <1188252770.954357.224380@x40g2000prg.googlegroups.com> On Aug 28, 6:13 am, Johan wrote: > Hi > > I have installed and tested this on centos, fedora and freebsd all > give the same problem so I guess I missed some steps. > > I have compiled bot apache (2.2.4) and mod_python (3.3.1) according to > the docs and no problem with this. > But when I have made everything about testing mod_python an browse tohttp://server/testand there expecting to see "Hello world" I instead > get an index of contents in this directory. If I go to http://server/test/mptest.py > it works. No errors in any log either. > > What Have I missed? > > This I added to httpd.conf > > AllowOverride All > AddHandler mod_python .py > PythonHandler mptest > PythonDebug On > > > this is my mptest.py: > from mod_python import apache > > def handler(req): > req.content_type = 'text/plain' > req.write("Hello World!") > return apache.OK > > /johan You need to look at the Apache documentation for the difference between AddHandler and SetHandler directives. If you don't want to read the Apache documentation and learn more about it, at least read: http://www.dscpl.com.au/wiki/ModPython/Articles/SetHandlerVersusAddHandler Graham From a.harrowell at gmail.com Fri Aug 17 10:43:11 2007 From: a.harrowell at gmail.com (TYR) Date: Fri, 17 Aug 2007 14:43:11 -0000 Subject: Naming dictionaries recursively In-Reply-To: <5ilkebF3oltfoU2@mid.uni-berlin.de> References: <1187354296.177606.273300@22g2000hsm.googlegroups.com> <5ilkebF3oltfoU2@mid.uni-berlin.de> Message-ID: <1187361791.979162.46330@22g2000hsm.googlegroups.com> > So the tougher problem seems to be parsing those lines. That is not a > valid Python dictionary unless the names `Bob`, `Humboldt`, `red`, and > `predatory` are not already defined. So you can't just ``eval`` it. In what way? {'key': val}, right? Anyway, I can always change the format they go into the file in. From zyzhu2000 at gmail.com Sat Aug 18 20:40:41 2007 From: zyzhu2000 at gmail.com (beginner) Date: Sun, 19 Aug 2007 00:40:41 -0000 Subject: How to call module functions inside class instance functions? Message-ID: <1187484041.838615.259980@e9g2000prf.googlegroups.com> Hi Everyone, I have encountered a small problems. How to call module functions inside class instance functions? For example, calling func1 in func2 resulted in a compiling error. "my module here" def func1(): print "hello" class MyClass: def func2(): #how can I call func1 here. func1() #results in an error Thanks, Geoffrey From vedrandekovic at v-programs.com Fri Aug 10 03:39:55 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Fri, 10 Aug 2007 00:39:55 -0700 Subject: py2exe with python 2.5 Message-ID: <1186731595.139576.107660@e9g2000prf.googlegroups.com> Hello, Now,I was install python 2.5 and remove python 2.4 completely.After I write: $ python mysetup.py py2exe ....... import py2exe_ util ImportError: Module use of conflicts with this version of Python ...ok, I know what is a problem, I haven't remove python completely, in my computer is one more folder Panda3D-1.4.0 but when I remove it and all dll files include python24.dll, I cannot run python or make that setup. (That panda3d contain python) Regards, Vedran From kar1107 at gmail.com Tue Aug 21 20:40:35 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Tue, 21 Aug 2007 17:40:35 -0700 Subject: Chaining programs with pipe In-Reply-To: <1187734166.384152.178040@o80g2000hse.googlegroups.com> References: <1187734166.384152.178040@o80g2000hse.googlegroups.com> Message-ID: <1187743235.124030.321200@l22g2000prc.googlegroups.com> On Aug 21, 3:09 pm, avishay wrote: > Hello > I'm trying to chain two programs with a pipe (the output of one > feeding the input of the other). I managed to capture the output and > feeding the input of each program independently with popen, but how do > I tie them together? Is there a solution that works equally on all > platforms? Not sure on non-unix platforms, but in unix like platforms it's best to reuse shell's power. >>> import commands >>> commands.getoutput('ls | wc') ' 4 4 24' >>> Thanks, Karthik > > Thanks, > Avishay From rrs at researchut.com Wed Aug 15 15:43:18 2007 From: rrs at researchut.com (Ritesh Raj Sarraf) Date: Wed, 15 Aug 2007 19:43:18 -0000 Subject: Module imports during object instantiation In-Reply-To: <1187205375.871837.254400@r34g2000hsd.googlegroups.com> References: <4c3vo4-u7k.ln1@learner.hq.netapp.com> <46c16ec9$0$405$426a34cc@news.free.fr> <1187205375.871837.254400@r34g2000hsd.googlegroups.com> Message-ID: <1187206998.252482.300780@a39g2000hsc.googlegroups.com> On Aug 16, 12:16 am, Ritesh Raj Sarraf wrote: > On Aug 15, 11:42 pm, Neil Cerutti wrote: > > > On 2007-08-15, Ritesh Raj Sarraf wrote: > > > Or am I terribly missing something that you are trying to tell ? > > > I didn't see log = Log() in your example. Sorry for the > > excursion. > > > Are you sure os.name is 'posix' on your system? > > Here again for you: > > In [6]: cat rick.py > IPython system call: cat rick.py > import os, sys > > class Log: > def __init__(self, verbose, lock = None): > self.VERBOSE = bool(verbose) > self.lock = bool(lock) > > if self.lock: > self.dispLock = threading.Lock() > else: > self.dispLock = None > > if os.name == 'posix': > try: > import foobar > except ImportError, e: > print >> sys.stderr, e > > self.platform = 'posix' > self.color = get_colors() > > elif os.name in ['nt', 'dos']: > self.platform = 'microsoft' > try: > import SomeModule > except ImportError, e: > # comment out next line before going to prod... > print >> sys.stderr, e > > self.color = None > else: > self.color = SomeModule.get_colors_windows() > else: > self.platform = None > self.color = None > > In [7]: from rick import Log > > In [8]: log = Log(verbose = True) > No module named foobar > --------------------------------------------------------------------------- > exceptions.NameError Traceback (most > recent call last) > > /tmp/ > > /tmp/rick.py in __init__(self, verbose, lock) > 18 > 19 self.platform = 'posix' > ---> 20 self.color = get_colors() > 21 > 22 elif os.name in ['nt', 'dos']: > > NameError: global name 'get_colors' is not defined > Oops!!! Looks like I completely missed this. It _did_ print the error message. Apologies to all for not keeping a close eye on the error message. From daniels at dsl-only.net Thu Aug 30 00:29:28 2007 From: daniels at dsl-only.net (Scott David Daniels) Date: Wed, 29 Aug 2007 21:29:28 -0700 Subject: Python molecular viewer In-Reply-To: References: Message-ID: <13dchs8a39et77f@corp.supernews.com> Andy Cheesman wrote: > Dear People, > > I was wondering if people could recommend a simple molecular viewing > package written in python. I'm working in Theoretical chemistry and I'm > not after an all-singing dancing molecular rendering package(pymol does > that rather well) but a program which reads XYZ files and displays > simple structures which can be rotated in 3D You could use VPython if you know how to convert XYZ files to ball and stick locations to cartesian coordinates. From gur.tom at gmail.com Thu Aug 30 03:50:30 2007 From: gur.tom at gmail.com (Tom Gur) Date: Thu, 30 Aug 2007 07:50:30 -0000 Subject: Embedding the python interpreter In-Reply-To: <13d879psf7e080@corp.supernews.com> References: <1188305107.028128.136960@d55g2000hsg.googlegroups.com> <13d879psf7e080@corp.supernews.com> Message-ID: <1188460230.341009.213860@50g2000hsm.googlegroups.com> On Aug 28, 4:03 pm, Grant Edwards wrote: > On 2007-08-28, Tom Gur wrote: > > > Hey, > > > Do you know an easy way to embed the python interpreter in a python > > program (so a non-technical user, which has no idea how to install the > > python interpreter would be able to run the script as an executable) ? > > Hey, > > This question is asked at least once a week. I'm surprised you > didn't see the threads. [It probably should be int he FAQ, but > isn't.] > > http://www.py2exe.org/http://sourceforge.net/projects/cx-freeze/http://pyinstaller.hpcf.upr.edu/cgi-bin/trac.cgihttp://cheeseshop.python.org/pypi/py2app/ > > -- > Grant Edwards grante Yow! Could I have a drug > at overdose? > visi.com Thanks a lot ! From lingyun.yang at gmail.com Sat Aug 11 03:53:30 2007 From: lingyun.yang at gmail.com (Bailu) Date: Sat, 11 Aug 2007 07:53:30 -0000 Subject: deselect an iterm in ListBox wxPython Message-ID: <1186818810.685844.263700@w3g2000hsg.googlegroups.com> Hi, I am a newbie in wxPython and doing a program with ListBox, I want to select and deselect items in this box, I have use self.devlist = wx.ListBox(self, style=wx.LB_MULTIPLE) self.Bind(wx.EVT_LISTBOX, self.select_dev, self.devlist) to create this box, but don't know how to implement self.select_dev to find out which one is clicked deselect it, if it was selected ( this is not working at default) select it, if it was not (toggle) The default behavior is, the selection is increasing, I can't deselect any of them. Thanks. Lingyun From rcdailey at gmail.com Tue Aug 21 12:00:24 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 21 Aug 2007 11:00:24 -0500 Subject: Python is removing my quotes! Message-ID: <496954360708210900p6da42670o3a28d6b0dbd4c524@mail.gmail.com> Hi, Note: I'm using Python on Windows I have an application that allows a user to submit a password as a command line parameter. The password of choice may contain any characters the user wishes, including quotes. If I do the following: python password.py "9999"MyPassword The resulting output when I print this inside the script is: 9999MyPassword Notice how the quotations have been stripped. Is it DOS doing this, or Python? Is there a way I can fix it? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Wed Aug 8 15:39:03 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 08 Aug 2007 19:39:03 -0000 Subject: Launch file from Python In-Reply-To: References: <1186594137.971393.128780@57g2000hsv.googlegroups.com> <1186594611.490723.251870@m37g2000prh.googlegroups.com> Message-ID: <1186601943.551097.82360@j4g2000prf.googlegroups.com> On Aug 8, 2:35 pm, Arnau Sanchez wrote: > kyoso... at gmail.com escribi?: > > > That's just the exit status or run status, if I recall correctly. I > > think 0 (i.e. False) means it didn't run properly and anything else is > > True, or ok. Something like that. > > The other way: 0 means "ok" while everything else means error (at least in > UNIX). The reason is clear: there is usually only one way to do things well, but > many to fail :-) > > > Technically speaking, you should > > probably switch to using the subprocess module as it is replacing that > > os module's functionality:http://www.python.org/doc/2.4/lib/module-subprocess.html > > Correct, subprocess replaces low-level os.system, os.popen*, os.spawn*, popen* > functions. Figures...I couldn't find the docs on it though...and I do know that some Windows programs return goofy numbers in the 1000s that mean it worked fine. So, in other words, the return value isn't very helpful. Mike From steve at holdenweb.com Mon Aug 6 11:26:48 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 06 Aug 2007 11:26:48 -0400 Subject: boolean operations on sets In-Reply-To: <1186409631.147290.323400@22g2000hsm.googlegroups.com> References: <1186409631.147290.323400@22g2000hsm.googlegroups.com> Message-ID: Flavio wrote: > Hi, I have been playing with set operations lately and came across a > kind of surprising result given that it is not mentioned in the > standard Python tutorial: > > with python sets, intersections and unions are supposed to be done > like this: > In [7]:set('casa') & set('porca') > Out[7]:set(['a', 'c']) > > In [8]:set('casa') | set('porca') > Out[8]:set(['a', 'c', 'o', 'p', 's', 'r']) > > and they work correctly. Now what is confusing is that if you do: > > In [5]:set('casa') and set('porca') > Out[5]:set(['a', 'p', 'c', 'r', 'o']) > > In [6]:set('casa') or set('porca') > Out[6]:set(['a', 'c', 's']) > > The results are not what you would expect from an AND or OR > operation, from the mathematical point of view! aparently the "and" > operation is returning the the second set, and the "or" operation is > returning the first. > > If python developers wanted these operations to reflect the > traditional (Python) truth value for data structures: False for empty > data structures and True otherwise, why not return simply True or > False? > > So My question is: Why has this been implemented in this way? I can > see this confusing many newbies... > it has been implemented in this way to conform with the definitions of "and" and "or", which have never been intended to apply to set operations. The result of these operations has always returned one of the operands in the case where possible, and they continue to do so with set operands. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From amccabe at hawkeyerec.com Tue Aug 14 09:50:44 2007 From: amccabe at hawkeyerec.com (Tony) Date: Tue, 14 Aug 2007 08:50:44 -0500 Subject: Script to copy database References: Message-ID: Thanks Laurent. That was very helpful. Pretty easy too. Thanks again for your help. Tony "Laurent Pointal" wrote in message news:f9s9ks$hns$1 at news2.u-psud.fr... > Tony a ?crit : >> I'm new at this and would like to know how set up a script to copy a >> database from a local computer to a network at a certain time everyday. >> Should be simple enough, but, as of now I am unfamiliar with how to do >> this. Would this be done by writing a script and setting up a scheduled >> task to run the script? Can anyone help me with the script? Just need >> it to copy an Access database from the local C: drive to a network F: >> drive. >> >> Thanks, >> Tony > > As you wrote about c: and f:, I imagine you are working under Windows. > IMHO you dont need Python for that. > > domybackup.bat > > copy c:\mypathtothefile\thefile.xxx F:\mypathdobackudir\ > > > And use your "planificateur de taches" (its corresponding english control > panel) to setup a periodic call to this batch file, eventually associate > an ad-hoc account to the task, so that the batch can access the file to > backup. > > > If you need more (ie. network access to setup/clean), here is a copy of a > script I use to export (using a Python script) an Access database. Just > replace the call to the Python script by a simple call to copy xxx yyyy. > > > > @echo off > REM LANCEMENT DE L'EXPORT DE LA BASE ADMINISTRATIVE EN MODE TACHE > REM DE FOND (BATCH). > > SET EXPORTS_BATCH=1 > REM Parametres pour se connecter a la machine de transfert. > SET EXPORTS_HOST=thecomputer > SET EXPORTS_SHARE=data > SET EXPORTS_DRIVE=O: > SET EXPORTS_USER=theremotuser > SET EXPORTS_PASSWD=theremotepasswd > REM Montage du volume. > REM le start pour permettre d'attendre que le montage soit effectif. > START /wait NET USE %EXPORTS_DRIVE% \\%EXPORTS_HOST%\%EXPORTS_SHARE% > %EXPORTS_PASSWD% /USER:%EXPORTS_USER% /PERSISTENT:No > IF ERRORLEVEL 1 GOTO erreur_montage > > REM Parametres pour le script Python. > SET SCRIPT_EXPORT="C:\Documents and Settings\myaccount\My > Documents\mybexport.py" > SET DSN_BASE_ADMIN=mydbaccound > SET LOGIN_BASE_ADMIN=mydbpasswd > SET PATH_FICHIERS_EXPORTS=%EXPORTS_DRIVE%\ > REM Variables d'environnement eventuellement utiles... > SET TEMP=%PATH_FICHIERS_EXPORTS% > SET TMP=%PATH_FICHIERS_EXPORTS% > REM Lancement du script Python qui realise l'export. > C:\Tools\Python24\python.exe %SCRIPT_EXPORT% > > REM Deconnexion du volume. > NET USE %EXPORTS_DRIVE% /DELETE > > goto termine > > :erreur_montage > ECHO "Erreur %ERROR_LEVEL% au montage de \\%EXPORTS_HOST%\%EXPORTS_SHARE% > en lecteur %EXPORTS_DRIVE%." > > :termine From DustanGroups at gmail.com Tue Aug 28 07:28:54 2007 From: DustanGroups at gmail.com (Dustan) Date: Tue, 28 Aug 2007 11:28:54 -0000 Subject: How to parse this line of code manually In-Reply-To: References: <1188270013.785762.9360@z24g2000prh.googlegroups.com> <1188271385.875677.78560@i38g2000prf.googlegroups.com> Message-ID: <1188300534.952616.109760@o80g2000hse.googlegroups.com> On Aug 28, 2:59 am, "A.T.Hofkamp" wrote: > On 2007-08-28, Davy wrote: > > > > > On Aug 28, 11:00 am, Davy wrote: > >> Hi all, > > >> It is well known that Python is appreciated for its merit of concise. > >> However, I found the over concise code is too hard to understand for > >> me. > > >> Consider, for instance, > >> def known_edits2(word): > >> return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in > >> NWORDS) > > >> Shall I understand the code in set() as > >> for e2 in edits1(e1) { > >> if e2 in NWORDS { > >> for e1 in edits1(word) { > >> e2 > >> } > >> } > > >> } > > > [SNIP] > > Hi all, I figured it myself. It is left to righ parse, right? > > So the above one is like > > for e1 in edits1(word) { > > for e2 in edits1(e1) { > > if e2 in NWORDS { > > push e2 to set > > } > > } > > } > > This is correct, although I am not sure what language you are using here, it > looks like a strange mix of Python and C to me. > > >> Any suggestions are welcome! > > The idea is known as List comprehension (for lists, obviously), and comes from > functional programming, Bird & Wadler used it in their book. > > The notation is very close to mathematics: > > { e2 | e1: edits(word), e2: edits(e1) in NWORDS } > > or in LaTeX: > > $\{ e_2 | \forall e_1: \mathrm{edits}(\mathrm{words}), > \forall e_2: \mathrm{edits}(e_1) \in \mathrm{NWORDS} \}$ > > :-) > > (which in words is something like: collect values e2, where e1 comes from > 'edits(word)', e2 comes from 'edits(e1)', and e2 in NWORDS) > For more examples: http://docs.python.org/tut/node7.html#SECTION007140000000000000000 A 'list comprehension' with parentheses instead of square-brackets creates a generator instead of a list, which can be more memory- efficient and allows for lazy evaluation. From steve at holdenweb.com Sat Aug 4 09:23:10 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 04 Aug 2007 09:23:10 -0400 Subject: how to run os.execv() to run command pslq dbname < gen.command In-Reply-To: <1186229986.707259.323130@19g2000hsx.googlegroups.com> References: <1186229986.707259.323130@19g2000hsx.googlegroups.com> Message-ID: Sonu wrote: > hello all , > i need to run psql from my py file,, > for that i am using : os.execv(path for psql ,['psql dbname < > gen.command']) > but its not working .......... > I want to watch my TV, but it's not working. Can you tell me how to fix it? ... > the command wht i want to run from this py file is :>>>psql dbname < > gen.command > > where gen.command file contain some command to create csv file from > database > > \o temp.csv > \a > \f , > select * from temp > > if u have any idea plz help me,, > Perhaps you could post your code, and a copy of the error messages you see when you run this program? That will give a much better idea of what the problem is. You do realise that the snippet you posted isn't even legal Python, right? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From arkanes at gmail.com Wed Aug 1 13:35:41 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 1 Aug 2007 12:35:41 -0500 Subject: Assertion in list comprehension In-Reply-To: <1185988597.055293.106540@q3g2000prf.googlegroups.com> References: <1185982643.001546.138180@e16g2000pri.googlegroups.com> <1185988597.055293.106540@q3g2000prf.googlegroups.com> Message-ID: <4866bea60708011035sb0cbff6s3daea4fc1286be73@mail.gmail.com> On 8/1/07, beginner wrote: > On Aug 1, 11:28 am, "Chris Mellon" wrote: > > On 8/1/07, beginner wrote: > > > > > > > > > > > > > Hi, > > > > > Does anyone know how to put an assertion in list comprehension? I have > > > the following list comprehension, but I want to use an assertion to > > > check the contents of rec_stdl. I ended up using another loop which > > > essentially duplicates the functions of list comprehension. It just > > > look like a waste of coding and computer time to me. > > > > > I just wish I could put the assertions into list comprehensions. > > > > > x=[(rec_stdl[0].st/10000.0, > > > rec_stdl[0].cl, > > > rec_stdl[0].bb, > > > rec_stdl[0].bo, > > > rec_stdl[1].bb, > > > rec_stdl[1].bo, > > > rec_stdl[0].ex > > > ) > > > for rec_stdl in rec_by_ex if len(rec_stdl)==2 > > > ] > > > > > #duplicated loop > > > if __debug__: > > > for rec_stdl in rec_by_ex: > > > l=len(rec_stdl) > > > assert(l<=2 and l>0) > > > if l==2: > > > assert(rec_stdl[0].c=="C" and rec_stdl[1].c=="P") > > > assert(rec_stdl[0].ex==rec_stdl[1].ex) > > > assert(rec_stdl[0].st==rec_stdl[1].st) > > > assert(rec_stdl[0].cp==rec_stdl[1].cp) > > > > First: All your asserts are wrong. Assert is a statement, not a > > function. These specific ones will behave as expected, but it's easy > > to accidentally write ones that always pass this way. > > > Do you mean I should not use the parentheses? > Yes. > > > Secondly: This is a waste of code, because if __debug__ is not defined > > asserts will be skipped by the compiler. You could use the same loop > > block for both branches. > > I know. My original question was how. Dan suggested to write a checker > function. > Use the second block in all cases. In any situation where "if __debug__" is False, the asserts are a noop and in fact won't even be present in the bytecode. > > > Thirdly: This sort of testing is precisely what unit tests and/or > > doctests are for. > > Agreed. > > -- > http://mail.python.org/mailman/listinfo/python-list > From a.schmolck at gmail.com Mon Aug 13 11:49:02 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Mon, 13 Aug 2007 16:49:02 +0100 Subject: Fatest standard way to sum bytes (and their squares)? References: Message-ID: Erik Max Francis writes: > Alexander Schmolck wrote: > >> Is this any faster? >> >> ordSum, orsSumSq = (lambda c:c.real,c.imag)(sum(complex(ord(x),ord(x)<<1) >> for x in data)) > > That's pretty clever, but I neglected to mention that I need to accumulate the > sums as ints/longs to avoid losing precision, so converting to floating point > isn't an optional. I think you can safely use this trick (provided it really makes things faster) provided you sum blocks no larger than 2**(53-8) bytes; if your files are really that big you'd certainly want to split summing into several blocks anyway, because otherwise you'll be doing *lots* of extra bignum arithmetic instead of int32/int64 addition (I'd assume this will slow things noticably down even in python). Another trick you could try, again using table-lookup: work on words (i.e. 2bytes) instead of single bytes again using a table (from word->(byte-sum,sq-byte-sum) tuples) ; this will half the function calls and the table size of is hopefully still small enough to not to ruin your cache-hit rate (you might want to try array). 'as From thomas at jollans.com Thu Aug 2 10:35:51 2007 From: thomas at jollans.com (Thomas Jollans) Date: Thu, 2 Aug 2007 16:35:51 +0200 Subject: Determining if file is valid image file In-Reply-To: <1186064275.652416.250540@d55g2000hsg.googlegroups.com> References: <1186064098.587590.91210@g4g2000hsf.googlegroups.com> <1186064275.652416.250540@d55g2000hsg.googlegroups.com> Message-ID: <200708021635.52490.thomas@jollans.com> On Thursday 02 August 2007, Andr? wrote: > On Aug 2, 11:14 am, Andr? wrote: > > Other than installing PIL, is there a "simple" way using Python only > > to determine if a file is a valid image file? > > > > I'd be happy if I could at least identify valid images files for gif, > > jpeg and png. Pointers to existing modules or examples would be > > appreciated. > > > > The reason why I'd prefer not using PIL is that I'd like to bundle > > such a function/module in my app. > > I should have added: I'm interesting in validating the file *content* > - not the filename :-) The file name has nothing to do with the type :-P A straightforward way you won't like: read the specs for all formats you're interested in and write the function yourself ;-) From dimitri.pater at gmail.com Mon Aug 6 05:59:36 2007 From: dimitri.pater at gmail.com (dimitri pater) Date: Mon, 6 Aug 2007 11:59:36 +0200 Subject: webbrowser.open question force Firefox Message-ID: Hi, I have a question regarding the use of webbrowser.open. On a windows XP machine, MS-IE is set as the default browser so when I do: webbrowser.open('http://localhost:8080') IE starts with this address. But in stead of launching IE, I want to launch Firefox *without* setting Firefox as the default browser globally on this machine. Any hints, ideas? Your help is most appreciated. regards, Dimitri -- --- You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From uymqlp502 at sneakemail.com Thu Aug 30 21:06:36 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Thu, 30 Aug 2007 18:06:36 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <1188518054.298017.90610@x35g2000prf.googlegroups.com> Message-ID: <1188522396.732521.51300@r23g2000prd.googlegroups.com> Ryan Ginstrom wrote: > I tried using DBC for a time in C++ (using a library with a clever > assembly-language hack). I personally found it neater having such code in > unit tests, but obviously, it's a matter of preference. I agree that it ultimately boils down to preference, but as I tried to explain earlier, I don't think that unit tests are equivalent to DBC (or, as I referred to it earlier, "self-testing code"). Unit tests are not automatically executed when you run your application. You need to write the drivers and generate sample inputs to all the functions in your application, which can be very time-consuming. And if you think you can anticipate all the weird internal data that might come up in the execution of your application, then either your application is very simple or you are fooling yourself. With self-testing code, on the other hand, all you need to do is to get sample inputs to your application (not internal inputs to functions) and run the entire application. That is much simpler and more comprehensive than unit testing. Again, I recognize that it doesn't necessarily replace unit testing completely. For one thing, unit testing can test for specific outputs for specific inputs, whereas you wouldn't want to clutter your actual code with such specific cases. For example, a unit test for a sorting function could provide a specific input and test for a specific output, but you probably wouldn't want to clutter your code with such a case. The self-tests in your code would be more for general tests. PEP 316 provides an excellent of comprehensive tests for a sorting function. If you pass those tests, you can be sure your function worked correctly. From mcl.office at googlemail.com Sun Aug 19 02:32:20 2007 From: mcl.office at googlemail.com (mosscliffe) Date: Sat, 18 Aug 2007 23:32:20 -0700 Subject: Symbolic Link In-Reply-To: <5ipbc3F3q94rmU1@mid.uni-berlin.de> References: <1187475296.173269.263080@k79g2000hse.googlegroups.com> <5ipbc3F3q94rmU1@mid.uni-berlin.de> Message-ID: <1187505140.524645.314920@d55g2000hsg.googlegroups.com> On 18 Aug, 23:49, "Diez B. Roggisch" wrote: > mosscliffe schrieb: > > > > > I am trying to create a link to a file, which I can then use in an > > HTML page. > > > The system is Linux on a hosted web service, running python 2.3. > > Other than that I have no knowledge of the system. > > > The link is created OK, but when I try to use it as filename for the > > IMG TAG, it does not get displayed. The page source of the created > > page is pointing to the link as temp/test1.jpg > > > Any ideas ? > > > srcFile = "temp/test2.jpg" > > > linkFile = "temp/test1.jpg" > > > if os.path.islink(linkFile): > > print "Link Exists", nl > > pass > > else: > > print "Making Link", nl > > os.symlink(srcFile, linkFile) > > > print '
the image

' % linkFile > > > print 'the image' % srcFile > > In what environment is that script running? If it's apache, it might be > that the apache settings disallow for following links. > > Diez It is Apache. Can I create some override in the current directory. I am afraid my Apache skills are almost zero. Thanks Richard From alberto.griggio at gmail.com Thu Aug 23 05:33:34 2007 From: alberto.griggio at gmail.com (Alberto Griggio) Date: Thu, 23 Aug 2007 11:33:34 +0200 Subject: python debugging under emacs? References: Message-ID: > Is there a debugging mode in emacs that works well with python? > > I tried gud, but it was giving me errors, so I thought I'd ask before I > try to get it to work: Is there an emacs mode (perhaps gud) that'll give a > view of the python source, and currenly executing line, the ability > inspect datastructures, etc.? You know, like a modern debugger? :) > > I also looked at ddd, but it was cranky too, and apparently hasn't seen a > new release in years. > > I'm really more of a vim person than an emacs person, but if emacs will > do what I want, I'd happily use it - for this. :) You can try pydb (http://bashdb.sourceforge.net/pydb/), has a GUD interface that in my experience works better than pdb... HTH, Alberto From philippe.martin at att.net Mon Aug 27 22:32:17 2007 From: philippe.martin at att.net (hg) Date: Mon, 27 Aug 2007 19:32:17 -0700 Subject: SCF released to GPL In-Reply-To: References: <46d29a6c$0$27404$ba4acef3@news.orange.fr> Message-ID: hg wrote: > M?ta-MCI (MVP) wrote: >> Salut ! >> >> Le deuxi?me envoi aurait pu ?tre en fran?ais. >> Cela aurait ?vit? le doublon, tout en maintenant le message. >> >> @+ >> >> Michel Claveau >> > > ;-) > > No: > 1) The redundancy is due to the fact that I just moved to another > state/ISP and that ... for some reason, the initial post did not show > for quite some times. > > 2) I'm desperately searching for the French NG from my client but cannot > find it ... any clue ? Maybe you can pass the message ? > > hg PS: I know this is not a python issue. can someone out there using news.sf.sbcglobal.net see fr.comp.lang.python ? could the name be different ? Thanks, hg From zentraders at gmail.com Sat Aug 11 15:37:36 2007 From: zentraders at gmail.com (Zentrader) Date: Sat, 11 Aug 2007 12:37:36 -0700 Subject: Who told str() to round my int()'s!!! In-Reply-To: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> References: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> Message-ID: <1186861056.323621.195570@e9g2000prf.googlegroups.com> On Aug 11, 9:40 am, "Adam W." wrote: > After a fair amount of troubleshooting of why my lists were coming > back a handful of digits short, and the last digit rounded off, I > determined the str() function was to blame: > > >>> foonum > > 0.0071299720384678782 > > >>> str(foonum) > '0.00712997203847' > > Why in the world does str() have any business rounding my numbers, and > how do I get around this? If 15 digit precision is a concern, I would suggest that you us the decimal class instead of floating points. Floating point problems on X86 machines are well documented. http://docs.python.org/lib/module-decimal.html http://pydoc.org/2.4.1/decimal.html http://gmpy.sourceforge.net/ From a.schmolck at gmail.com Sun Aug 12 05:53:09 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Sun, 12 Aug 2007 10:53:09 +0100 Subject: Fatest standard way to sum bytes (and their squares)? References: Message-ID: Erik Max Francis writes: > For a file hashing system (finding similar files, rather than identical ones), > I need to be able to efficiently and quickly sum the ordinals of the bytes of > a file and their squares. Because of the nature of the application, it's a > requirement that I do it in Python, or only with standard library modules (if > such facilities exist) that might assist. > > So far the fastest way I've found is using the `sum` builtin and generators:: > > ordinalSum = sum(ord(x) for x in data) > ordinalSumSquared = sum(ord(x)**2 for x in data) > > This is about twice as fast as an explicit loop, but since it's going to be > processing massive amounts of data, the faster the better. Are there any > tricks I'm not thinking of, or perhaps helper functions in other modules that > I'm not thinking of? Is this any faster? ordSum, orsSumSq = (lambda c:c.real,c.imag)(sum(complex(ord(x),ord(x)<<1) for x in data)) 'as From bryan at redfedora.co.uk Mon Aug 6 14:01:12 2007 From: bryan at redfedora.co.uk (Bryan Hepworth) Date: Mon, 06 Aug 2007 19:01:12 +0100 Subject: Tkinter or wxpython? In-Reply-To: <4866bea60708061043x34fb94edg8b675eb1608af9b1@mail.gmail.com> References: <1186410331.905174.21370@q3g2000prf.googlegroups.com> <7xps204tin.fsf@ruckus.brouhaha.com> <7xlkcopu4r.fsf@ruckus.brouhaha.com> <7x3aywr4tc.fsf@ruckus.brouhaha.com> <4866bea60708061043x34fb94edg8b675eb1608af9b1@mail.gmail.com> Message-ID: <46B761E8.8090306@redfedora.co.uk> Chris Mellon wrote: > On 06 Aug 2007 09:44:15 -0700, Paul Rubin > <"http://phr.cx"@nospam.invalid> wrote: > >> "Chris Mellon" writes: >> >>>> Might or might not matter for the application, especially considering >>>> that tkinter is part of the discussion. >>>> >>> The point is that you have no option with the browser - even Tkinter >>> has platform theming support now. >>> >> Hmm, I don't know anything about that. I'm taking the view that for a >> lot of apps, the requirement is to just put some functionality on the >> screen, with slick visual appearance having little value or even >> negative value. >> >> > > Define "functionality". From the rest of your posts, that seems to be > limited to "press buttons" and "type small amounts of non-formatted > text" on the interaction side and "display small amounts of simply > formatted text" on the output side. I'm not denying that you can get > by with this functionality in a large number of cases, but it's > certainly not optimal in general. If it were, we'd all still be using > VT100 terminals. > > >>> ...Gmail uses ajax instead of a page load when you start >>> typing a reply, >>> >> I see, the answer to what caused your problem is approximately "ajax >> is evil", or alternatively, the gmail app attempts slickness with a >> tool that doesn't support slickness that well. OK, I can accept that >> using browsers for slick interfaces has its problems, but the answer >> (a lot of the time, not always) is to just decide you don't need >> slickness. >> >> > > What you're calling "slickness" is what other people call "usable". > Obviously it could be done without the ajax, but you lose features and > usability. It's slower, because it takes a full page load, and I lose > the context of the discussion. > > >>>> File i/o and file system browsing are available from javascript if the >>>> user grants permission. >>>> >>> Which they won't (I don't even know how, from Firefox), so you can't >>> rely on it working. >>> >> The application javascript pops a dialog asking for permission and the >> user clicks yes or no. If you can get them to install a desktop app >> (gah!!) then you can certainly get them to click yes in a browser. >> The permission mechanism is admittedly browser dependent. >> >> > > My out of the box firefox install simply denies the operation and > raises a javascript error. > > >>> But not of anything else. I've often wanted to drag & drop a file onto >>> the file upload box in gmail, for example. >>> >> Well, ok, that's a slick feature that your app might need. None of >> mine have needed it so far. >> >> >>> How about something as simple as context menus? >>> >> Unnecessary slickness for many apps. I've never needed it. >> >> > > How have you decided that you've never needed it? Have you ever worked > with a UI designer or workflow expert? Or have you just never bothered > to implement it and you never heard anything from your users? How > closely have you worked with the users of your applications? > > >>>> Multiple windows are evil most of the time, >>>> >>> Multiple windows are the common case on the mac. They're not rare on >>> other platforms as well. The fact that your windows are constrained to >>> the browser and can't be torn off is a large limitation. No toolbars, >>> no palettes, no modal dialogs (except on IE, or if you constrain them >>> to the browser). Lots of unnecessary chrome on your extra windows, too >>> (see below). >>> >> You can get rid of the chrome with javascript, but the extra windows >> are still usually evil and unnecessary. Just because they get used a >> lot doesn't change that. A heck of a lot of deployed interfaces, web >> or desktop, simply suck. >> >> > > As phishing attacks become more common, browsing are restricting the > ability to remove or modify chrome. Again, a good feature for a > browser, not so much for an application platform. > > >>>>> More platforms to develop on and test with. >>>>> >>>> Compared to a desktop app? I don't think so. >>>> >>> Did you ever try counting? X browsers * Y browser versions * Z >>> platforms. There are javascript and CSS bugs and differences between >>> all of these. >>> >> If you can tell them to install a desktop app, you can alternatively >> tell them what browser to use. For example we use a complicated >> firefox-only browser app where I work, that relies heavily on canvas >> objects. But if you write your application with straightforward html >> you tend to have very few platform problems. >> >> > > It depends on your target audience and deployment arena. The context > is cross platform applications, so at least 2 browsers and at least 2 > platforms are required. Don't forget browser versioning, too - IE 5 is > different than IE 6 is different than IE 7. Even "straightforward" > HTML has non-trivial cross browser differences. > > >>> From my own professional experience, it's not any easier >>> to account for browser differences than it is for platform >>> differences. It's getting better as more people jump on the web >>> bandwagon and CSS and JS abstraction libraries show up, >>> >> I guess I see that stuff as mostly-evil and prefer straightforward >> html. >> >> > > You simply can't do much of anything beyond display text and basic > crud with straightforward HTML without stying. If that is the sole > limit of your UI needs, then bully for you but that's hardly the > common case and I'd venture that you don't have the experience to > support the rather sweeping claim you made. > > >>> I'm not talking about chrome and slickness. I'm talking about basic >>> usability concerns like "will this work with a higher font size" and >>> "will it reflow in a sensible way if I change the window size". The >>> CSS box model works okay for text, it's not so good for widgets. >>> >> I just haven't had this problem with HTML interfaces. I've never even >> used CSS, though that makes me a bit of a lamer. An interface that >> needs to fill the whole screen with widgets is probably too >> complicated. >> >> > > An application is not a book. Of course you fill the whole "screen" > with widgets - your application is defined by the widgets that it has, > and the amount of space those widgets take up is your screen space. > > >>> More than a few web apps end up writing their own layout engines in >>> dynamic javascript. This is sad. While I'm talking about chrome, add >>> "wasted screenspace due to browser chrome" to a limitation of web >>> apps, again unless you write your own browser host. This is another >>> example of a feature that makes a good browser (don't let arbitrary >>> web pages mess with my web browser functionality) clashing with the >>> desires of a good application (don't waste screen space with >>> irrelevant functionality). >>> >> I guess the term I'd use to describe all these effects is "slick" and >> a heck of a lot of the time it's just not needed. Anyway you can pop >> a chromeless browser window with a simple javascript call. >> >> >>> Man, you should be in PR with the way you spin things. You can't >>> implement anything except the most trivial of applications using only >>> the simple, familiar web elements like HTML forms. Anything more >>> complicated than that needs to be done with DHTML and probably AJAX, >>> and those UI elements don't look anything like the familiar ones. You >>> go in one breath from saying that you can implement dialogs in HTML to >>> saying that the rich client is the *less* familiar of the interfaces? >>> >> I don't see the contradiction--with HTML you have just a few widgets >> that everyone understands and you get an interface that's almost >> always self-explanatory. Yes you could call those interfaces trivial, >> but the little secret that I'm trying to convey is that very often, >> trivial is all that's needed. >> >> > > That's simply not true, and I don't think you can objectively justify > it. Besides, you specifically claimed HTML dialogs as being a > replacement for "real" ones, and that can't be done using trivial > interfaces. It requires DHTML, sometimes ajax, and/or browser support. > > >>> If you'd said "if you're making something really simple that has >>> limited rich UI or data entry needs, consider a web application >>> instead" I wouldn't have posted. A web application is something you >>> make because the deployment and access benefits outweigh the UI and >>> integration limitations, not as your default "go to" whenever you >>> create an application. >>> >> Well, I could back off to somewhere between the two. Like, "ask >> yourself whether your application really needs a rich gui or complex >> data entry features. If you can get by with a simple HTML interface, >> and a lot of the time you can, you'll probably have an easier time >> doing it that way and that should be the default". >> >> > > I would challenge the assumption that, starting from zero, it is less > complicated to write a web application, much less a "pretend" web app > using a local web server, than a desktop application using Tkinter > (ick) or wxPython or pyQt. I would also challenge the assumption that > 'a lot of the time' you can get away with a simple HTML interface, at > least by my personal definition of 'get away with'. I've worked a lot > with data entry people, where the actual requirements in terms of > slickness and flash are quite small. But "basic html" simply does not > fit the bill. There is a real cost in terms of how fast and how > accurately they can enter data in this environment. > > Moreover, if you *don't* need global access or zero-deployment > (zero-deployment is always nice but most environments where you can > reasonably force a specific browser and version also have IT > infrastructure), then you should ask yourself if forcing your > application in the web app model (I haven't even touched on the whole > stateless HTTP being mapped to a stateful environment issue, or the > need to manage the local web server) actually buys you anything. I > simply do not buy the claim that HTML interfaces are necessarily > simpler in any but the most trivial of cases, and even in those > super-trivial applications there are often hidden concerns that don't > filter up to management. > > >>> I'd like an example you have of a desktop application that could have >>> just as easily been a web application. Bonus points if it's not a CRUD >>> screen, and double bonus if you don't just handwave away things like >>> file browsing. Although there are benefits even for the crud screen - >>> I've written screens and applications for data entry professionals and >>> they almost always prefer the speed optimizations you can make in a >>> client application. >>> >> I guess I've written 4 or 5 nontrivial desktop gui apps and ZERO of >> them had file browsing. One of them did need access to the pc's >> serial port, which means there had to be application code on the >> desktop, but the gui could have been a browser (talking to an >> application-embedded http server) if browsers were available in those >> days. Another one of them saved some state to a local file but it did >> that without file browsing, and could have instead saved the state on >> a remote server if it were written as a remote app. >> >> > > Exactly how much time do you think using an HTML interface with an > embedded server would have saved you, especially considering the > careful care you have to take with access to the serial port? For the > record, I've written over a dozen client applications, many of which I > would consider trivial (but used features that would be expensive or > impossible to implement in the browser) and probably twice that many > web apps. > > >> I'm not saying file browsing is never needed, just that from >> experimental observation, it's quite often not needed. >> >> > > Plural of anecdote and all that. Make a survey of every application > that you interact with and see how many of them need to interact with > arbitrary files from the filesystem. > > >> Again, it all depends on what you're trying to do. For data entry >> stuff you probably want the data on a remote server anyway, and you >> can do basic CRUD validation with fairly simple javascript. Maybe >> that departs from pure HTML but it's nothing like the ajax/dhtml >> madness that causes the problems you've described. >> -- >> > > CRUD with javascript is something I actually have a lot of experience > with. Deficiencies in the data entry UI have real consequences because > you get invalid data and slow data entry speeds. The auto-completing > combo-box, for example, is simply impossible in a browser without > quite complicated (and slow) DHTML and is a huge boon for data entry. > > I'm not trying to claim that there are no benefits to web > applications. But I often see people touting the web as a *superior > application platform*, which is simply false, and as innately simpler > to develop for, which is also false. > I'm also in a similar predicament starting to look at Python for the first time. I'd be curious to know peoples take on other GUI's like pygtk and pyqt for example to get a fuller picture. As a total newbie the list seems daunting so taking advantage of other peoples experiences seems like a good idea. Bryan From bj_666 at gmx.net Wed Aug 1 02:31:34 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Aug 2007 06:31:34 GMT Subject: A way to re-organize a list References: <1184857535.033057.49150@m3g2000hsh.googlegroups.com> <1185932029.235957.226720@e9g2000prf.googlegroups.com> Message-ID: <5hanm6F3inuf2U3@mid.uni-berlin.de> On Wed, 01 Aug 2007 01:33:49 +0000, beginner wrote: > On Jul 19, 10:05 am, beginner wrote: >> Hi Everyone, >> >> I have a simple list reconstruction problem, but I don't really know >> how to do it. >> >> I have a list that looks like this: >> >> l=[ ("A", "a", 1), ("A", "a", 2), ("A", "a", 3), ("A", "b", 1), ("A", >> "b", 2), ("B", "a", 1), ("B", "b", 1)] >> >> What I want to do is to reorganize it in groups, first by the middle >> element of the tuple, and then by the first element. I'd like the >> output look like this: >> >> out=[ >> [ #group by first element "A" >> [("A", "a", 1), ("A", "a", 2), ("A", "a", 3)], #group by >> second element "a" >> [ ("A", "b", 1), ("A", "b", 2)], #group by second element >> "b" >> ], >> [ #group by first element "B" >> [("B", "a", 1)], >> [("B", "b", 1)] >> ] >> ] >> >> All the solutions I came up with are difficult to read and even harder >> to go back and change, and I just feel are too complicated for such a >> simple problem. I am wondering if anyone here has some insight. >> >> If there is a 'functional' way to do this, it would be even greater. >> >> Thanks, >> Geoffrey > > I guess I still don't quite get functional programming. Here is my > imperitive way to do it in O(n). I didn't try to follow it but are you sure about O(n)? With the inner loop going from 0 to `level` it looks suspiciously quadratic to me. You really should try to grasp the `itertools.groupby()` solution. And the result of that script looks strange: [[[[1, 2, 3, 4], [1, 2, 4, 5], [1, 2, 'A', 'B']]], [[[2, 2, 'A', 'C']]]] Aren't the two top level elements wrapped in one list too much? Furthermore the test data doesn't contain an example where the first item is the same but the second item is different. > def group_items(source_list, f_list, target=[]): Default arguments are evaluated *once* when the ``def`` is executed. So all calls to this function share the same list object bound to `target`. Call this function twice without an explicit `target` and you'll see the problem. Ciao, Marc 'BlackJack' Rintsch From B.Ogryczak at gmail.com Thu Aug 23 08:35:11 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: Thu, 23 Aug 2007 12:35:11 -0000 Subject: =?utf-8?q?Re:_sentance_containg_the_string_or_symbol_=CE=A9?= In-Reply-To: <1187868007.012689.224290@z24g2000prh.googlegroups.com> References: <1187868007.012689.224290@z24g2000prh.googlegroups.com> Message-ID: <1187872511.419052.30590@x40g2000prg.googlegroups.com> On 23 ago, 13:20, yadin wrote: > how can i print a sentance containg the string or symbol ? in python > and also lambda? Well, you can use this dictionary to find out its unicode code point: from htmlentitydefs import name2codepoint unichr(name2codepoint['Omega']) u'\u03a9' unichr(name2codepoint['Lambda']) u'\u039b' print u'this is upper case omega: \u03a9, and this is upper case lambda: \u039b' See http://www.digitalmediaminute.com/reference/entity/ for entity names. From brian at rkspeed-rugby.dk Thu Aug 2 03:59:26 2007 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: Thu, 02 Aug 2007 06:59:26 -0100 Subject: Floats as keys in dict References: <5hcthiF3ki7cjU1@mid.individual.net> Message-ID: greg writes: > Be careful with this. If you have two values that are > very close together, but on different sides of a rounding > boundary, they will end up as distinct keys even though > they "should" be regarded as equal. I don't think this is a big problem. It will only give me one more node. Wouldn't the same be possible if I use bisect? -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk From michele.simionato at gmail.com Sun Aug 26 13:40:28 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Sun, 26 Aug 2007 17:40:28 -0000 Subject: lisper learning python, ... could you please comment my first python program? In-Reply-To: <1188143768.742884.38520@r29g2000hsg.googlegroups.com> References: <1188143768.742884.38520@r29g2000hsg.googlegroups.com> Message-ID: <1188150028.716338.64390@57g2000hsv.googlegroups.com> On Aug 26, 5:56 pm, neptundan... at gmail.com wrote: > Hi, > to extend my skills, I am learning python. I have written small > program which computes math expression like "1+2*sin(y^10)/cos(x*y)" > and similar, so far only + - * / ^ sin con tan sqrt are supported. But > my program is quite inextensible, I have to change the code to add new > functions... Could some fellow experienced pythonista give me some > tips how to make my program shorter, and more extensible? I understand that you are doing this as a learning exercise. Still, I would recommend you to have a look at the shlex module in the standard library and to pyparsing. Looking at their source code should should give you some idea. BTW, since you are familiar with Lisp, I would recommend you IPython for a better interactive experience. Michele Simionato From greg at cosc.canterbury.ac.nz Wed Aug 1 22:19:59 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 02 Aug 2007 14:19:59 +1200 Subject: Floats as keys in dict In-Reply-To: References: Message-ID: <5hcthiF3ki7cjU1@mid.individual.net> Brian Elmegaard wrote: > However, the dict keys are then floats and I have to round the values > of new possible nodes in each step. Be careful with this. If you have two values that are very close together, but on different sides of a rounding boundary, they will end up as distinct keys even though they "should" be regarded as equal. I don't think there's any way to use a dictionary for this that works properly in all cases. Whatever scheme you come up with for comparison and hashing will suffer from this problem one way or another. So, like Alex said, you need a different data structure. -- Greg From Brian.McCann at viziant.net Fri Aug 24 12:02:28 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Fri, 24 Aug 2007 12:02:28 -0400 Subject: creating a tar file with python References: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx><93066C069973ED448DC2BCEA9C44A7383BE2ED@efmailx><46CE4D3D.7020106@holdenweb.com><93066C069973ED448DC2BCEA9C44A7383BE2EE@efmailx><1187969070.3385.20.camel@dot.uniqsys.com> <0A8A92C4-3F3A-42C4-A6F5-770C5ADFB6E5@leafe.com> Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE2F0@efmailx> I don't care if Steve Holden is the python God himself, He's a rude, arrogant, vulgar human who shows his true level of intellect by his use of profanity And he goes one level lower stating he respects the python group he spews his profanity to He chose to respond to my question, no one dragged him out of bed as hi so quickly pointed out. Re-read the thread! If your three chums are indicative to the type of people in this group Python is in sorry state ________________________________ From: python-list-bounces+brian.mccann=viziant.net at python.org on behalf of Ed Leafe Sent: Fri 8/24/2007 11:33 AM To: Carsten Haese Cc: python-list at python.org Subject: Re: creating a tar file with python On Aug 24, 2007, at 11:24 AM, Carsten Haese wrote: > You clearly have no idea who you're talking to. I suggest you > Google for > '"Steve Holden" Python' to get a clue. Good luck finding any more help > here. Even if it were Joe Nobody to whom he was directing those comments, it was *way* out of line. The fact that it was Steve only reinforces the cluelessness of the writer. -- Ed Leafe -- http://leafe.com -- http://dabodev.com -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at liquidtrust.org Wed Aug 22 15:52:06 2007 From: lists at liquidtrust.org (Charlie) Date: Wed, 22 Aug 2007 13:52:06 -0600 Subject: MsiLib Message-ID: <20070822135206.9dm789grk08ccsgw@74.220.202.27> Thanks for the help. That definitely gets me on the right track. I am having an issue though. I keep getting the error that MSIDBOPEN_READONLY is not defined. Here is my code for testing. Am I missing something really obvious or is something just not working that should and my system is screwed up somewhere? Thanks. import msilib c = msilib.OpenDatabase('test.msi', MSIDBOPEN_READONLY) view = c.OpenView("SELECT * FROM Registry") record = view.Fetch() From llasram at gmail.com Wed Aug 22 19:06:51 2007 From: llasram at gmail.com (Marshall T. Vandegrift) Date: Wed, 22 Aug 2007 19:06:51 -0400 Subject: Class destruction References: <496954360708221117pd7465fr838a24b167a1dcdd@mail.gmail.com> <46CC8482.9040100@gmx.de> Message-ID: <876437cgok.fsf@seneca.iss.local> Nils Oliver Kr?ger writes: > If you want to "reuse" the file, you will have to delete your classes > instance explicitly using the del statement ... this will also call > the destructor. Sometimes, but not always. The `del' statement simple removes the reference to the instance and decrements its reference count. The __del__() routine for the instance still only gets called whenever the object is actually garbage collected. Furthermore, the Python Reference Manual notes that: Circular references which are garbage are detected when the option cycle detector is enabled (it's on by default), but can only be cleaned up if there are no Python-level __del__() methods involved. [http://docs.python.org/ref/customization.html] The proper way to handle the case presented by the OP is for the class to expose a close()-like method and/or -- for use with Python 2.5 and later -- implement the methods of the context manager protocol [http://docs.python.org/ref/context-managers.html]. The following code supports basic usage: def close(self): self._file.close() print "File closed" def __enter__(self): return self def __exit__(self, *exc_info): self.close() return False Then the users of this class can freely do any of: f = fout(filename) ... f.close() with fout(filename) as f: ... with closing(fout(filename)) as f: ... HTH, -Marshall From evan at yelp.com Mon Aug 13 15:23:10 2007 From: evan at yelp.com (Evan Klitzke) Date: Mon, 13 Aug 2007 12:23:10 -0700 Subject: Assignments and Variable Substitution In-Reply-To: References: Message-ID: On 8/13/07, brad wrote: > I'd like to do something like this: > > var = '123' > %s = [], %var > > So that, in the end, var is '123' and an empty list is named '123' as > well. The list assignments are created during a loop. You can't assign a variable whose name is 123, but you can do this sort of thing with setattr. -- Evan Klitzke From antroy at gmail.com Tue Aug 21 05:46:27 2007 From: antroy at gmail.com (Ant) Date: Tue, 21 Aug 2007 02:46:27 -0700 Subject: The folder a script is executed in In-Reply-To: <1187688599.348139.297150@o80g2000hse.googlegroups.com> References: <1187687436.476773.276550@22g2000hsm.googlegroups.com> <1187688437.358293.322460@22g2000hsm.googlegroups.com> <1187688599.348139.297150@o80g2000hse.googlegroups.com> Message-ID: <1187689587.644109.14110@r34g2000hsd.googlegroups.com> On Aug 21, 10:29 am, aine_ca... at yahoo.com wrote: > On 21 Aug, 11:27, Ant wrote: > > > > > On Aug 21, 10:10 am, aine_ca... at yahoo.com wrote: > > ... > > > > myLocation = GetMyLocation() > > > print myLocation > > > > >> C:/folder > > > Do you mean the folder containing the script? Or the current working > > directory? > > > If the former, then look at os.path.split(sys.argv[0])[0] > > If the latter, try something like: os.path.abspath(os.curdir) > > > -- > > Ant... > > >http://antroy.blogspot.com/ > > The following code - > > import os > import sys > print os.getcwd() + "." > print os.path.split(sys.argv[0])[0] + "." > > gives me - > > C:\Documents and Settings\me\Desktop. > . Which looks correct. You've executed the code in an interactive session launched from a desktop shortcut at a guess. You won't get the location of the script unless you are actually running a script :-). Of course you'll get a current working directory however you are running python. -- Ant... http://antroy.blogspot.com/ From rdm at rcblue.com Tue Aug 14 01:49:30 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 13 Aug 2007 22:49:30 -0700 Subject: Binary, Hex, and Decimal string conversions In-Reply-To: <496954360708130735s73a0fb02mbba68dad14f59193@mail.gmail.co m> References: <496954360708111559s1cef4212pabd14e95b27435ea@mail.gmail.com> <496954360708121620r4dd68ac9o430326ae8c8ae04d@mail.gmail.com> <649D1D6C-A44C-4D03-920D-489BBD108789@jedimindworks.com> <20070813034138.CA4C81E4012@bag.python.org> <496954360708130735s73a0fb02mbba68dad14f59193@mail.gmail.com> Message-ID: <20070814054942.8EED81E4004@bag.python.org> An HTML attachment was scrubbed... URL: From jyoung79 at kc.rr.com Wed Aug 8 21:58:55 2007 From: jyoung79 at kc.rr.com (jay) Date: Wed, 8 Aug 2007 20:58:55 -0500 Subject: Python mode Message-ID: I'm starting to learn how to use emacs (on Mac OS 10.4) and I found that you can load something called python-mode.el which looks like it can help when writing Python code in emacs. I'm hoping it can color python syntax as well as indent it correctly, etc. My problems are: 1. Where should you place the 'python-mode.el' file? I downloaded a folder from 'sourceforge.net' that contains 4 files (python-mode.el, doctest-mode.el, pycomplete.el and pycomplete.py). I couldn't find any installation instructions anywhere. Do I use all 4 files or just the one and where should it go? One web-site said the 'python- mode.el' file needed to be compiled before being moved to whereever it needs to go. How does one compile these things? 2. All the web-sites I found about installing this said I should change my .emacs file which should be located in my home folder. I can't find a .emacs file anywhere on my machine. The only thing close to it is a .emacs.d folder which contains an autosave folder. Does anyone know where this .emacs file is located? Or do I need to manually create one? Thanks for looking at my questions. Jay -------------- next part -------------- An HTML attachment was scrubbed... URL: From cvezvu at gmail.com Thu Aug 16 11:05:13 2007 From: cvezvu at gmail.com (cvezvu at gmail.com) Date: Thu, 16 Aug 2007 08:05:13 -0700 Subject: Guitars, amps, tabs and more Message-ID: <1187276713.342841.226620@57g2000hsv.googlegroups.com> Reviews of latest models of best guitars, fender, gibson, yamaha, and many more, with pictures and prices. http://pro-guitars.blogspot.com/ And if you want to win a free guitar go here http://freeguitars.blogspot.com/ From ldo at geek-central.gen.new_zealand Fri Aug 31 22:00:01 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 01 Sep 2007 14:00:01 +1200 Subject: strings (dollar.cents) into floats References: <877incd20i.fsf@benfinney.id.au> <46d75cf3$0$7698$9b4e6d93@newsspool2.arcor-online.net> <1188575044.874256.42960@50g2000hsm.googlegroups.com> Message-ID: In message <1188575044.874256.42960 at 50g2000hsm.googlegroups.com>, sturlamolden wrote: > There are fractions that can be exactly represented by floats that > cannot be exactly represented by decimals. There are no such. From jmtulloss at gmail.com Thu Aug 9 22:23:09 2007 From: jmtulloss at gmail.com (Justin T.) Date: Fri, 10 Aug 2007 02:23:09 -0000 Subject: Threaded Design Question In-Reply-To: <1186706363.947909.185460@e9g2000prf.googlegroups.com> References: <1186683909.797328.68770@i13g2000prf.googlegroups.com> <1186706363.947909.185460@e9g2000prf.googlegroups.com> Message-ID: <1186712589.266128.285110@j4g2000prf.googlegroups.com> On Aug 9, 5:39 pm, MRAB wrote: > On Aug 9, 7:25 pm, half.ital... at gmail.com wrote: > > > Hi all! I'm implementing one of my first multithreaded apps, and have > > gotten to a point where I think I'm going off track from a standard > > idiom. Wondering if anyone can point me in the right direction. > > > The script will run as a daemon and watch a given directory for new > > files. Once it determines that a file has finished moving into the > > watch folder, it will kick off a process on one of the files. Several > > of these could be running at any given time up to a max number of > > threads. > > > Here's how I have it designed so far. The main thread starts a > > Watch(threading.Thread) class that loops and searches a directory for > > files. It has been passed a Queue.Queue() object (watch_queue), and > > as it finds new files in the watch folder, it adds the file name to > > the queue. > > > The main thread then grabs an item off the watch_queue, and kicks off > > processing on that file using another class Worker(threading.thread). > > > My problem is with communicating between the threads as to which files > > are currently processing, or are already present in the watch_queue so > > that the Watch thread does not continuously add unneeded files to the > > watch_queue to be processed. For example...Watch() finds a file to be > > processed and adds it to the queue. The main thread sees the file on > > the queue and pops it off and begins processing. Now the file has > > been removed from the watch_queue, and Watch() thread has no way of > > knowing that the other Worker() thread is processing it, and shouldn't > > pick it up again. So it will see the file as new and add it to the > > queue again. PS.. The file is deleted from the watch folder after it > > has finished processing, so that's how i'll know which files to > > process in the long term. > > I would suggest something like the following in the watch thread: > > seen_files = {} > > while True: > # look for new files > for name in os.listdir(folder): > if name not in seen_files: > process_queue.add(name) > seen_files[name] = True > > # forget any missing files and mark the others as not seen, ready for > next time > seen_files = dict((name, False) for name, seen in seen_files.items() > if seen) > > time.sleep(1) Hmm, this wouldn't work. It's not thread safe and the last line before you sleep doesn't make any sense. From BH at bh.com Mon Aug 27 06:08:29 2007 From: BH at bh.com (BH) Date: Mon, 27 Aug 2007 12:08:29 +0200 Subject: wx.grid and different Value Choice each line ? Message-ID: <46d2a1f9$0$27412$ba4acef3@news.orange.fr> Hi, Hox can I have different value choice for each line in a grid with wxPython ? I want to develop a small software for satisfaction surveys. Each line of the grid is a different question. Sometimes answers are the sames between two lines, but sometimes not. Thx, Bertrand From sjmachin at lexicon.net Fri Aug 3 19:30:01 2007 From: sjmachin at lexicon.net (John Machin) Date: Fri, 03 Aug 2007 16:30:01 -0700 Subject: xlrd question In-Reply-To: References: Message-ID: <1186183801.441601.207030@g12g2000prg.googlegroups.com> On Aug 4, 1:22 am, JYOUN... at kc.rr.com wrote: > When running 'python setup.py install' to install items for xlrd to work, does anybody know > what items are > installed and where items are installed at on a Mac (OS 10.4)? I'm assuming it mainly uses > things out of the xlrd > folder, but was curious if it copies files to other locations. > Background: I'm the xlrd author. I've never even sat down in front of a Mac. xlrd is a pure-Python package. The setup.py is close to vanilla. Consequently (I'm guessing) the files should be installed on a Mac in a folder called P/lib/site-packages/xlrd where P is the folder containing the Python executable etc. It's easy to find out exactly where. Result on my Windows box: >>> import sys, xlrd; print sys.version; print xlrd.__file__ 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] C:\python25\lib\site-packages\xlrd\__init__.pyc At some stage in the distant past, the hierarchy was somewhat flatter, e.g. >>> import sys, xlrd; print sys.version; print xlrd.__file__ 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] C:\python21\xlrd\__init__.pyc Script files like runxlrd.py should end up somewhere else, probably in P/Scripts. If all else fails, use the shell find command. BTW, I've never had anyone else ask where files are installed, on any platform. What is your problem/concern? Cheers, John From grante at visi.com Fri Aug 24 17:08:33 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 24 Aug 2007 21:08:33 -0000 Subject: py2exe/distutils: how to include a tree of files? References: <13cuhdr58m5one7@corp.supernews.com> Message-ID: <13cui6h16a6v80d@corp.supernews.com> On 2007-08-24, Grant Edwards wrote: > I'm packaging up a python program and need to include an entire > directory tree in the distribution. the data_files=[] option to > setup() is fine for individual files, but what do I do when I > need to include an entire directory tree? [...] > There must be some py2exe documentation somewhere... I can't even find anywhere that documents the 'data_files=[]' option to setup(). It certainly doesn't show up when I do help(setup) after importing setup from distutils.core. -- Grant Edwards grante Yow! What a COINCIDENCE! at I'm an authorized "SNOOTS visi.com OF THE STARS" dealer!! From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Aug 14 15:57:29 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 14 Aug 2007 21:57:29 +0200 Subject: chmod g+ Equivalent References: <1187042290.821786.178420@19g2000hsx.googlegroups.com> <5ic53dF3pi903U1@mid.individual.net> <1187045766.841230.148600@b79g2000hse.googlegroups.com> Message-ID: <5iefp9F3o8k6fU1@mid.individual.net> milan_sanremo wrote: > The group ownership is set by chown, Yes -- by storing a group's gid (group ID) in the file metadata. The group ID is an int from /etc/group. > but the group id (setgid bit) is set by chmod. "group id" is not "setgid bit". The "setgid bit" is one bit in the file metadata that tells the OS to change the group ID based privileges for a process. Regards, Bj?rn -- BOFH excuse #412: Radial Telemetry Infiltration From gagsl-py2 at yahoo.com.ar Mon Aug 20 15:32:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 20 Aug 2007 12:32:44 -0700 Subject: regular expression dictionary search In-Reply-To: <1187624901.163499.157680@i13g2000prf.googlegroups.com> References: <1187624901.163499.157680@i13g2000prf.googlegroups.com> Message-ID: <1187638364.694573.53130@o80g2000hse.googlegroups.com> On 20 ago, 12:48, mkPyVS wrote: > On Aug 20, 9:35 am, "Shawn Milochik" wrote: > > As a side note unless you are searching large buffers it is possibly > more costly to compile into a re object then do a match with it as > opposed to let the match object perform a compile a function level > itself- if you use the class option above I would recommend storing > the re.compiled versions of your patterns in the dictionary > (everything is an object!) rather than the string repr and issuing a > compile. The re module already does exactly that - compiled expressions are cached in a dictionary (but this fact appears to be undocumented, so one should not rely heavily on this). Anyway, if you have the regular expression object, it's better to call its match method directly instead of using the module match function. Using re.match(compiled_regex,...) is the worst case. In the posted original code, replace re.match(regex, aWord) with regex.match(aWord). -- Gabriel Genellina From Michael.J.Fromberger at Clothing.Dartmouth.EDU Tue Aug 28 15:48:34 2007 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Tue, 28 Aug 2007 15:48:34 -0400 Subject: tempfile.mkstemp and os.fdopen References: <1188323759.955043.317630@19g2000hsx.googlegroups.com> Message-ID: In article <1188323759.955043.317630 at 19g2000hsx.googlegroups.com>, billiejoex wrote: > Hi there. > I'm trying to generate a brand new file with a unique name by using > tempfile.mkstemp(). > In conjunction I used os.fdopen() to get a wrapper around file > properties (write & read methods, and so on...) but 'name' attribute > does not contain the correct file name. Why? > > >>> import os > >>> import tempfile > >>> fileno, name = tempfile.mkstemp(prefix='ftpd.', dir=os.getcwd()) > >>> fd = os.fdopen(fileno, 'wb') > >>> fd.name > > > Moreover, I'd like to know if I'm doing fine. Does this approach avoid > race conditions or other types of security problems? > > Thanks in advance In brief, since os.fdopen() only has access to the file descriptor, it does not have a convenient way to obtain the file's name. However, you might also want to look at the TemporaryFile and NamedTemporaryFile classes in the tempfile module -- these expose a file-like API, including a .name attribute. Assuming tempfile.mkstemp() is implemented properly, I think what you are doing should be sufficient to avoid the obvious file-creation race condition. Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From __peter__ at web.de Wed Aug 22 12:13:08 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Aug 2007 18:13:08 +0200 Subject: Eval and raw string ?? References: <1187798806.029598.264740@q3g2000prf.googlegroups.com> Message-ID: Mark wrote: > Eval() doesn't seem to recognize the r'string' format. Is there a way > around this. > Example: > If I input: ---------> eval("r'C:\tklll\ndfd\bll'") > I get the output: > > Traceback (most recent call last): > File "", line 1, in > eval("r'C:\tklll\ndfd\bll'") > File "", line 1 > r'C: klll > ^ > SyntaxError: EOL while scanning single-quoted string The string you are passing to eval already contains that newline. Use a raw string instead: >>> eval(r"r'C:\tklll\ndfd\bll'") 'C:\\tklll\\ndfd\\bll' Peter From http Wed Aug 22 02:17:38 2007 From: http (Paul Rubin) Date: 21 Aug 2007 23:17:38 -0700 Subject: for statement on empty iterable References: <1187760507.951994.50310@q4g2000prc.googlegroups.com> <7xabsk3zgm.fsf@ruckus.brouhaha.com> <1187761270.713307.224570@i38g2000prf.googlegroups.com> <7xejhw15r9.fsf@ruckus.brouhaha.com> <1187761957.636211.107060@x40g2000prg.googlegroups.com> Message-ID: <7xd4xgnldp.fsf@ruckus.brouhaha.com> james_027 writes: > Yes i am new to python :). I am sorry I should be clarify myself ... > for example > > l = ['j', 'a', 'm', 'e', 's'] > > for i in l > # i want to know the nth number of times it has loop thru or > something like counter? Oh I see. You have to combine a couple of concepts but for this example you'd say: name = 'james' # 'l' looks too much like the digit 1 for i,c in enumerate(name): print i, c print i enumerate(name) generates the sequence (0,'j'), (1,'a'), (2,'m'), (3,'e'), (4,'s') and the above loop splits those tuples into two indexes i and c. You should probably read the tutorial and work through the examples. If you get something wrong with this basic stuff, your computer won't explode or anything like that, so try stuff out. Be more careful when you start using library routines that can delete files ;). From iapain at gmail.com Fri Aug 31 12:36:52 2007 From: iapain at gmail.com (iapain) Date: Fri, 31 Aug 2007 16:36:52 -0000 Subject: So what exactly is a complex number? In-Reply-To: References: <1188576174.3479.9.camel@dot.uniqsys.com> Message-ID: <1188578212.572819.262260@l22g2000prc.googlegroups.com> > > On Thu, 2007-08-30 at 20:11 -0500, Lamonte Harris wrote: > > > Like in math where you put letters that represent numbers for place > > > holders to try to find the answer type complex numbers? You shouldnt worry about it in python, its pretty large to handle all your calc. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Aug 31 03:37:35 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 31 Aug 2007 09:37:35 +0200 Subject: list index() In-Reply-To: <1188517164.844790.109150@q4g2000prc.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <87hcmhebwv.fsf@benfinney.id.au> <1188492060.983148.90000@r34g2000hsd.googlegroups.com> <87fy20d2lt.fsf@benfinney.id.au> <1188517164.844790.109150@q4g2000prc.googlegroups.com> Message-ID: <46d7c52f$0$30706$426a74cc@news.free.fr> zzbbaadd at aol.com a ?crit : > On Aug 30, 4:28 pm, Ben Finney > wrote: >> zzbba... at aol.com writes: >>> On Aug 30, 12:09 am, Ben Finney >>> wrote: >>>> It's letting you know that the item isn't in the list. There's no >>>> sensible return value from an "index" function in that condition. >>> for str: >>> find( sub[, start[, end]]) >>> [...] >>> Return -1 if sub is not found. >>> -1 is used in other languages as well. >> It is no more sensible there than in the 'str.find' method, which is a >> historical wart. > > One man's sensible is another man's insensible. For instance, some > people feel -1 as a valid index into a list is sensible. Other's find > it insensible. Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "sensible"[-1] e >>> From indu_shreenath at yahoo.co.in Thu Aug 9 03:50:52 2007 From: indu_shreenath at yahoo.co.in (indu_shreenath at yahoo.co.in) Date: Thu, 09 Aug 2007 00:50:52 -0700 Subject: how to get output. In-Reply-To: <5hvrhhF3m15c7U1@mid.uni-berlin.de> References: <5hvrhhF3m15c7U1@mid.uni-berlin.de> Message-ID: <1186645852.687961.323420@x35g2000prf.googlegroups.com> Hey, I did write the following: but it does not work. import subprocess as sp try: = sp.Popen("DIR . /AD /B", stdout=sp.PIPE) result = p.communicate()[0] print result except: print "error" This throws error. DIR . /AD /B will list out only directories in the current directory. Thanks, Indu On Aug 9, 11:46 am, "Diez B. Roggisch" wrote: > indu_shreenath schrieb: > > > Hey, > > I want to get the output of "DIR /AD /B" command to a varriable using > > python. How can I do this? > > Using the subprocess-module. > > However, I'm not sure what DIR /AD /B does - but there are many > functions in module os that might deliver what you want without invoking > an external command. > > Diez From kyosohma at gmail.com Wed Aug 15 11:34:37 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 15 Aug 2007 08:34:37 -0700 Subject: Python Book Recommendations In-Reply-To: <1187191803.845011.30400@x35g2000prf.googlegroups.com> References: <1b31ae500708141638w77614014o6f382d0389bc69df@mail.gmail.com> <1187191803.845011.30400@x35g2000prf.googlegroups.com> Message-ID: <1187192077.005818.174440@i13g2000prf.googlegroups.com> On Aug 15, 10:30 am, Azazello wrote: > On Aug 15, 7:47 am, "Shawn Milochik" wrote: > > > If I could have only one book, I would buy "Core Python, Second > > Edition," by Wesley Chun. > > > For the record, I own: > > Core Python, Second Edition (great) > > wxPython in Action (haven't used yet) > > Beginning Python (barely used) > > Python in a Nutshell (use as a reference, although interactive python > > dir() is more useful) > > Dive into Python (great book) > > Python Cookbook (great book) > > Python Pocket Reference (not very useful) > > Python Phrasebook (I love the Phrasebook series, but this isn't a > > necessary book) > > I would like to add: > > Foundations of Python Network Programming > > I also use the Python Essential Reference. (although all of the > information is probably online it's nice to have a solid paper > reference) Depending on what you're doing, a book can actually be faster than Google! Of course, a lot of these books don't cover any 3rd party modules, so Google is still very handy. Mike From kay.schluehr at gmx.net Sat Aug 11 08:20:23 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 11 Aug 2007 05:20:23 -0700 Subject: Destruction of generator objects In-Reply-To: <20070811140017.22a11f82@cube.tz.axivion.com> References: <20070808002852.6228ae91@cube.tz.axivion.com> <1186613044.494852.306970@q75g2000hsh.googlegroups.com> <20070809011441.05d7dfb6@cube.tz.axivion.com> <1186819365.988117.232230@g4g2000hsf.googlegroups.com> <20070811121630.1b010eab@cube.tz.axivion.com> <1186831173.814193.235420@o61g2000hsh.googlegroups.com> <20070811140017.22a11f82@cube.tz.axivion.com> Message-ID: <1186834823.389706.137980@r34g2000hsd.googlegroups.com> On Aug 11, 2:00 pm, Stefan Bellon wrote: > On Sat, 11 Aug, Kay Schluehr wrote: > > Honestly, I'd recommend wrapping the generator into a function object, > > create the resource on construction ( or pass it ) and destroy it > > implementing __del__. > > > def gen_value(self): > > while True: > > yield self.iter.next() > > > class GeneratorObj(object): > > def __init__(self, obj, gen): > > self.iter = make_iter(obj) > > self.gen = gen(self) > > > def __del__(self): > > destroy(self.iter) > > > def next(self): > > return self.gen.next() > > Ok, I think there is an __iter__ missing in order to implement the > iterator protocol, and I don't see why the generator cannot be inside > the class itself. Sure. [...] > But I do not see an output of "gen del" which makes me think that the > destructor is not called, thus not releasing the resource. It seems I > have not completely understood how generators work ... But why shall the destructor be called? Your example does not indicate that a ListGenerator object is somewhere destroyed neither explicitely using del nor implicitely by destroying the scope it is living in. From pyth0nc0d3r at gmail.com Fri Aug 31 13:13:47 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Fri, 31 Aug 2007 11:13:47 -0600 Subject: So what exactly is a complex number? In-Reply-To: <1188579019.141544.292210@50g2000hsm.googlegroups.com> References: <1188576174.3479.9.camel@dot.uniqsys.com> <1188579019.141544.292210@50g2000hsm.googlegroups.com> Message-ID: >Is English your native language? I'm having a hard time decoding your question. dont be an ass.... About the complex numbers I get what they are in python now. Thanks Paul Boddie -Lamonte. On 8/31/07, Paul Boddie wrote: > > On 31 Aug, 18:12, "Chris Mellon" wrote: > > On 8/31/07, Carsten Haese wrote: > > > > > On Thu, 2007-08-30 at 20:11 -0500, Lamonte Harris wrote: > > > > Like in math where you put letters that represent numbers for place > > > > holders to try to find the answer type complex numbers? > > > > > Is English your native language? I'm having a hard time decoding your > > > question. > > > > I'm pretty sure he was describing middle school algebra. > > Yes, I imagine that the "letters that represent numbers" is intended > to refer to this: > > http://en.wikipedia.org/wiki/Elementary_algebra > > Whereas complex numbers are, of course, described here: > > http://en.wikipedia.org/wiki/Complex_number > > I hope the above resources are informative for the original inquirer. > > Paul > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Kevin.Smith at sas.com Wed Aug 15 15:55:35 2007 From: Kevin.Smith at sas.com (Kevin D. Smith) Date: Wed, 15 Aug 2007 13:55:35 -0600 Subject: Move files/directories to Recycle Bin using standard Python libs References: Message-ID: On 2007-08-15 13:02:24 -0600, "Chris Mellon" said: > Not easily. The recycle bin is part of the shell, and the shell api > calls have very complicated struct parameters that are cumbersome to > use correctly from ctypes. If you do the work to map the fileop > structs to ctypes you can call the shell API file operation functions > in shell32.dll. This assumes that "standard" for you is Python 2.5, > which has ctypes. Otherwise you are out of luck. Unfortunately, I need this to work on Python 2.4 as well... -- Kevin D. Smith From erniedude at gmail.com Mon Aug 6 19:00:10 2007 From: erniedude at gmail.com (dude) Date: Mon, 06 Aug 2007 23:00:10 -0000 Subject: maybe a popen question... or something else? Message-ID: <1186441210.383700.301790@i13g2000prf.googlegroups.com> Working on Windows XP Say I have a Windows executable, foo.exe. foo.exe is a command line tool that can take a number of different arguments and perform corresponding actions. I want to invoke foo.exe from a Python script (using whatever will work best). I want to continuously pass arguments to foo.exe in between doing other stuff from within my Python script. Some pseudo code: processHandle = invoke("foo.exe") # what python module should "invoke" be here? doUnrelatedStuff() processHandle.passArgs("arg1 arg2") # The same foo.exe I invoked above gets these args for processing doMoreUnrelatedStuff() processHandle.passArgs("arg3 arg4") # The same foo.exe I invoked above gets these args for processing processHandle.close() # "foo.exe is destroyed" Thanks for any help. From jstroud at mbi.ucla.edu Fri Aug 3 20:22:40 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 03 Aug 2007 17:22:40 -0700 Subject: How to pass a reference to the current module Message-ID: Hello All, Say I have this code: import AModule import ModuleUser ModuleUser.do_something_with(AModule, 'some_function_name') But say the functions are defined in the same module that contains the above code. I can imagine this hack: import AModule import ModuleUser ModuleUser.do_something_with(AModule.__name__, 'some_name') Where AModule.__name__ could be substituted for __name__ under the proper circumstances. Then, I would have this code in ModuleUser: import sys def do_something_with(modname, funcname): afunction = sys.modules[modname].funcname [etc.] Which is terribly ugly to me and makes for a pretty miserable API in my opinion, requiring the programmer to type underscores. Basically, what I am trying to acomplish is to be able to do this in any arbitrary module or __main__: funcname = determined_externally() ModuleUser.do_something_with(AModule, funcname) Ideally, it would be nice to leave out AModule if the functions were designed in the same namespace in which do_something_with is called. Thanks in advance for any suggestions. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From tkpmep at hotmail.com Fri Aug 17 11:02:57 2007 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: Fri, 17 Aug 2007 08:02:57 -0700 Subject: Downloading multiple csv files from a website In-Reply-To: <1187358972.458872.241790@i13g2000prf.googlegroups.com> References: <1187356117.474747.189980@g4g2000hsf.googlegroups.com> <1187358972.458872.241790@i13g2000prf.googlegroups.com> Message-ID: <1187362977.390391.49170@d55g2000hsg.googlegroups.com> Our systems administrator suggested that I try wget, a GNU utility that is designed to pick up data. It might prove to be the easiest way to get the data I want, and I am going to try that first. Thanks again. Thomas Philips From aleax at mac.com Mon Aug 27 00:05:17 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 26 Aug 2007 21:05:17 -0700 Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com> <1187898049.734696.9500@l22g2000prc.googlegroups.com> <13csi2tn49esmc3@corp.supernews.com> <13csqk47j0c56b0@corp.supernews.com> <13ct7v3qn2v5206@corp.supernews.com> <13d49lk6ue2as6d@corp.supernews.com> <13d4hutad1dq699@corp.supernews.com> Message-ID: <1i3h176.kjfosu1ly2afyN%aleax@mac.com> bambam wrote: > Is it safe to write > > A = [x for x in A if x in U] > > or is that undefined? I understand that the slice operation It's perfectly safe and well-defined, as the assignment rebinds the LHS name only AFTER the RHS list comprehension is done. Alex From steve at holdenweb.com Tue Aug 7 08:53:47 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 07 Aug 2007 08:53:47 -0400 Subject: distutils In-Reply-To: <1186489676.042901.236140@w3g2000hsg.googlegroups.com> References: <1186489676.042901.236140@w3g2000hsg.googlegroups.com> Message-ID: vedrandekovic at v-programs.com wrote: > Hello again, > > Is there any patch for python "distutils", for this > >>>> from distutils import log,dir_util > ImportError: cannot import name log > What version of Python are you running with? It looks as though there may be something wrong with your installation if it's recent: sholden at bigboy ~/Projects/Python $ python Python 2.5.1 (r251:54863, May 18 2007, 16:56:43) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> from distutils import log >>> import distutils.log >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From tim at tdw.net Sat Aug 4 12:10:31 2007 From: tim at tdw.net (Tim Williams) Date: Sat, 4 Aug 2007 17:10:31 +0100 Subject: Problems with headers in email.message In-Reply-To: References: Message-ID: <9afea2ac0708040910q5de8b667n3c7b70818d920d29@mail.gmail.com> On 04/08/07, Slippy wrote: > Hi, python newbie, struggling to learn here. I'm trying to write a > simple program which posts messages to my google group (via email). > I'm using smtplib, email and email.message to build and send a > message, but all the header attributes are appearing in the message > body, so my messages are arriving with loads of junk in the body, no > subject line and only the skinniest of headers. I know I'm doing > something wrong, but I don't know what... > > Here's a simplification of what I'm doing....essentially, I've taken > from what I've learned at > http://codeidol.com/python/python3/Client-Side-Scripting/pymail-A-Console-Based-Email-Client/ > > -------------Snip Here-------------Snip Here-------------Snip > Here------------- > import smtplib, email > from email.message import Message > m = Message( ) > m['From'] = 'Slippy ' > m['To'] = 'mygroup at googlegroups.com' > m['Subject'] = 'A Test Message' > m.set_payload('This is a test email. Please ignore') > s = smtplib.SMTP('smtp.myemail.com') > failed = > s.sendmail('user at myemail.com','mygroup at googlegroups.com',str(m)) > if failed: > print 'Message sending failed.' > else: > print 'Message sent.' > print 'Bye.' > -------------Snip Here-------------Snip Here-------------Snip > Here------------- > > Now, I get all the right responses, and the message sends ok. I go and > check my inbox, and the message is there, but the From, To and Subject > lines I created (as well as a preceding blank line and a "From nobody" > line) are in the message body, followed by the body text. > > How do I assign values to the header? > > I'd appreciate any help anyone can give me with this. Your script (as posted) works fine for me. I did need to change one import line to: from email.Message import Message (note the capitalization), but that was all - originally it stopped the script dead, so it wasn't the cause of your problem. -- Tim Williams From jcd at sdf.lonestar.org Mon Aug 27 18:23:11 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 27 Aug 2007 18:23:11 -0400 Subject: Biased random? In-Reply-To: <13d6i72s8b2a3ad@corp.supernews.com> References: <13d6i72s8b2a3ad@corp.supernews.com> Message-ID: <46D34ECF.8060106@sdf.lonestar.org> I don't know if this is pythonic or not, but try something like this: from math import log from random import randint def: skewedrandom(n): int(log(randrange(1,n), 2)) Play with your log to get the range you want Cheers, Cliff Grant Edwards wrote: > On 2007-08-27, Jun-geun Park wrote: > > >>> I have a list of items, and need to choose several elements >>> from it, "almost random". The catch is that the elements from >>> the beginning should have more chance of being selected than >>> those at the end (how much more? I don't care how the >>> "envelope" of probability looks like at this point - can be >>> linear). I see that there are several functions in Python >>> standard libraries for various distribution, but is there an >>> easy pythonic way to make them do what I need? >>> > > >> That's weird. random.randint(a,b) will be enough for most >> cases. Test your system to see the distribution is uniform >> with something like: >> > > Except he wants a non-uniform distribution. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From SMERSH009X at gmail.com Fri Aug 3 22:22:35 2007 From: SMERSH009X at gmail.com (SMERSH009) Date: Sat, 04 Aug 2007 02:22:35 -0000 Subject: Email In-Reply-To: <1186159660.264082.91830@j4g2000prf.googlegroups.com> References: <1186076005.729346.327140@z24g2000prh.googlegroups.com> <46b2393f$0$27409$ba4acef3@news.orange.fr> <1186159660.264082.91830@j4g2000prf.googlegroups.com> Message-ID: <1186194155.560881.183790@e16g2000pri.googlegroups.com> On Aug 3, 9:47 am, Rohan wrote: > On Aug 2, 1:06 pm, Laurent Pointal wrote: > > > > > Rohan wrote: > > > I was wondering if there could be an arrangement where a file could be > > > attached and send as an email. > > > For ex > > > f = open(add.txt,w) > > > f.write('python') > > > f.close() > > > > Now I would like to send an email with add.txt as an attachment, is it > > > possible ? > > > some one give me a pointer towards this. > > > You can use iMailer as an example script to get parts: > > >http://nojhan.free.fr/article.php3?id_article=22 > > > A+ > > > Laurent. > > Laurent the link you gave me is in a language unknown to me if you > have anything that expalains in english, then let me know. > thanks Did you try Google translate? Here is the tiny url of the page you wanted translated http://tinyurl.com/3xlcmc From theller at ctypes.org Wed Aug 15 13:21:23 2007 From: theller at ctypes.org (Thomas Heller) Date: Wed, 15 Aug 2007 19:21:23 +0200 Subject: ming on win32 anyone ? [help a noob] In-Reply-To: <%QCwi.14541$rr5.1213@newsfe1-win.ntli.net> References: <%QCwi.14541$rr5.1213@newsfe1-win.ntli.net> Message-ID: daz.diamond schrieb: > hoping someone can help ... > > how do I install ming (with python) on win32? have downloaded the > tar.gz of ming-0.3.0 which doesn't have a handy self-installer, and > I'm absolutely foxed as to what to do next ... the install > instructions in the package seem to be linux oriented, which to me > may as well be in greek > > any clues much appreciated, thx > > daz Maybe you want this one: http://www.develer.com/oss/GccWinBinaries Quote from that page: """ Unofficial MinGW GCC binaries for Windows This page contains a friendly installer for GCC 4.1.2 for Windows (native "mingw" win32 version). It's an unofficial release, not promoted by the MinGW project. It features full Python integration. """ From gnewsg at gmail.com Fri Aug 24 04:26:05 2007 From: gnewsg at gmail.com (billiejoex) Date: Fri, 24 Aug 2007 01:26:05 -0700 Subject: tarfile module for version 2.2.3 In-Reply-To: References: Message-ID: <1187943965.116322.307790@x35g2000prf.googlegroups.com> On 24 Ago, 09:57, Antoon Pardon wrote: > I have to write a little program that has to run on a number of hosts. > Versions of python range from 2.2.3. to 2.4.2. > > The easiest way to implement the necessary behaviour seems to me to > use the tarfile module. However that was only introduced in 2.3 > I had a look in the code and at first sight couldn't find anything > that would cause problems if I used this module with python 2.2.3. > > Could someone confirm that the tarmodule is compatible with python 2.2. > I will try some tests myself but it would be nice to have confirmation > from elsewhere. > > -- > Antoon Pardon Try also the test suite (Lib/test/test_tarfile.py). From nicksavill at googlemail.com Tue Aug 28 05:02:35 2007 From: nicksavill at googlemail.com (nicksavill at googlemail.com) Date: Tue, 28 Aug 2007 09:02:35 -0000 Subject: sorting a list of lists In-Reply-To: <1188233798.684136.263640@22g2000hsm.googlegroups.com> References: <1188233798.684136.263640@22g2000hsm.googlegroups.com> Message-ID: <1188291755.083433.50610@d55g2000hsg.googlegroups.com> Thanks guys, "dirty hack" was what I needed to get a job done quickly. Nick From ldo at geek-central.gen.new_zealand Sat Aug 18 00:48:14 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 18 Aug 2007 16:48:14 +1200 Subject: encrypting files + filestreams? References: <1187186797.579680.206820@19g2000hsx.googlegroups.com> Message-ID: In message <1187186797.579680.206820 at 19g2000hsx.googlegroups.com>, per9000 wrote: > crptz = AES.new("my-secret_passwd") You're using ECB mode. Never use ECB mode. At a minimum, use CBC mode. Also, another common thing is, don't use the actual password to encrypt the entire file. Instead, randomly generate a "session key" to use for the actual encryption, and only use the password to encrypt that. > def encrypt2(cryptor, infile, outfile): > """enly encrypt a few bytes at a time""" > > size = 512 > bytes = infile.read(size) > > seek = 0 > interval = 97 > ctr = 0 > > while len(bytes) == size: > seek += size > if ctr % interval == 0: > print '\r%15d bytes completed' % (seek), > ctr += 1 > > outfile.write(cryptor.encrypt(bytes)) > # change to this to decrypt > # outfile.write(cryptor.decrypt(bytes)) > bytes = infile.read(size) > > if len(bytes) != 0: > bytes += "#" * (size - len(bytes)) > outfile.write(cryptor.encrypt(bytes)) > seek += len(bytes) Finally, it is recommended that you also compute and encrypt a cryptographic hash of the plaintext. That way, you can check that still matches after decryption, to guard against tampering. From gherron at islandtraining.com Wed Aug 1 23:50:53 2007 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 01 Aug 2007 20:50:53 -0700 Subject: sending very large packets over the network In-Reply-To: <9c8d48280708011555l5d1d439fu3c5fbcc61dc41f07@mail.gmail.com> References: <9c8d48280708011555l5d1d439fu3c5fbcc61dc41f07@mail.gmail.com> Message-ID: <46B1549D.3040108@islandtraining.com> Walker Lindley wrote: > OK, I'm back with another networking question. I'm trying to seend > large amounts of information over TCP (the length of data being given > to send() is on the order of 16000 characters in length). > Unfortunately on the receiving end, the packets appear to be > truncated. So I wrote some code that continuously tries to send bigger > and bigger packets until it fails and noticed that it never fails at > the same length. I'm not even sure these two things are related, but > is there some undocumented (or documented and I missed it) maximum > size for data you can pass to send()? For ethernet connections the size is often about 1500. But the size depends on the underlying protocol, and even if you know the underlying protocol along the full route, you can't rely on packets that are received being the same as those that are sent. TCP/IP is a *stream* connection. What you are guaranteed is this: All the bytes that are sent from one end will be received eventually on the other end, in the proper order. (Or failing that, you will receive an error notification.) No guarantee is made about the packet sizes on either end, and you can't even rely on the packets being the same in number or length on the two ends. Your send code can try sending a packet of any size, but it must be prepared to examine the number of bytes actually sent, and retry with the remainder in a loop until all bytes are sent. Similarly your receiving code must loop around the receive accepting whatever sized packets makes it through the connection. In many TCP/IP connections, it seems that the packets received are one-for-one with the packets sent, but relying on this *IS AN ERROR* that will bite you. It fails to across the internet (sometimes) and when (at least some) wireless cards are involved. You may be better off using a package that knows all this and handles it properly. Modules asyncore and asynchat are one possibility. Gary Herron > > the sample code is as follows > #server > import socket > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.bind(("", 2000)) > s.listen(0) > sock, addrinfo = s.accept() > for i in range(2 ** 16): > length = int(sock.recv(16)) > print "excpecting data of length:", length > data = sock.recv(length) > print "received data of length:", len(data) > print > s.close() > sock.close() > > #client > import socket > import time > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.bind(("", 2001)) > s.connect(("localhost", 2000)) > for i in range(2 ** 16): > packet = "h" * i > s.send("%16d" % len(packet)) > print "attempting to send data of length:", len(packet) > tmp = s.send(packet) > print "actually sent data of length:", tmp > print > time.sleep(.001) > s.close() > > i just put them in different files and ran them from the command line. > Any help or suggestions would be greatly appreciated. Thanks. > > > -Walker > > -- > This e-mail is licensed under the Creative Commons > Attribution-NoDerivs 2.5 License. To view a copy of this license, > visit http://creativecommons.org/licenses/by-nd/2.5/ or send a letter > to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, > California, 94105, USA. From kyosohma at gmail.com Fri Aug 31 17:28:43 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 31 Aug 2007 14:28:43 -0700 Subject: Is there a simple way to exit a while loop on keystroke? In-Reply-To: <1188593722.696576.12390@y42g2000hsy.googlegroups.com> References: <1188578827.809840.90100@r29g2000hsg.googlegroups.com> <1188581623.588967.78050@z24g2000prh.googlegroups.com> <1188583918.747640.300850@22g2000hsm.googlegroups.com> <1188593722.696576.12390@y42g2000hsy.googlegroups.com> Message-ID: <1188595723.878736.186900@w3g2000hsg.googlegroups.com> On Aug 31, 3:55 pm, Arnaud Delobelle wrote: > On Aug 31, 7:11 pm, gsxg wrote: > > > Thanks, > > The curses library doesn't look to helpful to me. > > And yet it is. > > -- > Arnaud Maybe the OP is on Windows. The docs seem to indicate that the curses module isn't for Windows (see excerpt below): While curses is most widely used in the Unix environment, versions are available for DOS, OS/2, and possibly other systems as well. This extension module is designed to match the API of ncurses, an open- source curses library hosted on Linux and the BSD variants of Unix. See also: http://docs.python.org/lib/module-curses.html Oddly enough, I have it in my Windows distro, so it's rather confusing. I've never used it, so I don't know if it plays nice on Windows or not. Mike From deets at nospam.web.de Sat Aug 18 18:49:29 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 19 Aug 2007 00:49:29 +0200 Subject: Symbolic Link In-Reply-To: <1187475296.173269.263080@k79g2000hse.googlegroups.com> References: <1187475296.173269.263080@k79g2000hse.googlegroups.com> Message-ID: <5ipbc3F3q94rmU1@mid.uni-berlin.de> mosscliffe schrieb: > I am trying to create a link to a file, which I can then use in an > HTML page. > > The system is Linux on a hosted web service, running python 2.3. > Other than that I have no knowledge of the system. > > The link is created OK, but when I try to use it as filename for the > IMG TAG, it does not get displayed. The page source of the created > page is pointing to the link as temp/test1.jpg > > Any ideas ? > > srcFile = "temp/test2.jpg" > > linkFile = "temp/test1.jpg" > > if os.path.islink(linkFile): > print "Link Exists", nl > pass > else: > print "Making Link", nl > os.symlink(srcFile, linkFile) > > print '
the image

' % linkFile > > print 'the image' % srcFile In what environment is that script running? If it's apache, it might be that the apache settings disallow for following links. Diez From steve at REMOVE.THIS.cybersource.com.au Fri Aug 3 21:52:30 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 04 Aug 2007 11:52:30 +1000 Subject: How to pass a reference to the current module References: Message-ID: On Fri, 03 Aug 2007 18:32:54 -0700, James Stroud wrote: > Carsten Haese wrote: >> This seems to confirm my suspicion that the do_something_with function >> doesn't actually need a reference to the module, it only needs a >> reference to the function to call. >> >> Maybe your hurdle is how to obtain a reference to a function from the >> current module when all you have is the name of the function in a >> string. The answer to that would be "globals()[funcname]". > > This is like a bad case of phone-tag. Please see my response to your > previous post for why this does not seem feasible to me. I've read your previous post, and I don't understand why you consider it unfeasible. The user provides a function name in a config file, which gives you funcname as a string. You already know which module it comes from (you didn't specify how, but all your examples show that). Carsten is simply showing you how to get the function from the function name without the nasty hack using sys._getframe. Why is in unfeasible? -- Steven. From bj_666 at gmx.net Mon Aug 27 11:41:55 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Aug 2007 15:41:55 GMT Subject: How to free memory ( ie garbage collect) at run time with Python 2.5.1(windows) References: <1188224306.863247.127890@50g2000hsm.googlegroups.com> Message-ID: <5jg9m3F3snbajU1@mid.uni-berlin.de> On Mon, 27 Aug 2007 07:18:26 -0700, rfv-370 wrote: > have made the following small test: > > Before starting my test my UsedPhysicalMemory(PF): 555Mb > >>>>tf=range(0,10000000) PF: 710Mb ( so 155Mb for my List) >>>> tf=[0,1,2,3,4,5] PF: 672Mb (Why? Why the remaining 117Mb is not freed?) >>>> del tf PF: 672Mb (unused memory not freed) > > So changing the list contents and/or deleting the list changes > nothing...from a memory point of view. >From the OS memory point of view to be precise. Although here the integer cache applies as Alex pointed out, in the general case memory might be kept allocated by Python to be re-used later. The Python allocator is better suited for frequent allocation and deallocation of many small objects than `malloc()` from the C standard library is. And even a `free()` in the C standard library doesn't guarantee that memory is given back to the OS and reported as free memory again. Ciao, Marc 'BlackJack' Rintsch From nagle at animats.com Wed Aug 1 01:08:50 2007 From: nagle at animats.com (John Nagle) Date: Wed, 01 Aug 2007 05:08:50 GMT Subject: Scipy and Mcafee Site Advisor? In-Reply-To: References: Message-ID: David Lees wrote: > I know scipy.org is legit and supplies widely used and useful python > packages. Can someone explain why my McAfee SiteAdvisor software, flags > scipy.org as a dangerous site? Pardon my ignorance, but is this a > temporary error in the SiteAdvisor database or is there some privacy > consideration involved? I am wondering if I should remove the > SiteAdvisor software, because it is not particularly reliable. > > Puzzled. > > david lees SiteAdvisor says: (http://www.siteadvisor.com/sites/scipy.org) "After entering our e-mail address on this site, we received 81 e-mails per week. We received 2 e-mails which contained a virus." The scipy list maintainer says they're going to add virus scanning to the mailing list, which should, in time, get the site a better rating. John Nagle From cjw at sympatico.ca Tue Aug 21 13:59:11 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 21 Aug 2007 13:59:11 -0400 Subject: Regarding Classes In-Reply-To: References: Message-ID: Lamonte Harris wrote: > What is the main reason of "self" when it involves classes/functions > "self" provides a semi-standard way of addressing the current instance of a class. It is used in an instance's method. It is not typically used in functions. Colin W. From splifingate at gmail.com Wed Aug 1 20:47:03 2007 From: splifingate at gmail.com (ah) Date: Wed, 01 Aug 2007 20:47:03 -0400 Subject: What does this thread have to do with classical music, In-Reply-To: <290720071853200863%erfc@caballista.org> References: <7nnh7350b5h25ghocra72b23mmsnnkj8bh@4ax.com> <468e2d68$0$4831$8f2e0ebb@news.shared-secrets.com> <468e482b$0$97236$892e7fe2@authen.yellow.readfreenews.net> <4692df4a$0$4804$8f2e0ebb@news.shared-secrets.com> <469392cd$0$97226$892e7fe2@authen.yellow.readfreenews.net> <469445b3$0$4819$8f2e0ebb@news.shared-secrets.com> <4694e124$0$97214$892e7fe2@authen.yellow.readfreenews.net> <46957ef1$0$10227$8f2e0ebb@news.shared-secrets.com> <46963170$0$97261$892e7fe2@authen.yellow.readfreenews.net> <46981df7$0$12095$8f2e0ebb@news.shared-secrets.com> <46990784$0$97223$892e7fe2@authen.yellow.readfreenews.net> <4699297c$0$4706$4c368faf@roadrunner.com> <140720071431044860%erfc@caballista.org> <46a3a1a7$0$15115$8f2e0ebb@news.shared-secrets.com> <220720072148091069%erfc@caballista.org> <46a5385d$0$4832$8f2e0ebb@news.shared-secrets.com> <250720071834457296%erfc@caballista.org> <46aceaa5$0$13281$8f2e0ebb@news.shared-secrets.com> <290720071853200863%erfc@caballista.org> Message-ID: <46b12539$0$4807$8f2e0ebb@news.shared-secrets.com> Art Deco wrote: > ah wrote: >>Art Deco wrote: >>> ah wrote: >>>>Art Deco wrote: >>>>> ah wrote: >>>>>>Art Deco wrote: >>>>>>> Who wrote? >>>>>>> >>>>>>> >>>>>>>>What does that have to do with classical music, snuhwolf? >>>>>>> >>>>>>>>What does that have to do with classical music, snuhwolf? >>>>>>> >>>>>>> How many more times will you be asking the same tired, lame questions, >>>>>>> Tholen? >>>>>> >>>>>>Till 2056? >>>>> >>>>> At that point, he will have made the Thirty Years Pset War look like >>>>> 1967 in the Sinai. >>>> >>>>It must have been Hell to keep a garden during those times. >>>> >>>>Did they all eat jerky, or what? >>> >>> Worse -- worm-laden hardtack. >> >>Luxury! >> >>Why, I remember when I was a lad . . . we used to watch the local churls >>across the fences eating that well. >> >>We only had millings (and (occasionally) water) on Tuesdays and Fridays. > > Grog and hardtack, life is good! ?Viva la basura! From arnodel at googlemail.com Thu Aug 30 15:52:59 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 30 Aug 2007 19:52:59 -0000 Subject: subclassing Python types In-Reply-To: References: <1188500442.434722.157350@q5g2000prf.googlegroups.com> <46d717f5$0$30367$9b4e6d93@newsspool4.arcor-online.net> <1188501865.541186.272290@e9g2000prf.googlegroups.com> Message-ID: <1188503579.357874.275870@l22g2000prc.googlegroups.com> On Aug 30, 8:44 pm, Robert Kern wrote: > zzbba... at aol.com wrote: > > So it's: > > class MyString(str): > > def __init__(self,strInput): > > self = strInput > > That doesn't quite work. Assigning to "self" only reassigns the name inside the > function. It does not replace the object. > > Instead, call the .__init__() method on str. That won't do much as strings are immutable objects... As pointed out by Steve Holden and me, str.__new__ is the way. -- Arnaud From NO_Kroeger at gmx.de Wed Aug 22 14:46:26 2007 From: NO_Kroeger at gmx.de (=?ISO-8859-1?Q?Nils_Oliver_Kr=F6ger?=) Date: Wed, 22 Aug 2007 20:46:26 +0200 Subject: Class destruction In-Reply-To: <496954360708221117pd7465fr838a24b167a1dcdd@mail.gmail.com> References: <496954360708221117pd7465fr838a24b167a1dcdd@mail.gmail.com> Message-ID: <46CC8482.9040100@gmx.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Robert Dailey schrieb: > Hi, > > I'm wondering where the most appropriate location is to cleanup class > objects. For example, i have a file handle as an instance attribute in one > of my classes and I need to call f.close() on it when the class object falls > out of scope. Any ideas? I've tried __del__() but I don't remember this > working for some reason. I might try it again later just to be positive. __del__(self) is the perfectly right place for such cleanup ... it gets called once your instance is either deleted explicitly by you or it's handled by the garbage collector when there are no more references. The possible problem why this did not work four you is, that the destruction by the garbage collector cannot be predicted ... it may well take some time. If you try to open the same file from another class before yours gets cleaned you run into trouble. If you want to "reuse" the file, you will have to delete your classes instance explicitly using the del statement ... this will also call the destructor. The below code works fine: def __del__( self ): self._file.close() print "File closed" Hope that helps ... Nils -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGzISBzvGJy8WEGTcRAiOwAJ94fJza4/GVQsFmbXwsP8kdvQjV5wCfQktw F/zPJAw0ayjYe5MGxPR1YqI= =4Hl6 -----END PGP SIGNATURE----- From edloper at gradient.cis.upenn.edu Thu Aug 9 01:40:38 2007 From: edloper at gradient.cis.upenn.edu (Edward Loper) Date: Thu, 09 Aug 2007 00:40:38 -0500 Subject: mmm-mode, python-mode and doctest-mode? Message-ID: <46BAA8D6.1050402@gradient.cis.upenn.edu> > Anyone testing on xemacs? I tried it, and C-c C-c sent xemacs into an > infinite loop (apparantly). It works fine for me in XEmacs 21.4 (patch 17) (i386-debian-linux, Mule). If you could answer a few questions, it might help me track down the problem: - What version of xemacs are you running? - What version of doctest-mode are you running (0.4 or 0.5)? - Are you using doctest-mode by itself, or in combination with another mode (via mmm-mode)? - Does pressing control-g (possibly repeatedly) cause it to become unstuck? - Does it always freeze when you hit C-c C-c? Or does it depend on the contents of the buffer? Does it freeze if you run it in an empty buffer? You could try changing the value of doctest-python-command, to see if that helps -- "M-x customize-variable doctest-python-command". Set it to the full path to a Python interpreter. Thanks, -Edward From duncan.booth at invalid.invalid Mon Aug 13 07:32:34 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Aug 2007 11:32:34 GMT Subject: decorators - more than just syntactic sugar References: <46be005e$0$13866$ba620e4c@news.skynet.be> Message-ID: "BJ?rn Lindqvist" wrote: > On 8/11/07, Helmut Jarausch wrote: >> How can I find out the predefined decorators? > > There are two in the standard library, @classmethod for declaring > class methods and @staticmethod for declaring static methods. They are > listed at the built ins page > http://docs.python.org/dev/lib/built-in-funcs.html, unpedagogically > not separated from ordinary functions. > > There are at least two other decorators in the standard library: functools.wraps contextlib.contextmanager From jjl at pobox.com Sun Aug 5 13:52:28 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 05 Aug 2007 17:52:28 GMT Subject: Misleading wikipedia article on Python 3? Message-ID: <87bqdlswbn.fsf@pobox.com> I'm surprised to read this: http://en.wikipedia.org/wiki/Python_3 """Note that while there is no explicit requirement that code be able to run unmodified in both versions, in practice it is quite likely for most code. As of January 2007, it looks like most reasonable code should run quite well under either branch.""" I haven't been following Python 3 development recently. Have things really changed that much? Last time I looked, e.g. dict.items() no longer returned a list. Seems unlikely that most code will run on 2 and 3, in that case, and IIUC Guido has said all along that not much code will run on both. Maybe somebody who's following current Py3k goings-on can fix the article if needed... John From guido at python.org Fri Aug 31 13:17:05 2007 From: guido at python.org (Guido van Rossum) Date: Fri, 31 Aug 2007 10:17:05 -0700 Subject: Python 3000 released as 3.0a1 Message-ID: [Bcc: python-list at python.org] The first Python 3000 release is out -- Python 3.0a1. Be the first one on your block to download it! http://python.org/download/releases/3.0/ Excerpts: Python 3000 (a.k.a. "Py3k", and released as Python 3.0) is a new version of the language that is incompatible with the 2.x line of releases. The language is mostly the same, but many details, especially how built-in objects like dictionaries and strings work, have changed considerably, and a lot of deprecated features have finally been removed. This is an ongoing project; the cleanup isn't expected to be complete until 2008. In particular there are plans to reorganize the standard library namespace. The release plan is to have a series of alpha releases in 2007, beta releases in 2008, and a final release in August 2008. The alpha releases are primarily aimed at developers who want a sneak peek at the new langauge, especially those folks who plan to port their code to Python 3000. The hope is that by the time of the final release, many 3rd party packages will already be available in a 3.0-compatible form. More links: * Online docs: http://docs.python.org/dev/3.0/ * What's new: http://docs.python.org/dev/3.0/whatsnew/3.0.html * Source tar ball: http://python.org/ftp/python/3.0/Python-3.0a1.tgz * Windows MSI installer: http://python.org/ftp/python/3.0/python-3.0a1.msi * PEP 3000: http://python.org/dev/peps/pep-3000/ * Issue tracker: http://bugs.python.org/ * Py3k dev list: http://mail.python.org/mailman/listinfo/python-3000/ * Conversion tool for Python 2.x code: http://svn.python.org/view/sandbox/trunk/2to3/ -- --Guido van Rossum (home page: http://www.python.org/~guido/) From rozelles at btinternet.com Mon Aug 6 09:21:07 2007 From: rozelles at btinternet.com (Lincoln Rozelle) Date: Mon, 6 Aug 2007 14:21:07 +0100 Subject: I need help speeding up an app that reads football scores andgenerates rankings Message-ID: <2D88C16C-D4A3-44F6-8BFE-6ECE19FEBDA3@btinternet.com> Hey Terry I got your name from the following page: http://mail.python.org/pipermail/python-list/2007-May/438521.html I'm interested in producing a web-app for football games that runs in python. When I talk about football, since I'm in Europe though, I mean soccer. Which football do you mean? Lincoln Lincoln Rozelle 0131 221 9954 0781 313 2537 rozelles at btinternet.com http://www.ilkindustries.com This e-mail and any files transmitted with it are strictly confidential and intended only for use by the addressee/s unless otherwise indicated. If you are not the intended recipient any use, dissemination printing or copying is strictly prohibited and an infringement of copyright. If you have received this e-mail in error, please let us know. http://www.linkedin.com/pub/2/210/206 -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Wed Aug 15 13:42:37 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 15 Aug 2007 10:42:37 -0700 Subject: Move files/directories to Recycle Bin using standard Python libs In-Reply-To: References: Message-ID: <1187199757.774573.48940@q4g2000prc.googlegroups.com> On Aug 15, 11:39 am, Kevin D. Smith wrote: > I would like to move files and directories to the Recycle Bin on > Windows from Python. I have found some older articles describing how > to do this, but they require additional packages to be installed. I'm > working on a plugin for an existing project and only have the standard > library to work with. Is there a way to use the Recycle Bin using > standard Python? > > -- > Kevin D. Smith Sounds like a Windows only thing to me, so you'll probably have to use the win32 package regardless. See the following links: http://mail.python.org/pipermail/python-list/2004-October/287638.html http://tgolden.sc.sabren.com/python/win32_how_do_i/copy-a-file.html Mike From olsongt at verizon.net Sat Aug 11 15:53:10 2007 From: olsongt at verizon.net (Grant Olson) Date: Sat, 11 Aug 2007 15:53:10 -0400 Subject: ANN: Compyler 0.1 Message-ID: <000601c7dc51$3f0bfb40$ac01a8c0@johnyaya> Compyler is a pre-alpha x86 native code compiler. So far it can generate primitive .pyds but not standalone executables. It can run some simple test cases including pystones (although there is a memory leak there). And no, I don't expect it'll ever be much faster than Cpython . I was primarily interested in being able to distribute low-footprint standalone executables written in python and code obfustication. The basic approach taken by compyler is to transliterate python bytecode into x86 assembly, instead of trying to generate assembly from the syntax tree. This is basically abandonware. I haven't touched this in six months, but did do a lot of up front work. I basically wanted to release it before my hardrive blows up in case anyone was looking for prior art. The code also contains a version of pyasm that has some more patches and features than the official distribution if you're one of pyasm's 3 users. More info can be found at: http://members.verizon.net/~olsongt/compyler/index.html -Grant From dfabrizio51 at gmail.com Fri Aug 17 13:04:22 2007 From: dfabrizio51 at gmail.com (chewie54) Date: Fri, 17 Aug 2007 17:04:22 -0000 Subject: best GUI library for vector drawing program In-Reply-To: References: <1187357244.883516.79840@j4g2000prf.googlegroups.com> Message-ID: <1187370262.861439.259680@q3g2000prf.googlegroups.com> On Aug 17, 12:08 pm, Jeremy Sanders wrote: > chewie54 wrote: > > What would be the best cross-platform GUI library to use for a vector > > based CAD program ( something like Visio on Windows ) WxWidgets, > > Tk, PyQt, Java Swing, Java SWT,???? I need the capibility to > > draw and edit in a window that looks like a page of paper so WYSIWYG > > is very important, and I need to save the drawings in vector based > > file formats like PS, EPS, SVG, as well as image formats like jpg, > > png, and gif. Also, the images need to be high resolution so that > > they can be pasted into various other programs in Windows OS, and > > Linux OS, and the Mac OS. > > PyQt/Qt4 is capable of that (SVG export was added in Qt4.3). > > I have a graph drawing application based around it (Veusz). > > If you base everything around QPainter, you'll be able to write to any of > those output formats (including eps and pdf), and bitmaps. Antialiasing is > optional for bitmap formats. > > Jeremy > > -- > Jeremy Sandershttp://www.jeremysanders.net/ Jeremy, I looked at your application, Veusz (it looks very nice), and I see you have binary distrubitions for each os. Is is difficult to build these binaries for each system. Could you tell me how that is done? Thanks, Dan From arkanes at gmail.com Wed Aug 1 10:41:58 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 1 Aug 2007 09:41:58 -0500 Subject: wxPython version question In-Reply-To: <1185970526.612299.277930@o61g2000hsh.googlegroups.com> References: <1185970526.612299.277930@o61g2000hsh.googlegroups.com> Message-ID: <4866bea60708010741j75e8fa9cve0ac201d848368ea@mail.gmail.com> On 8/1/07, The Max wrote: > Hi at all > > > Hi have need of testing the version of wxPython in use .... at the > moment I use wxversion, but I don't can find a method for testing > version like this: > > if versionOfWX() <= 2.8: > > or > > if versionOfWX() >= 2.8: > > ( versioneOfWX is a pseudo-function create for this example ) > > > > Someone know a solution for this ? > > > > Thanks and sorry for my orrible english > > -- > http://mail.python.org/mailman/listinfo/python-list > help(wxversion) describes in some detail all the methods you need. From steve at holdenweb.com Fri Aug 31 15:30:20 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 31 Aug 2007 15:30:20 -0400 Subject: So what exactly is a complex number? In-Reply-To: <1188585591.3479.34.camel@dot.uniqsys.com> References: <1188576174.3479.9.camel@dot.uniqsys.com> <1188579019.141544.292210@50g2000hsm.googlegroups.com> <1188585591.3479.34.camel@dot.uniqsys.com> Message-ID: Carsten Haese wrote: > On Fri, 2007-08-31 at 11:13 -0600, Lamonte Harris wrote: >>> Is English your native language? I'm having a hard time decoding your >> question. >> dont be an ass.... > > I'm sorry you took it this way. I was only trying to help. It won't > happen again. > For what it's worth, I too had difficulty parsing "Like in math where you put letters that represent numbers for place holders to try to find the answer type complex numbers?", so I suppose I must be an ass too. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From danb_83 at yahoo.com Sat Aug 4 00:05:00 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Fri, 03 Aug 2007 21:05:00 -0700 Subject: bias in random.normalvariate?? In-Reply-To: <1186198720.800007.38800@k79g2000hse.googlegroups.com> References: <1186198720.800007.38800@k79g2000hse.googlegroups.com> Message-ID: <1186200300.903625.317200@x40g2000prg.googlegroups.com> On Aug 3, 10:38 pm, drewl... at gmail.com wrote: > I'm a Python newbie and certainly no expert on statistics, but my wife > was taking a statistics course this summer and to illustrate that > sampling random numbers from a distribution and taking an average of > the samples gives you a random number as the result (bigger sample -> > smaller variance in the calculated random number, converging in on the > mean of the original distribution), I threw together this program: > ... > > I added the lo and high stuff to my test program out of fear that I > was running into something funky in adding up 100 floating point > numbers. That would be more of a worry if the sample size was much > bigger, but lo and high showed apparent bias quite aside from the > calculation of the mean. > > Am I committing some other obvious statistical or Python blunder? > e.g. Am I mis-understanding what random.normalvariate is supposed to > do? Doing some testing with mu=0, sigma=1, and n=1000000 gives me means of -0.00096407536711885962 -0.0015179019121429708 +6.9223244807378563e-05 +0.0017483897464631625 -0.0011148444018505548 +0.0015367250480148183 There appears to be no consistent bias. From steven.bethard at gmail.com Fri Aug 31 13:09:54 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 31 Aug 2007 11:09:54 -0600 Subject: reload(sys) In-Reply-To: <1188564816.430863.219560@w3g2000hsg.googlegroups.com> References: <1188521143.421431.119100@l22g2000prc.googlegroups.com> <1188564816.430863.219560@w3g2000hsg.googlegroups.com> Message-ID: S?nmez Kartal wrote: > On 31 A ustos, 04:24, Steven Bethard wrote: >> S?nmez Kartal wrote: >>> I've had an encoding issue and solved it by >>> "sys.setdefaultencoding('utf-8')"... >>> My first try wasn't successful since setdefaultencoding is not named >>> when I imported sys module. After, I import sys module, I needed to >>> write "reload(sys)" also. >>> I wonder why we need to call "reload(sys)" to get setdefaultencoding >>> named? >> sys.setdefaultencoding is purposely deleted from the sys module after >> it's loaded because you really shouldn't be using it. The reload() call >> restores the deleted attribute. >> >> If you'd like a less brittle solution to your encoding issue, explain >> what the issue was, and people here can probably help you find a better >> solution. >> >> STeVe > > I was using the XMLBuilder(xmlbuilder.py). I'm writing XML files as > "f.write(str(xml))". At execution of that line, it gives error with > description, configure your default encoding... Could you post the actual traceback you're getting? STeVe From jefishman at gmail.com Mon Aug 6 16:14:39 2007 From: jefishman at gmail.com (anethema) Date: Mon, 06 Aug 2007 13:14:39 -0700 Subject: udp, datagram sockets In-Reply-To: References: <1186416225.769753.307110@o61g2000hsh.googlegroups.com> Message-ID: <1186431279.714122.316530@j4g2000prf.googlegroups.com> On Aug 6, 1:27 pm, Carsten Haese wrote: > On Mon, 2007-08-06 at 09:03 -0700, 7stud wrote: > > server: > > ------------------ > > import socket > > import sys > > > s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > > s.bind(("", 7777)) > > [...] > > #Send messages back to client: > > total_sent = 0 > > while total_sent < len(message): > > print "debug: send while loop" > > > size_sent = s.sendto(message[total_sent:], ("localhost", > > 7777) ) > > total_sent += size_sent > > > print "debug:", total_sent, len(message) > > I don't think that sending the datagram to port 7777 on localhost sends > the message back to the client. I'm guessing the server is sending the > message back to itself, which throws it into the infinite feedback loop > you're experiencing. > > HTH, > > -- > Carsten Haesehttp://informixdb.sourceforge.net Yes, you want to use the socket.recvfrom() method, store the address, and send the response to that address. Your code is indeed repeatedly sending itself the received message. You want to change > > data = s.recv(1024) to data, recv_addr = s.recvfrom(1024) and > > size_sent = s.sendto(message[total_sent:], ("localhost", > > 7777) ) to size_sent = s.sendto(message[total_sent:], recv_addr) However, your client closes immediately after sending all its data, so it will never receive that message. From python at jayloden.com Wed Aug 1 00:22:29 2007 From: python at jayloden.com (Jay Loden) Date: Wed, 01 Aug 2007 00:22:29 -0400 Subject: Any way to monitor windows network connection? In-Reply-To: <1185939997.135825.310080@z24g2000prh.googlegroups.com> References: <1185939997.135825.310080@z24g2000prh.googlegroups.com> Message-ID: <46B00A85.4030004@jayloden.com> momobear wrote: > hi, Is there any way to show me detailed listings of all TCP and UDP > endpoints in my microsoft windows XP in python way? > thanks. Not sure if it's exactly what you're looking for, but this might be of use as a starting point at least: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/392572 From bbxx789_05ss at yahoo.com Thu Aug 9 05:16:52 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 09 Aug 2007 02:16:52 -0700 Subject: wxPython before MainLoop In-Reply-To: <13bl9a75laqcm70@corp.supernews.com> References: <13bl9a75laqcm70@corp.supernews.com> Message-ID: <1186651012.889801.320910@q75g2000hsh.googlegroups.com> I reorganized my Thread class a little bit: ------------ class MyThread(threading.Thread): def __init__(self, a_frame): threading.Thread.__init__(self) self.frame_obj = a_frame def run(self): result = self.long_slow_init() wx.CallAfter(self.frame_obj.receive_result, result) #CallAfter() calls the specified function with the specified argument #when the next pause in execution occurs in this thread. def long_slow_init(self): print "starting long_slow_init()..." time.sleep(6) result = 20.5 return result -------------- From gigs at hi.t-com.hr Wed Aug 29 17:11:53 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Wed, 29 Aug 2007 23:11:53 +0200 Subject: cgi In-Reply-To: References: <46d5c01b$0$36438$4fafbaef@reader5.news.tin.it> <46d5daa7$0$36441$4fafbaef@reader5.news.tin.it> Message-ID: Gigs_ wrote: > Fabio Z Tessitore wrote: >> Are you sure your script is in the right dir? >> >> On my home computer, php script will work in /var/www but my python >> script need an other dir to work properly (i don't remember which now >> ;-)) >> >> bye >> > i think that it is in right dir because other script in same dir work. > dir is: cgi-bin sorry................... for waisting your time, somehow in html page in form i forgot to put right script addr thx anyway work now From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Aug 13 04:09:54 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 13 Aug 2007 10:09:54 +0200 Subject: Module imports during object instantiation In-Reply-To: <1186888682.860619.258610@19g2000hsx.googlegroups.com> References: <1186888682.860619.258610@19g2000hsx.googlegroups.com> Message-ID: <46c011b5$0$417$426a74cc@news.free.fr> Ritesh Raj Sarraf a ?crit : > On Aug 11, 3:17 am, James Stroud wrote: >> You do realize your import statement will only be called for nt and dos >> systems don't you? >> > > Yes. I would like to load a Windows Python Module (which is, say a > specific implementation for Windows only) in such a condition where I > find that the platform is Dos/NT. > > Loading it globally doesn't make sense because when from the same > class an object is created on a non-windows platfom, it would be > waste. It would either ImportError or else just load the module and > never use it. > > As per my understanding __init__ is executed only once during object > creation. For such situations (that I've explained above), I think > __init__() is the correct place to put imports. Nope. The initializer will be called *each time* you instanciate the class. And nothing prevents client code from calling it explicitelly as many times as it wants - ok, this would be rather strange, but this is still technically possible. What I mean that you have no assurance about the number of times an initializer will be called. wrt/ your problem, remember that top-level code is executed when the module is loaded (either as a main program or as an imported module). The canonical solution to os-specific imports is to handle them at the top-level: if os.name == 'posix: from some_posix_module import get_colors elif os.name in ['nt', 'dos']: from some_nt_module import get_windows_color as get_colors else: get_colors = lambda: None # or any other sensible default value... class SomeClass(object): def __init__(self, *args, **kw): self.colors = get_colors() From winter at biotec.tu-dresden.de Tue Aug 21 15:00:05 2007 From: winter at biotec.tu-dresden.de (Christof Winter) Date: Tue, 21 Aug 2007 21:00:05 +0200 Subject: How to optimise this code? In-Reply-To: References: Message-ID: <46CB3635.7050705@biotec.tu-dresden.de> David N Montgomery wrote: > class testCase: > def __init__(self, tc): > if tc == 1:self.testCase1() > if tc == 2:self.testCase2() > if tc == 3:self.testCase3() > if tc == 4:self.testCase4() > if tc == 5:self.testCase5() > if tc == 6:self.testCase6() > > def testCase1(self): > print "tc1" > > def testCase2(self): > print "tc2" > > def testCase3(self): > print "tc3" > > def testCase4(self): > print "tc4" > > def testCase5(self): > print "tc5" > > def testCase6(self): > print "tc6" > > > def testCaseX(self): > print "tcX" > > totalNumberOfTestCases = 6 > x = 0 > while x <= totalNumberOfTestCases: > x += 1 > testCase(x) > > > This template code is working, but I envisage having 100+ test cases and > am concerned about my useage of if statements. I would be grateful for > any pointers as to how I can run all tests cases, regardless of how > many, in a more efficient manner. > > Thank you in advance. To get rid of the if statements, replace __init__ function with: def __init__(self, tc): functionToCall = eval("self.testCase%s" % tc) functionToCall() HTH, Chris From aahz at pythoncraft.com Sat Aug 11 17:28:12 2007 From: aahz at pythoncraft.com (Aahz) Date: 11 Aug 2007 14:28:12 -0700 Subject: Augmented assignment (was Re: Something in the function tutorial confused me.) References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> Message-ID: In article , Roel Schroeven wrote: > >I used to interpret the target in 'The target is only evaluated once' >more like an L-value in C/C++. That's not correct, of course, but I >didn't understand exactly how wrong it was until now. It's true almost everywhere except augmented assignment. Augmented assignment is a prime example of the compromises one needs to make in adding features. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "And if that makes me an elitist...I couldn't be happier." --JMS From grante at visi.com Wed Aug 29 09:18:39 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 29 Aug 2007 13:18:39 -0000 Subject: Gmane's been quiet ... References: <1i3l2k9.1j3tdgr1iz19yeN%raims@dot.com> <13d9l0f1i2erdc6@corp.supernews.com> <1i3lsqu.10ti61g1fs47osN%raims@dot.com> Message-ID: <13dashf69pebi6e@corp.supernews.com> On 2007-08-29, Steve Holden wrote: > Lawrence Oluyede wrote: >> Grant Edwards wrote: >>> Posting that were made to mailing lists via gmane? >> >> That, I do not know >> > Given that I have now read a reply to my post-via-gmane on gmane before > seeing the original post appear there I shall assume they've been having > some sort of issue. New articles are showing up on gmane's NNTP server now, though the one posting I made via that server yesterday appears to have been lost. -- Grant Edwards grante Yow! MERYL STREEP is my at obstetrician! visi.com From arkanes at gmail.com Wed Aug 8 13:03:09 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 8 Aug 2007 12:03:09 -0500 Subject: Tkinter or wxpython? In-Reply-To: <46B9F09B.2060903@codebykevin.com> References: <7xlkcopu4r.fsf@ruckus.brouhaha.com> <7x7io8r6na.fsf@ruckus.brouhaha.com> <46B9DE7B.3050909@codebykevin.com> <46B9F09B.2060903@codebykevin.com> Message-ID: <4866bea60708081003j4e8343a9s3fe2ff2fb3d3f55a@mail.gmail.com> On 8/8/07, Kevin Walzer wrote: > Chris Mellon wrote: > > On 8/8/07, Kevin Walzer wrote: > > > Using Tile, of course, loses you the first major benefit of Tk - that > > it's already included in the standard library. So in this sense it's > > still "ugly old school look and feel" vs "no external dependencies", > > which is the swing decision for many people. People who prefer the Tk > > API, of course, will be happy to use Tile. > > Tile has been implemented in the Tk core starting with version 8.5, > still somewhere between alpha and beta stage. Once 8.5 is out, and > Python is configured to build against Tk 8.5 (instead of 8.4), it should > Just Work. > > > > Also, while you can get (mostly) native *look*, the feel is absent. > > Unless I'm very uninformed, Tile is a theming engine only, and doesn't > > implement platform conventions with regard to behavior (the "feel" > > part of look and feel). > > What do you mean here? Things like keyboard accelerators, menu > placement, and so on? Those things are already natively implemented by > Tk, and the developer just needs to invoke them. Sometimes some > conditional code is required for stuff like keyboard accelerators (the > "tk windowingsytem" command is useful for this), but again, it should > Just Work. > > Or am I missing something? > There's conventions for shortcuts and they vary by platform. For example, home/end do different things on a mac vs on windows. Scrollbars interact differently, and menu pulldowns operate differently. To my knowledge, while Tile can replicate the *look* of these things, it does not help with the interaction. People often say "look and feel" when they actually just mean look. It's something that I try to bring up when I hear "look and feel" being applied to purely visual skinning tools. Don't think I'm singling out Tk, Gtk has exactly the same problem - you can make the buttons look native, but it doesn't adjust the behavior. From steve at holdenweb.com Fri Aug 10 08:19:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 10 Aug 2007 08:19:33 -0400 Subject: Smoother Lines in Turtle Graphics In-Reply-To: References: <1186703789.695265.52390@e9g2000prf.googlegroups.com> <5i2tnaF3mgsofU1@mid.uni-berlin.de> <1186744055.367994.61850@g12g2000prg.googlegroups.com> Message-ID: Jeremy Sanders wrote: > Ant wrote: > >> Python: Batteries and Turtles included! > > I didn't know that! It looks like turtle is based on Tk, which doesn't have > antialiasing yet (see http://wiki.tcl.tk/10101 ), so it can't really be > made nice and smooth (unless you could somehow use tkzinc/tkpath to draw > with). > > I suppose turtle wouldn't be that hard to reimplement it to use Qt/Gtk > instead. > Doing that would make it less useful, though, since the primary value of turtle is to provide something that (sort of) works fro the standard library without adding further batteries. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From __peter__ at web.de Thu Aug 9 04:21:39 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 09 Aug 2007 10:21:39 +0200 Subject: how to get output. References: <5hvrhhF3m15c7U1@mid.uni-berlin.de> <1186645852.687961.323420@x35g2000prf.googlegroups.com> <1186646135.742185.5280@x35g2000prf.googlegroups.com> Message-ID: indu_shreenath at yahoo.co.in wrote: > I corrected a typ below. > > On Aug 9, 12:50 pm, indu_shreen... at yahoo.co.in wrote: >> Hey, >> >> I did write the following: >> but it does not work. >> >> import subprocess as sp >> try: >> p = sp.Popen("DIR . /AD /B", stdout=sp.PIPE) >> result = p.communicate()[0] >> print result >> except: >> print "error" >> >> This throws error. >> DIR . /AD /B will list out only directories in the current directory. try: ... except: print "error" is a really bad idea because it hides any meaningful and therefore valuable information about the error. IIRC the "dir" command is internal to the dos shell and therefore has to be called indirectly. The actual command is "cmd", not "dir": [following snippet found at http://www.python-forum.de/viewtopic.php?p=73048&sid=13808229538bd52de4ef75c32cf67856] >>> import subprocess >>> args = ["cmd", "/C", "dir", "J:\\", "/O", "/AD", "/B"] >>> process = subprocess.Popen(args, stdout = subprocess.PIPE, stderr = subprocess.STDOUT) >>> print process.stdout.read() If you just want a list of subdirectories, here's a better approach: >>> def directories(folder): ... return os.walk(folder).next()[1] >>> directories(".") [snip list of subdirectories of cwd] Peter From ladynikon at gmail.com Fri Aug 3 11:46:56 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Fri, 3 Aug 2007 11:46:56 -0400 Subject: Eclipse/PyDev question. In-Reply-To: References: <1186153119.391091.275860@r34g2000hsd.googlegroups.com> <1186153259.372809.230110@d30g2000prg.googlegroups.com> <1186153503.806195.225560@g4g2000hsf.googlegroups.com> Message-ID: <59f9c5160708030846j5bb2e275u8db95474519b00fe@mail.gmail.com> I wonder how long before they come out with a python version of eclipse. I know there is a C/C++ now. Danyelle From jergosh at wp.pl Sun Aug 5 07:09:46 2007 From: jergosh at wp.pl (=?UTF-8?B?R3J6ZWdvcnogU8WCb2Rrb3dpY3o=?=) Date: Sun, 05 Aug 2007 13:09:46 +0200 Subject: A question on plugin design Message-ID: <46B5AFFA.3030301@wp.pl> I'm working on my little project (an IM client) which I wanted to support plugins. My idea was that the core program would by itself do virtually nothing but manage plugins and all functionality would be provided by the plugins themselves (including protocol handling and UI. My first attempt was to check a directory for *.py files, execfile() them and rely on them to call a method to register a plugin object. This approach led to some conundrums and I discarded the it as bad design. My second take was to __import__() from each plugin file the plugin object and append it to a list of all plugins. But, this way I have to put imports into the __init__() of the plugin object or else they have no effect. Is this a valid approach? I'm starting to think that such problems are again symptoms of poor design. I'd also be grateful for pointers to a well designed Pythonic plugin architecture but I'd much prefer a small project with a simple API. TIA, Greg Slodkowicz From rodrigo.cr at gmail.com Tue Aug 28 10:36:50 2007 From: rodrigo.cr at gmail.com (rodrigo) Date: Tue, 28 Aug 2007 14:36:50 -0000 Subject: Check for dict key existence, and modify it in one step. Message-ID: <1188311810.226363.295500@w3g2000hsg.googlegroups.com> Im using this construct a lot: if dict.has_key(whatever): dict[whatever] += delta else: dict[whatever] = 1 sometimes even nested: if dict.has_key(whatever): if dict[whatever].has_key(someother): dict[whatever][someother] += delta else: dict[whatever][someother] = 1 else: dict[whatever]={} dict[whatever][someother] = 1 there must be a more compact, readable and less redundant way to do this, no? Thanks, Rodrigo From larry.bates at websafe.com Thu Aug 2 14:11:51 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 02 Aug 2007 13:11:51 -0500 Subject: File access In-Reply-To: <1186072898.405831.105670@e16g2000pri.googlegroups.com> References: <1186072898.405831.105670@e16g2000pri.googlegroups.com> Message-ID: JD wrote: > Hi, > > What I am trying to do is to run a subprocess on another machine using > subprocess.Popen, this subprocess contuinue writing something into a > file when it is runing. > > After submit this subprocess, I tried to open the file and readlines() > in the loop (with a delay) in the loop) when the subprocess was > runing. > > The problem is I could not get anything untill the subprocess > finished. > > I also tried to run another python programm when the subprocess is > runing, I could get what I want. > > Does anyone know why? Thanks! > > JD > I believe you are approaching this incorrectly. You should probably be using a socket server/socket client to communicate between these two. Or perhaps you could use a multi-user database table. Writing/reading to files from two different workstations and expecting them to by synchronized most likely won't work. -Larry From rhamph at gmail.com Thu Aug 16 15:21:24 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: Thu, 16 Aug 2007 19:21:24 -0000 Subject: Idea for joined() builtin Message-ID: <1187292084.077352.235340@i38g2000prf.googlegroups.com> I know similar things have been argued before, but little things (like the joined name implying a copy) can make a big difference. That and I'm providing a simple implementation that works right now, so you don't have to wait for it to ever become a builtin. ;) >>> joined([], [[1,2,3], [4,5,6]]) [1, 2, 3, 4, 5, 6] >>> joined(' ', ['hello', 'world']) 'hello world' def joined(sep, iterable): if hasattr(sep, 'join'): return sep.join(iterable) # string-like interface else: output = type(sep)() # Hopefully an empty container for i in iterable: output.extend(i) # list-like interface output.extend(sep) else: if sep: del output[-len(sep):] return output A little commentary on the intended usage. There are three common ways to "combine" objects: The first is adding numbers together. This may be accomplished with a +b or sum([a, b]). All values affect the output, but their individuality is lost; you cannot extract the original values[1]. The second is concatenation. This is usually done with list.extend, ''.join(), or with my joined function. It can also be done with a+b, but the performance is substantially worse if done repeatedly. All values affect the output and most of their individuality is retained; given the original lengths of the subsequences, you can extract them from the combined form. The third is the "or" operation of a set or integer. This is done with a|b. The values usually have some effect on the output, but as redundant entries are removed, they lose a significant part of their individuality. The important thing to realize is that all of these different ways of "combining" objects has different conceptual behaviour and different performance characteristics. Get them confused or attempt to over- generalize and you will be bitten. [1] Math/crypto has some exceptions. Stop mentally poking holes in my argument. :) -- Adam Olsen, aka Rhamphoryncus From asma61 at dsl.pipex.com Fri Aug 31 16:15:10 2007 From: asma61 at dsl.pipex.com (DaveM) Date: Fri, 31 Aug 2007 21:15:10 +0100 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188497498.3468.60.camel@dot.uniqsys.com> <0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net> <1188551958.728836.137370@x35g2000prf.googlegroups.com> Message-ID: <6ftgd35rd1g4mddqg2f44d7svd4r85ev17@4ax.com> On Fri, 31 Aug 2007 02:37:15 -0700, Erik Max Francis wrote: >_Troll_ and _frolic_ aren't pronounced with the same "o" sound in any >accent I've ever heard of. You've never heard an English accent then. >Which you pronounce _boat_ and _bot_ the same way, too? No - but I would pronounce "lever" and "fever" the same way, if that helps. DaveM From larry.bates at websafe.com Tue Aug 28 12:18:52 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 28 Aug 2007 11:18:52 -0500 Subject: Getting subprocesses to be hidden on Windows In-Reply-To: <1188246076.131276.292010@r34g2000hsd.googlegroups.com> References: <1188246076.131276.292010@r34g2000hsd.googlegroups.com> Message-ID: geoffbache wrote: > Hi, > > As part of my efforts to write a test tool that copes with GUIs > nicely, I'm trying to establish how I can start a GUI process on > Windows that will not bring up the window. So I try to hide the window > as follows: > > info = subprocess.STARTUPINFO() > info.dwFlags |= subprocess.STARTF_USESHOWWINDOW > info.wShowWindow = subprocess.SW_HIDE > > proc = subprocess.Popen(..., startupinfo=info) > > This works, in a way, but doesn't work recursively. I.e. if the > started process itself starts a window, that second window will not be > hidden. This even applies to dialog boxes within the application. So > instead of a lot of windows popping up I now get a lot of disembodied > dialogs appearing, which is a slight improvement but not much. > > Also, certain processes (e.g. tkdiff) seem to ignore the directive to > be hidden altogether. > > This is dead easy on UNIX with virtual displays like Xvfb. Can someone > shed any light if it's possible on Windows from python? > > Regards, > Geoff Bache > While I'm not entirely sure I understand what you want, I think you can accomplish it by using win32CreateProcess instead of subprocess. You can run the application minimized or perhaps in a REALLY small window. If you have modal dialog boxes, I don't think you can do anything as they don't run in the parent windows frame but rather outside (I could be wrong about this). -Larry From ldo at geek-central.gen.new_zealand Thu Aug 30 20:57:09 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 31 Aug 2007 12:57:09 +1200 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <46d674c2$0$417$426a34cc@news.free.fr> <1188496588.750629.208100@g4g2000hsf.googlegroups.com> <1188498073.997168.282420@q5g2000prf.googlegroups.com> Message-ID: In message , Steve Holden wrote: > But why would you want to ignore built-in support like "value in dict"? Because a function can be passed as a value in its own right, a built-in construct cannot. From zentraders at gmail.com Tue Aug 14 18:54:47 2007 From: zentraders at gmail.com (Zentrader) Date: Tue, 14 Aug 2007 15:54:47 -0700 Subject: IDLE path browser not recognizing my PYTHONPATH In-Reply-To: <46C17651.6090407@v.loewis.de> References: <1187071523.150365.125590@x40g2000prg.googlegroups.com> <46C17651.6090407@v.loewis.de> Message-ID: <1187132087.474387.71660@q4g2000prc.googlegroups.com> On Aug 14, 2:30 am, "Martin v. L?wis" wrote: > > I set PYTHONPATH to /home/me/bin in bash.bashrc, however the IDLE path > > browser is not recognizing this. Not sure why. > > > Grateful for any insight. > > The file "bash.bashrc" has no relevance. If you meant to set the > variable every time you start bash, put it into ".bashrc", in your > home directory. If that still doesn't work, type "env" before starting > idle, and inspect its output. > > Regards, > Martin You also have to export, so to add to your existing PYTHONPATH, you would add something like this to ~/.bashrc export PYTHONPATH="${PYTHONPATH}:/home/me/bin/" From sjmachin at lexicon.net Mon Aug 6 18:45:25 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 06 Aug 2007 15:45:25 -0700 Subject: xlrd question In-Reply-To: <1186306305.693234.266390@w3g2000hsg.googlegroups.com> References: <1186306305.693234.266390@w3g2000hsg.googlegroups.com> Message-ID: <1186440325.053904.85990@x40g2000prg.googlegroups.com> On Aug 5, 7:31 pm, has wrote: > > Nope, DistUtils will copy all modules to site-packages as part of the > installation procedure. If you're a developer you'll probably want to > keep the original distribution around as it'll contain documentation, > examples, etc. which you'll want to refer to when writing your own > scripts. End-users of your scripts won't need it though. xlrd installs sub-folders called "docs" and "examples", containing you- guess-what. The runxlrd.py script will be parked in a "scripts" folder somewhere. There should been no need to retain the folder into which the distribution was unpacked and from which it was installed. From matsben at gmail.com Mon Aug 20 03:04:45 2007 From: matsben at gmail.com (Mats) Date: Mon, 20 Aug 2007 00:04:45 -0700 Subject: best GUI library for vector drawing program In-Reply-To: <1187361760.396397.251030@e9g2000prf.googlegroups.com> References: <1187357244.883516.79840@j4g2000prf.googlegroups.com> <1187359935.718745.206790@i38g2000prf.googlegroups.com> <1187361760.396397.251030@e9g2000prf.googlegroups.com> Message-ID: <1187593485.206021.291390@w3g2000hsg.googlegroups.com> If you want to stay within Tcl/Tk you could take a look at my tkpath package: http://tclbitprint.sf.net/ and shots: http://tclbitprint.sourceforge.net/tkpath/quartz/index.html http://tclbitprint.sourceforge.net/tkpath/gdiplus/index.html http://tclbitprint.sourceforge.net/tkpath/cairo/index.html Mats From mail at timgolden.me.uk Fri Aug 24 03:55:01 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 24 Aug 2007 08:55:01 +0100 Subject: Newbie: List file system roots In-Reply-To: References: Message-ID: <46CE8ED5.6070506@timgolden.me.uk> Einar W. H?st wrote: > Hi, > > How would you list the file system roots in Python? That is, I'm looking > for a way to list all connected drives (C:, D: etc) on a Windows box, or > all /root, /tmp etc on a *nix box. In Java, there's a built-in API > function to do this, File.listRoots(), but I couldn't find any > equivalents in the Python libraries. Couple of options for Windows (probably more as well): http://timgolden.me.uk/python/win32_how_do_i/find-drive-types.html http://timgolden.me.uk/python/wmi_cookbook.html#find-drive-types TJG From lists at liquidtrust.org Wed Aug 22 13:42:33 2007 From: lists at liquidtrust.org (Charlie) Date: Wed, 22 Aug 2007 11:42:33 -0600 Subject: MsiLib Message-ID: <20070822114233.vnncyhsiyo0swc8w@74.220.202.27> Hi, I am trying to figure out how to use msilib to extract the registry information from an MSI file and I really could use a good example of how that is accomplished or even just an example using msilib in general. Does anybody happen to know of an example for this as I wasn't able to find one? If there isn't one, would anybody be willing to throw one together? Thanks Charlie From quetzalcotl at consultant.com Mon Aug 20 04:23:13 2007 From: quetzalcotl at consultant.com (Ingo Menger) Date: Mon, 20 Aug 2007 01:23:13 -0700 Subject: Xah's Edu Corner: Under the spell of Leibniz's dream In-Reply-To: <1187567809.896668.228650@z24g2000prh.googlegroups.com> References: <1187567809.896668.228650@z24g2000prh.googlegroups.com> Message-ID: <1187598193.118227.270460@19g2000hsx.googlegroups.com> On 20 Aug., 01:56, Xah Lee wrote: > (for you math illiterates out there: ... > (for you mathematicians out there: ... Please, Xah Lee, could you possibly stop to "explain" things that are absolutely trivial? If somebody has doubts about the etymology of a word, he may use the dictionary, or he could ask. From SMERSH009X at gmail.com Fri Aug 3 21:58:10 2007 From: SMERSH009X at gmail.com (SMERSH009) Date: Sat, 04 Aug 2007 01:58:10 -0000 Subject: Script that Navigates Page needs Javascript Functionality Message-ID: <1186192690.100410.260840@g12g2000prg.googlegroups.com> I have a script that navigates pages and scrapes the HTML source of the page. in order to view the results I need I need python to "navigate to" this Javascript link: javascript:__doPostBack('ctl00$cpMain$pagerTop','4') This basically translates into "go to page 4." I read the posts on this group, and from what I understand, the functionality I need is with simplejson? If so, what is the syntax i would use to execute that Javascript? Or am I completely off base with using simplejson altogether? Thanks for the help -Sam From horpner at yahoo.com Wed Aug 8 15:23:16 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 08 Aug 2007 19:23:16 GMT Subject: Misleading wikipedia article on Python 3? References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <7xzm15q8fy.fsf@ruckus.brouhaha.com> <41Dti.37401$G23.10727@newsreading01.news.tds.net> <1186582066.096793.14700@57g2000hsv.googlegroups.com> <1186600271.858692.182090@22g2000hsm.googlegroups.com> Message-ID: On 2007-08-08, Istvan Albert wrote: > On Aug 8, 2:00 pm, Neil Cerutti wrote: > >> I thought, in fact, that open was on more shaky ground. ;) > > yeah, that too ... OK, I had misremembered. The current docs say that open is preferred, and that file should rather be used as a type name. > >> I can't find any evidence of that in the PEPs. Do you have a reference? > > here is something: > > http://svn.python.org/view/python/branches/p3yk/Misc/NEWS?rev=56685&view=auto > > look for : > > - Removed these Python builtins: > apply(), callable(), coerce(), file(), reduce(), reload() Thanks very much. -- Neil Cerutti Outside of the killings, Washington has one of the lowest crime rates in the country. --Marion Barry From rcdailey at gmail.com Tue Aug 14 11:42:00 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 14 Aug 2007 10:42:00 -0500 Subject: Python script for mobile platforms -- suggested? In-Reply-To: <46C12274.2070705@jayloden.com> References: <496954360708121958m170b6cd2j8419802dcdd35482@mail.gmail.com> <496954360708131727o5276d5a5w57baff6cbea4c34c@mail.gmail.com> <46C12274.2070705@jayloden.com> Message-ID: <496954360708140842s2e5b7c6ctb7a40aa4099719db@mail.gmail.com> Hi Jay, I apologize for not having been detailed enough. Right now I'm using a C++ library known as TinyXML to parse my XML files. When a menu is to be displayed, the XML is parsed and the appropriate images, text, etc that will display on the menu is loaded based on the data in that XML. Note that the XML parsing happens before the menu is drawn and only happens once per menu as to avoid performance overhead during the menu drawing. For example, to create a menu that has an image in the center of the screen, the XML would be this: The "Origin" and "Justification" elements act sort of like function calls, and the "Frame" element defines an "Object" kind of. Each Frame is a visual element in the Menu. I'm not sure if you'll agree or not, but even in this simple example it's very hard to read just given the nature of the XML syntax. Secondly, I'm not using XML as it was intended to be used. I'm using it as a script instead of a representation of data. Most of the real menus are 600+ lines of XML much like above, however it is not nearly as simplistic. I will paste a real example of a menu below this email for those curious to look at it. I haven't decided on what the Python version of the example above would look like, that would probably happen sometime after I decided to go with Python for a menu scripting replacement (If I do, that is). I might mix XML and Python much like World of Warcraft mixes XML with LUA script. Again, this all depends on design. The important points I wanted to get across is that the Python script wont' be executed past the construction of a menu. The Python/XML script would be simply there to allow the game to create the menu and other important things. I hope I've given enough examples and details. If I haven't, please let me know and I'll answer any questions you may have. Thanks for following up. On 8/13/07, Jay Loden wrote: > > Robert Dailey wrote: > > I'm currently developing a game for a cell phone. The game has a GUI > > system that's currently using XML to define the individual menus. > > Basically this means that for every single menu the user goes to, it > > loads and parses an XML file. Would using Python Script instead of > > XML be a reasonable replacement, or would it be even slower? I've > > read various articles online but I'm still curious to hear what > > everyone has to say here. > > A number of questions come to mind...for starters: > > 1) What is parsing the XML now? C code? Python? > 2) What is the proposed python script supposed to do when they load the > menu? without knowing that or seeing some sample code or details, that's an > impossible question to answer, since an arbitrary Python script might take > milliseconds, seconds, hours, or days to complete running. > > It might help if you give a concrete example (code is always welcome!) and > explained exactly what the options are that you're considering and why. Then > the folks on the list can try to give you a rough estimate or possibly > suggest alternative methods you may not have considered. > > -Jay > -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Wed Aug 15 12:10:10 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 15 Aug 2007 16:10:10 GMT Subject: closing StringIO objects References: <1i2vpnc.wv6c3n1r76qzvN%aleax@mac.com> Message-ID: On 2007-08-15, Alex Martelli wrote: > Neil Cerutti wrote: >> The documentation says the following about StringIO.close: >> >> close( ) >> Free the memory buffer. >> >> Or else... what? > > Or else the memory buffer sticks around, so you can keep > calling getvalue as needed. I believe the freeing will happen > anyway, eventually, if and when the StringIO instance is > garbage collected (just like, say, a file object's underlying > fd gets closed when the file object is garbage collected), but > relying on such behavior is often considered a dubious practice > nowadays (given the existence of many Python implementations > whose GC strategies differ). Thanks. It doesn't seem worth the trouble, given your explanation. I was refactoring some pickled StringIO code, and decided to try out the with statement. I discovered that StringIO isn't a context manager, so I dipped into contextlib and found 'closing'. But it's starting to look overengineered, and I realized I had no idea if it was worth all this fuss just to close a StringIO object. from __future__ import with_statement from contextlib import closing import pickle import StringIO def unserialize(d): with closing(StringIO.StringIO(d)) as s: obj = pickle.load(s) return obj def serialize(d): with closing(StringIO.StringIO()) as s: pickle.dump(d, s) arg = s.getvalue() return arg -- Neil Cerutti Beethoven wrote fewer symphonies than Haydn and Mozart because he wrote longer, and besides he went death. --Music Lit Essay From ldo at geek-central.gen.new_zealand Tue Aug 28 07:41:07 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 28 Aug 2007 23:41:07 +1200 Subject: Xah's Edu Corner: Under the spell of Leibniz's dream References: <1187567809.896668.228650@z24g2000prh.googlegroups.com> <1187578927.945921.280180@q4g2000prc.googlegroups.com> Message-ID: In message , Albert Y. C. Lai wrote: > Twisted wrote: >> A link to a copy in a non-toxic format would be nice. > > http://www.cs.utexas.edu/users/EWD/transcriptions/EWD12xx/EWD1298.html Not a mention of G?del. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Aug 24 06:08:13 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 24 Aug 2007 12:08:13 +0200 Subject: Newbie: List file system roots References: Message-ID: <5j7p0dF2vlof6U1@mid.individual.net> "Einar W. H?st" wrote: > How would you list the file system roots in Python? That is, I'm > looking for a way to list all connected drives (C:, D: etc) on a > Windows box, or all /root, /tmp etc on a *nix box. /root and /tmp are no "roots", but normal directories. glob.glob("/*") will give you all of those. Regards, Bj?rn -- BOFH excuse #236: Fanout dropping voltage too much, try cutting some of those little traces From tjreedy at udel.edu Mon Aug 20 11:18:49 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 20 Aug 2007 11:18:49 -0400 Subject: yet another indentation proposal References: <13ci0oesdtlh871@corp.supernews.com><_49yi.9351$3x.6614@newssvr25.news.prodigy.net><1187589173.410862.132580@o80g2000hse.googlegroups.com> Message-ID: If there is not one already, a page for blind and visually impaired programmers on the Python site would be a good addition. From michele.simionato at gmail.com Mon Aug 13 01:58:42 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 13 Aug 2007 05:58:42 -0000 Subject: is there anybody using __del__ correctly?? In-Reply-To: <0M2dnWsFO7-zwSLbnZ2dnUVZ_ryqnZ2d@comcast.com> References: <1186731369.073644.158490@z24g2000prh.googlegroups.com> <1186762908.121319.35900@x35g2000prf.googlegroups.com> <1186895084.388293.295330@57g2000hsv.googlegroups.com> <0M2dnWsFO7-zwSLbnZ2dnUVZ_ryqnZ2d@comcast.com> Message-ID: <1186984722.604498.39490@q75g2000hsh.googlegroups.com> On Aug 12, 9:14 pm, Steven Bethard wrote: > Michele Simionato wrote: > > On Aug 10, 7:09 pm, Steven Bethard wrote: > >> There were also a few recipes posted during this discussion that wrap > >> weakrefs up a bit nicer so it's easier to use them in place of __del__: > > >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/519635 > > > I knew about your recipe and I thought it was clever, *very* > > clever. I have been thinking about it a bit more today and > > here is an alternative, which does not require metaclasses, > > does not require descriptors, and does not require the user to > > declare the attributes she will use in the __finalize__ method. > > Warning: it is no more tested than the test case in your recipe: > > > import weakref > > > _get = object.__getattribute__ > > _set = object.__setattr__ > > _del = object.__delattr__ > > > def getinnerobj(self): > > return _get(self, '*innerobj*') > > > class Impostor(object): > > "It tries very hard to impersonate the inner object" > > def __init__(self, obj): > > _set(self, '*innerobj*', obj) > > def __getattribute__(self, name): > > return getattr(getinnerobj(self), name) > > def __setattr__(self, name, value): > > _set(getinnerobj(self), name, value) > > def __delattr__(self, name): > > _del(getinnerobj(self), name) > > > _refset = set() > > > class Finalized(object): > > def __new__(cls, *args, **kw): > > self = super(Finalized, cls).__new__(cls, *args, **kw) > > self.__init__(*args, **kw) > > def finalize(ref, refset=_refset): > > refset.remove(ref) > > cls.__finalize__(self) > > fake = Impostor(self) > > _refset.add(weakref.ref(fake, finalize)) > > return fake > > def __finalize__(self): > > pass > > The problem here is that __getattribute__ doesn't work for things like > __getitem__. Yeah, it is the old issue of special methods being special, i.e. len(x) is not exactly x.__len__(). I am not sure if this can be changed in Py3k, it is certainly annoying in some (rare) circumstances, as here. One workaround is to add all special methods to the Impostor class: SPECIALMETHODS = ['__%s__' % name for name in ''' abs add and call concat contains delitem delslice div eq floordiv ge getitem getslice gt iadd iand iconcat idiv ifloordiv ilshift imod imul index inv invert ior ipow irepeat irshift isub iter itruediv ixor le len lshift lt mod mul ne neg not or pos pow repeat repr rshift setitem setslice str sub truediv xor '''.split()] def add_special_method(cls, name): def meth(self, *args): return getattr(self, name) (*args) meth.__name__ = name setattr(cls, name, meth) for name in SPECIALMETHODS: add_special_method(Impostor, name) In this way the Impostor can emulate even the special methods. Here is an example: >>> class C(object): ... pass ... >>> c=Impostor(C()) >>> print c <__main__.C object at 0x102a390> Notice that the impostor is calling the __str__ method of C, so it really looks like a C object. Moreover >>> c.__class__ and >>> isinstance(c, C) True so the Impostor is doing a damn pretty good job of imposture for C objects. Of course it does what it can, and it cannot impersonate C objects completely: >>> type(c) so code using checks like ``type(c) is C`` would break and the approach here cannot be considered more than a hack. Still a cool hack, I would say ;) Michele Simionato From jonas.esp at googlemail.com Fri Aug 17 19:13:03 2007 From: jonas.esp at googlemail.com (Kless) Date: Fri, 17 Aug 2007 23:13:03 -0000 Subject: Encryption and hashing In-Reply-To: References: <1187377630.017794.36510@50g2000hsm.googlegroups.com> Message-ID: <1187392383.237609.97250@19g2000hsx.googlegroups.com> On 17 ago, 20:34, Laszlo Nagy wrote: > > For who knows any of criptography I comment that you can use > > algorithms as secure as Rijndael, Twofish, or Serpent with the CFB > > cipher mode. And for hash you can use RIPEMD, SHA-2 or WHIRLPOOL. > > As I recall, PyCrypto can also use these, and many others. And it can > also do RSA. These are the algorithms supported in the last version of PyCrypto: $ ls pycrypto-2.0.1/src/ AES.c Blowfish.c DES.c IDEA.c RIPEMD.c winrand.c ARC2.c cast5.c _dsa.c MD2.c _rsa.c XOR.c ARC4.c CAST.c _fastmath.c MD4.c SHA256.c block_template.c DES3.c hash_template.c RC5.c stream_template.c So it haven't Twofish, Serpent, neither Whirlpool. Neither many others. From __peter__ at web.de Wed Aug 22 03:05:59 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Aug 2007 09:05:59 +0200 Subject: Logging module gives duplicate log entries References: <1187702248.203917.188570@k79g2000hse.googlegroups.com> <1187731317.661324.244870@k79g2000hse.googlegroups.com> <1187735263.468497.147220@l22g2000prc.googlegroups.com> Message-ID: Shiao wrote: > Maybe my question wasn't very clear. What I meant is that these four > lines lead in my case to two entries per logged event: > > applog = logging.getLogger() > applog.setLevel(logging.DEBUG) > hdl = logging.FileHandler('/tmp/foo.log') > applog.addHandler(hdl) > > However if I REPLACE the above by: > > logging.basicConfig(level=logging.DEBUG, filename='/tmp/foo.log') > > things work as expected. Then you have a logic error in your program that causes that piece of code to run twice (I simulate that by the for-loop): $ python Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> for i in range(2): ... logging.getLogger().addHandler(logging.StreamHandler()) ... >>> logging.warn("twice") twice twice logging.basicConfig() on the other hand does nothing if it finds existing handlers: $ python Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> for i in range(2): ... logging.basicConfig() ... >>> logging.warn("once") WARNING:root:once Peter From hniksic at xemacs.org Wed Aug 22 03:59:39 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 22 Aug 2007 09:59:39 +0200 Subject: File Read Cache - How to purge? References: <1187669203.698637.81990@i38g2000prf.googlegroups.com> <87veb9xb7y.fsf@mulj.homelinux.net> <87ir781afk.fsf@mulj.homelinux.net> Message-ID: <87k5roov84.fsf@mulj.homelinux.net> Steve Holden writes: >> That URL claims that you need to run "sync" before dropping the >> cache, and so do other resources. I wonder if that means that >> dropping the cache is unsafe on a running system. > > Good grief. Just let the operating system do its job, for Pete's > sake, and go find something else to obsess about. Purging the page cache for the purposes of benchmarking (such as measuring cold start time of large applications) is an FAQ, not an "obsession". No one is arguing that the OS shouldn't do its job in the general case. From kairosenthal at tiscali.de Fri Aug 10 05:24:57 2007 From: kairosenthal at tiscali.de (Kai Rosenthal) Date: Fri, 10 Aug 2007 02:24:57 -0700 Subject: com: makepy gencache.EnsureModule Message-ID: <1186737897.040138.201880@j4g2000prf.googlegroups.com> Hello, I' having a problem with gencache.EnsureModule: I used win32com\client\makepy.py to successfully generate Python sources. Unfortunately, after I call win32com.client.Dispatch(), the object I get back is of type "COMObject" instead of one of the generated classes. In particular, I'm trying to interact with SolidWorks Extensibility Type Library and the PROGID is "SldWorks.Application". Using win32com\client\makepy.py -i SolidWorks Extensibility Type Library {801A0000-A66C-11D3-A8BD-0000861EBBD6}, lcid=0, major=1, minor=0 >>> # Use these commands in Python code to auto generate .py support >>> from win32com.client import gencache >>> gencache.EnsureModule('{801A0000-A66C-11D3-A8BD-0000861EBBD6}', 0, 1, 0) Looking in win32com\gen-py, the appropriate file _does_ exist: 801A0000-A66C-11D3-A8BD-0000861EBBD6x0x1x0.py and it does contain the correct class definitions. Then, in my code: >>> mod = win32com.client.gencache.EnsureModule('{801A2001-A66C-11D3-A8BD-0000861EBBD6}', 0, 1, 0) >>> mod None >>> ob = win32com.client.Dispatch("SldWorks.Application") >>> ob Why are the object mod is None and the object ob is instead >? Any bright ideas as to what's going wrong here? Thanks for your hints, Kai From __peter__ at web.de Fri Aug 10 07:31:18 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 10 Aug 2007 13:31:18 +0200 Subject: subprocess.Popen(cmd) question References: Message-ID: WolfgangZ wrote: > I'm starting some subprocesses inside a loop. The processes run > independent and dont need any communication between each other. Due to > memory issues I need to limit the number of running processes to around > 10. How can I insert a break into my loop to wait until some processes > are finished? > > Some minimal examplecode: > > import subprocess > for i in range(0,100): > cmd='ping localhost' > p=subprocess.Popen(cmd) > p.wait() > Just polling the processes may be good enough: import random import subprocess import sys import time from itertools import islice from functools import partial PROCESSES = 100 SIMULTANEOUS = 10 def info(*args): print >> sys.stderr, " ".join(str(a) for a in args) class Process(object): def __init__(self, index): self.index = index info("starting process #%d" % index) self.process = subprocess.Popen(["ping", "localhost", "-w", "%d" % random.randrange(1, 6)]) def __nonzero__(self): running = self.process.poll() is None if not running: # XXX ugly side effect info("process #%d terminated" % self.index) return running def processes(): for i in range(PROCESSES): yield partial(Process, i) def main(): starters = processes() running = [sp() for sp in islice(starters, SIMULTANEOUS)] while running: before = len(running) running = [p for p in running if p] after = len(running) if before == after: info("waiting") time.sleep(1) else: running.extend(sp() for sp in islice(starters, SIMULTANEOUS - len(running))) info("that's all, folks") if __name__ == "__main__": main() Peter From kwmsmith at gmail.com Fri Aug 3 16:51:03 2007 From: kwmsmith at gmail.com (Kurt Smith) Date: Fri, 3 Aug 2007 15:51:03 -0500 Subject: Strange set of errors In-Reply-To: References: Message-ID: On 8/3/07, Stephen Webb wrote: > Greetings all, > > I've recently begun using Python to do scientific computation, and I wrote > the following script to find approximate eigenvalues for a semi-infinite > matrix: > > > from pylab import * > from numpy import * > from scipy import * > > def bandstructure(N,s): > > b = s/4.0 > > jmax = 10 + N**2 > > spectrum1 = [0]*2*N > spectrum2 = [0]*2*N > spectrum3 = [0]*2*N > > > for k in arange(1, 2*N+1, 1): > > A = zeros( (jmax,jmax) ) > > i = 0 > while i <= jmax-1: > if i <= jmax-2: > A[i,i+1] = b > A[i+1,i] = b > A[i,i] = ((k + 2.0*i*N)/N)**2 > i = i+1 > else: > A[i,i] = ((k + 2.0*i*N)/N)**2 > i = i+1 > > #This portion of the code builds a matrix twice as large to check > against > > B = zeros( (2*jmax,2*jmax) ) > > i = 0 > while i <= 2*jmax-1: > if i <= 2*jmax-2: > B[i,i+1] = b > B[i+1,i] = b > B[i,i] = ((k + 2.0*i*N)/N)**2 > i = i+1 > else: > B[i,i] = ((k + 2.0*i*N)/N)**2 > i = i+1 > > x = linalg.eigvals(A) > y = linalg.eigvals(B) > > j = 1 > while j<=3: > if abs(y[j]-x[j]) <= 10.0**(-5): > j = j + 1 > else: > print 'jmax not large enough to obtain accurate results' > > spectrum1[k-1] = x[0] + 0.5*s > spectrum2[k-1] = x[1] + 0.5*s > spectrum3[k-1] = x[2] + 0.5*s > > plot (k, spectrum1, k, spectrum2, k, spectrum3) > > xlabel('k (energy level)') > ylabel('E/E_r') > title('Finite Size Band Structure, N = %d, s = %f' % (N, s)) > grid(true) > > > When I run this script, I get the following message, which I can't figure > out: > > Traceback (most recent call last): > File "", line 1, in > File "bandstruc.py", line 61, in bandstructure > plot (k, spectrum1, k, spectrum2, k, spectrum3) > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib/pylab.py", > line 2028, in plot > ret = gca().plot(*args, **kwargs) > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib/axes.py", > line 2535, in plot > for line in self._get_lines(*args, **kwargs): > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib/axes.py", > line 437, in _grab_next_args > for seg in self._plot_2_args(remaining[:2], **kwargs): > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib/axes.py", > line 337, in _plot_2_args > x, y, multicol = self._xy_from_xy(x, y) > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib/axes.py", > line 266, in _xy_from_xy > nrx, ncx = x.shape > ValueError: need more than 0 values to unpack > Basically, you're trying to plot spectrum[123] vs. k: the spectra are lists, but k is an integer. I made some modifications to get things working more smoothly. Note the ion() function call at the beginning, and the use of "indx = arange(1,2*N+1)" instead of plotting vs. k. There's probably some other things that could be cleaned up, but I'm short on time right now; this will get your code working at least. Hope this helps, (From a fellow physicist) Kurt ################################################################## from pylab import * from numpy import * ion() def bandstructure(N,s): b = s/4.0 jmax = 10 + N**2 spectrum1 = [0]*2*N spectrum2 = [0]*2*N spectrum3 = [0]*2*N for k in arange(1, 2*N+1, 1): A = zeros( (jmax,jmax) ) i = 0 while i <= jmax-1: if i <= jmax-2: A[i,i+1] = b A[i+1,i] = b A[i,i] = ((k + 2.0*i*N)/N)**2 i = i+1 else: A[i,i] = ((k + 2.0*i*N)/N)**2 i = i+1 #This portion of the code builds a matrix twice as large to check against B = zeros( (2*jmax,2*jmax) ) i = 0 while i <= 2*jmax-1: if i <= 2*jmax-2: B[i,i+1] = b B[i+1,i] = b B[i,i] = ((k + 2.0*i*N)/N)**2 i = i+1 else: B[i,i] = ((k + 2.0*i*N)/N)**2 i = i+1 x = linalg.eigvals(A) y = linalg.eigvals(B) j = 1 while j<=3: if abs(y[j]-x[j]) <= 10.0**(-5): j = j + 1 else: print 'jmax not large enough to obtain accurate results' spectrum1[k-1] = x[0] + 0.5*s spectrum2[k-1] = x[1] + 0.5*s spectrum3[k-1] = x[2] + 0.5*s indx = arange(1,2*N+1, 1) plot (indx, spectrum1, indx, spectrum2, indx, spectrum3) xlabel('k (energy level)') ylabel('E/E_r') title('Finite Size Band Structure, N = %d, s = %f' % (N, s)) grid(True) From glarocque at cfl.forestry.ca Thu Aug 16 09:46:58 2007 From: glarocque at cfl.forestry.ca (glarocque at cfl.forestry.ca) Date: Thu, 16 Aug 2007 06:46:58 -0700 Subject: (Re)announcing APL 2007 In-Reply-To: <1186764041.534462.156660@e9g2000prf.googlegroups.com> References: <5hnkb3F3hus4jU1@mid.individual.net> <1186406430.744134.298400@x35g2000prf.googlegroups.com> <1186764041.534462.156660@e9g2000prf.googlegroups.com> Message-ID: <1187272018.280910.15390@g4g2000hsf.googlegroups.com> On Aug 10, 12:40 pm, r... at ca.inter.net wrote: > On Aug 6, 9:20 am, Paul Mansour wrote: > > > APL2007 Roll Call: Is anyone going to this? > > > I'm thinking about going, but I don't want to the only one to show up, > > as in San Diego. > > Here here. > > Sorry to mention the elephant in the room, but this discussion begs > the obvious question: what is the rationale for putting on this > conference? Perhaps I missed that discussion, and if so, please > excuse me. > > As we know, there are already two well-attended APL vendor conferences > in the world each year, plus several other more local gatherings. > > Speaking as an APL consultant and product distributor, this puts > people in a tough spot, since we now have at least three events to > consider travelling to and attending (assuming APL2000 is hosting its > usual Florida event this year?). > > I suppose I should be happy for another opportunity to meet and > network with potential APL colleagues and customers, but if it's > mainly the same small audience at each event, the costs are hard to > justify more than once per year. > > I don't have any answers to this dilemma yet, but I think it requires > a lot more discussion. Just putting on a conference and hoping people > attend may, at this point I think, be somewhat counterproductive. > > ...richard Richard, In your comments you were concerned by the fact that the rationale for APL2007 was not clear. You also mentioned that there was some sort of a conflict with two APL vendor conferences. When the decision was made to hold a conference in the fall of 2007, the members of the steering committee were well aware that there was a potential conflict with APL vendor workshops. However, we had a discussion about this issue and finally concluded that it was a good idea to go ahead with APL2007 for two reasons. First, the idea to hold APL2007 is to have users of different Array Programming Languages (including APL, J, K, NIAL and other related languages) attend the conference. SIGAPL, in addition to fostering the discussion between array programming languages themselves, aims to promote the array processing paradigm and its richness in contrast to the scalar one. It is SIGAPL's vision to serve as a counterpoint in the programming community by facilitating communications among researchers, developers and users of Array Programming Languages. APL2007 will be an excellent opportunity to promote our core values in the mainstream programming community through our conference agenda, tutorials and discussion panels. This will benefit APL and all Array Programming Languages. Second, there was an opportunity to meet jointly with OOPSLA. Thus, APL2007 attendees will have the opportunity to spend a few more days and attend other presentations on object oriented programming. As far as APL is concerned, there has been development in object oriented programming in some APL versions. I am confident that all the APL vendors and many APL consultants and users will attend the conference, along with researchers, consultants or users of Array Programming Languages. So, I am looking forward to meeting you at APL2007. Guy Larocque SIGAPL Chairman From graemeglass at gmail.com Fri Aug 10 08:24:29 2007 From: graemeglass at gmail.com (Graeme Glass) Date: Fri, 10 Aug 2007 12:24:29 -0000 Subject: Threaded Design Question In-Reply-To: <1186683909.797328.68770@i13g2000prf.googlegroups.com> References: <1186683909.797328.68770@i13g2000prf.googlegroups.com> Message-ID: <1186748669.095699.112760@g12g2000prg.googlegroups.com> Using IPC is just adding needles complexity to your program. Instead of constantly scanning the directory for files and then adding them to a Queue, and then having to worry if that specific file may have already been popped off the queue and is currently running by one of the workers, just poll the directory for a specific event, ala CREATE. If you are using a *nix based system, you can use, pyinotify (http:// pyinotify.sourceforge.net/) using EventsCodes.IN_CREATE event. Else if you using a windows system, take a look at: http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html, Tim has a couple of different ideas, sure one of them will be what you need. Then all you have to do is added newly created files to the queue, fork the off to workers and the workers can delete them when they done. No need to worry if someone is working with it already, as it will only be added once to the queue, when it is created. HTH. Regards, Graeme From cvezvu at gmail.com Wed Aug 15 08:32:52 2007 From: cvezvu at gmail.com (cvezvu at gmail.com) Date: Wed, 15 Aug 2007 12:32:52 -0000 Subject: Guitar Reviews Message-ID: <1187181172.442413.193040@57g2000hsv.googlegroups.com> Custom guitar, acoustic guitar, electric guitars, reviews, specifications, pictures, prices, all here!!!!! http://pro-guitars.blogspot.com/ Free guitars!!!! http://freeguitars.blogspot.com/ From dejanews at email.com Sun Aug 19 08:27:07 2007 From: dejanews at email.com (samwyse) Date: Sun, 19 Aug 2007 07:27:07 -0500 Subject: Parser Generator? In-Reply-To: <_6mdnZxbdNKTVFrbnZ2dnUVZ_tqtnZ2d@comcast.com> References: <_6mdnZxbdNKTVFrbnZ2dnUVZ_tqtnZ2d@comcast.com> Message-ID: Jack wrote: > Thanks for all the replies! > > SPARK looks promising. Its doc doesn't say if it handles unicode > (CJK in particular) encoding though. > > Yapps also looks powerful: http://theory.stanford.edu/~amitp/yapps/ > > There's also PyGgy http://lava.net/~newsham/pyggy/ > > I may also give Antlr a try. > > If anyone has experiences using any of the parser generators with CJK > languages, I'd be very interested in hearing that. I'm going to echo Tommy's reply. If you want to parse natural language, conventional parsers are going to be worse than useless (because you'll keep thinking, "Just one more tweak and this time it'll work for sure!"). Instead, go look at what the interactive fiction community uses. They analyse the statement in multiple passes, first picking out the verbs, then the noun phrases. Some of their parsers can do on-the-fly domain-specific spelling correction, etc, and all of them can ask the user for clarification. (I'm currently cobbling together something similar for pre-teen users.) From wildemar at freakmail.de Mon Aug 20 11:23:29 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 20 Aug 2007 17:23:29 +0200 Subject: Newbee Question In-Reply-To: <5itohrF3qv9t4U1@mid.uni-berlin.de> References: <5itohrF3qv9t4U1@mid.uni-berlin.de> Message-ID: <46C9B1F1.2000705@freakmail.de> Diez B. Roggisch wrote: > Sounds a bit like homework. Which usually isn't simply delivered here. > > Wrong! Usually that happens pretty quickly here (as proven again in this case). Not that it should, but only the seniors seem to detect lazy learners. /W From multiseed at gmail.com Tue Aug 21 09:17:28 2007 From: multiseed at gmail.com (Shiao) Date: Tue, 21 Aug 2007 13:17:28 -0000 Subject: Logging module gives duplicate log entries Message-ID: <1187702248.203917.188570@k79g2000hse.googlegroups.com> Hi, I am getting duplicate log entries with the logging module. The following behaves as expected, leading to one log entry for each logged event: logging.basicConfig(level=logging.DEBUG, filename='/tmp/foo.log') But this results in two entries for each logged event: applog = logging.getLogger() applog.setLevel(logging.DEBUG) hdl = logging.FileHandler('/tmp/foo.log') applog.addHandler(hdl) The app is based on the web.py framework, so I guess my problem may be connected to be some interaction with other uses of logging within the framework. This is not specific to the root logger, the same happens with logging.getLogger('foo'). Any clue would be more than welcome. best, ShiaoBu From newsreturns at biszumknie.de Tue Aug 28 08:37:34 2007 From: newsreturns at biszumknie.de (Andreas Lobinger) Date: Tue, 28 Aug 2007 14:37:34 +0200 Subject: expat error, help to debug? In-Reply-To: References: Message-ID: Aloha, Andreas Lobinger wrote: > Andreas Lobinger wrote: >> Lawrence D'Oliveiro wrote: >>> In message , Andreas Lobinger wrote: >>>> Anyone any idea where the error is produced? > The registered Handler has to return a (integer) value. > Would have been nice if this had been mentioned in the documentation. Delete last line, it is mentioned in the documentation. From dstromberg at datallegro.com Tue Aug 21 18:31:40 2007 From: dstromberg at datallegro.com (Dan Stromberg - Datallegro) Date: Tue, 21 Aug 2007 15:31:40 -0700 Subject: python debugging under emacs? Message-ID: Is there a debugging mode in emacs that works well with python? I tried gud, but it was giving me errors, so I thought I'd ask before I try to get it to work: Is there an emacs mode (perhaps gud) that'll give a view of the python source, and currenly executing line, the ability inspect datastructures, etc.? You know, like a modern debugger? :) I also looked at ddd, but it was cranky too, and apparently hasn't seen a new release in years. I'm really more of a vim person than an emacs person, but if emacs will do what I want, I'd happily use it - for this. :) From spottedMetal at gmail.com Sat Aug 11 16:45:10 2007 From: spottedMetal at gmail.com (Gregory D. Weber) Date: Sat, 11 Aug 2007 20:45:10 GMT Subject: Something in the function tutorial confused me. In-Reply-To: References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <1186424693.529497.217040@w3g2000hsg.googlegroups.com> <46B8626A.2070303@bigfoot.com> <5hsoi3F3mlni2U1@mid.individual.net> <1186581124.3383.55.camel@dot.uniqsys.com> <1i2nhxn.tme05x17r39odN%aleax@mac.com> Message-ID: Neil Cerutti wrote: > On 2007-08-11, Alex Martelli wrote: >> Neil Cerutti wrote: >> ... >>> The Python Language Reference seems a little confused about the >>> terminology. >>> >>> 3.4.7 Emulating numeric types >>> 6.3.1 Augmented assignment statements >>> >>> The former refers to "augmented arithmetic operations", which I >>> think is a nice terminology, since assignment is not necessarily >>> taking place. Then the latter muddies the waters. >> Assignment *IS* "necessarily taking place"; if you try the augmented >> assignment on something that DOESN'T support assignment, you'll get an >> exception. Consider: >> >>>>> tup=([],) >>>>> tup[0] += ['zap'] >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: 'tuple' object does not support item assignment >> >> Tuples don't support item ASSIGNMENT, and += is an ASSIGNMENT, >> so tuples don't allow a += on any of their items. >> >> If you thought that += wasn't an assignment, this behavior and >> error message would be very problematic; since the language >> reference ISN'T confused and has things quite right, this >> behavior and error message are perfectly consistent and clear. > > Thanks for the correction. I was under the illusion that > sometimes augmented assignment would instead mutate the > object. > I too thought += was an assignment. And it bit me very painfully a few weeks ago. If it's an assignment, then wouldn't "x += y" mean the same thing as "x = x + y"? If so, why does an assignment to variable a, below, have the *side effect* of changing variable b ... ? >>> a = [1, 2, 3] >>> b = a >>> b [1, 2, 3] >>> a += [4] >>> a [1, 2, 3, 4] >>> b [1, 2, 3, 4] ... but using the "x = x + y" style, the assignment to variable c, below, does *not* have a side effect on variable d (as indeed it should not!)? >>> c = [1, 2, 3] >>> d = c >>> d [1, 2, 3] >>> c = c + [4] >>> c [1, 2, 3, 4] >>> d [1, 2, 3] >>> From sbellon at sbellon.de Wed Aug 8 19:14:41 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Thu, 9 Aug 2007 01:14:41 +0200 Subject: Destruction of generator objects References: <20070808002852.6228ae91@cube.tz.axivion.com> <1186613044.494852.306970@q75g2000hsh.googlegroups.com> Message-ID: <20070809011441.05d7dfb6@cube.tz.axivion.com> On Wed, 08 Aug, MRAB wrote: > Simple! :-) Sorry, I forgot to mention that I am forced to using Python 2.4. -- Stefan Bellon From mxr at qvii.com Thu Aug 2 12:02:20 2007 From: mxr at qvii.com (Mike Rooney) Date: Thu, 02 Aug 2007 12:02:20 -0400 Subject: Error subclassing datetime.date and pickling Message-ID: <46B2000C.4090001@qvii.com> Hi everyone, this is my first post to this list. I am trying to create a subclass of datetime.date and pickle it, but I get errors on loading it back. I have created a VERY simple demo of this: import datetime class MyDate(datetime.date): """ This should be pickleable. >>> md = MyDate(2007, 1, 6) >>> import pickle >>> pickle.dump(md, open("test.pickle", 'w')) >>> mdp = pickle.load(open("test.pickle")) >>> import os; os.remove("test.pickle") """ def __init__(self, y, m, d): datetime.date.__init__(self, y, m, d) if __name__ == "__main__": import doctest doctest.testmod() The traceback that occurs is: Traceback (most recent call last): File "C:\Python25\lib\doctest.py", line 1212, in __run compileflags, 1) in test.globs File "", line 1, in mdp = pickle.load(open("test.pickle")) File "C:\Python25\lib\pickle.py", line 1370, in load return Unpickler(file).load() File "C:\Python25\lib\pickle.py", line 858, in load dispatch[key](self) File "C:\Python25\lib\pickle.py", line 1133, in load_red value = func(*args) TypeError: __init__() takes exactly 4 arguments (2 given) I have found a few relating issues: - https://sourceforge.net/tracker/?func=detail&atid=105470&aid=952807&group_id=5470 - http://sourceforge.net/tracker/index.php?func=detail&aid=720908&group_id=5470&atid=105470 But these are both rather old and are marked as fixed. I am running Python 2.5.1 on Windows XP SP2. Any help here would be greatly appreciated! - Mike From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Aug 6 03:48:44 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 06 Aug 2007 09:48:44 +0200 Subject: A question on plugin design In-Reply-To: <873ayxso2o.fsf@pobox.com> References: <87fy2yrp4y.fsf@pobox.com> <873ayxso2o.fsf@pobox.com> Message-ID: <46b6d24b$0$29273$426a74cc@news.free.fr> John J. Lee a ?crit : > jjl at pobox.com (John J. Lee) writes: > >> Grzegorz S?odkowicz writes: >> [...] >>> I'd also be grateful for pointers to a well designed Pythonic plugin >>> architecture but I'd much prefer a small project with a simple API. >> Google for setuptools and Python eggs. Search for "entry point" on >> the setuptools page. > > And as an example of a project that uses that plugin system, look at > the nose testing tool And at Trac too. From dijkstra.arjen at gmail.com Thu Aug 9 10:43:04 2007 From: dijkstra.arjen at gmail.com (dijkstra.arjen at gmail.com) Date: Thu, 09 Aug 2007 14:43:04 -0000 Subject: tests In-Reply-To: References: <1186666919.456036.120270@d30g2000prg.googlegroups.com> Message-ID: <1186670584.148181.180040@r34g2000hsd.googlegroups.com> On Aug 9, 4:04 pm, brad wrote: > kyoso... at gmail.com wrote: > > You should be able to read chunks of each file in binary mode and do a > > compare to check for equality. Some kind of loop should do the trick. > > Why not a simple md5 or sha with the hash library? Or even: http://docs.python.org/lib/module-filecmp.html From dejanews at email.com Sun Aug 19 08:42:39 2007 From: dejanews at email.com (samwyse) Date: Sun, 19 Aug 2007 12:42:39 GMT Subject: Searching for pixel color In-Reply-To: References: Message-ID: <3VWxi.28395$RX.23749@newssvr11.news.prodigy.net> michael maver wrote: > Hello, I was just wondering if anyone knew of a way to search the screen > for a certain color in Python. I know of lots of ways to do this... > I know it is possible to do this in other languages, but I'm not sure > how I'd go about doing this in Python. Just to let you know, I'm running > windows XP and I don't really need it to be a cross platform solution, > but if it was that'd be an extra bonus. ... but they are all platform dependent; not just Windows vs Unix, but PIL vs wxWin vs whatever. def search_screen(desired_color): root = my_gui.root_window() width, height = root.get_size() for x in xrange(0, width): for y in xrange(0, height): if root.get_pixel(x,y) == desired_color: return x,y return -1, -1 Modify the above using the appropriate values for 'my_gui' and its methods, 'root_window', 'get_size' and 'get_pixel'. > Thanks very much for taking the time to read this and, hopefully, respond! You're welcome. From uymqlp502 at sneakemail.com Thu Aug 30 22:00:47 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Thu, 30 Aug 2007 19:00:47 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <7xlkbsmqe4.fsf@ruckus.brouhaha.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> Message-ID: <1188525647.003223.199620@q5g2000prf.googlegroups.com> Paul Rubin wrote: > Bruno Desthuilliers writes: > > FWIW, the "Eiffel and SPARK Ada folks" also "brilliantly explained" > > why one can not hope to "write reliable programs" without strict > > static declarative type-checking. > > I don't know about Eiffel but at least an important subset of SPARK > Ada's DBC stuff is done using static analysis tools (not actually > built into the compiler as it happens) to verify statically > (i.e. without actually running the code) that the code fulfills the > DBC conditions. I don't see any way to do that with Python > decorators. Yes, thanks for reminding me about that. With SPARK Ada, it is possible for some real (non-trivial) applications to formally (i.e., mathematically) *prove* correctness by static analysis. I doubt that is possible without "static declarative type- checking." SPARK Ada is for applications that really *must* be correct or people could die. With all due respect, most (not all, but most) Python programmers never get near such programs and have no idea about how stringent the requirements are. Nor do most programmers in general, for that matter. (It's not an insult) From ssalvatori at gmail.com Tue Aug 14 23:08:58 2007 From: ssalvatori at gmail.com (stefano) Date: Wed, 15 Aug 2007 03:08:58 -0000 Subject: make images with python Message-ID: <1187147338.400947.181010@x40g2000prg.googlegroups.com> I need make some images using python but i'm lost :P i need some module to make .png (with drawline, drawcircle, drawpoint etc etc etc ) like gd for php :P thants :D From dstromberg at datallegro.com Thu Aug 9 17:26:19 2007 From: dstromberg at datallegro.com (Dan Stromberg - Datallegro) Date: Thu, 09 Aug 2007 21:26:19 GMT Subject: Screenscraping, in python, a web page that requires javascript? Message-ID: Is there a method, with python, of screenscraping a web page, if that web page uses javascript? I know about BeautifulSoup, but AFAIK at this time, BeautifulSoup is for HTML that doesn't have embedded javascript. Thanks! From larry.bates at websafe.com Fri Aug 31 19:42:10 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 31 Aug 2007 18:42:10 -0500 Subject: parsing response from SOAPpy request In-Reply-To: <1188601582.917623.122890@r29g2000hsg.googlegroups.com> References: <1188601582.917623.122890@r29g2000hsg.googlegroups.com> Message-ID: seancron wrote: > I'm using SOAPpy to access weather data from the NOAA National Digital > Forecast Database XML Web Service [1] and I've been having > trouble figuring out how to parse the data. > > The response comes back as XML document but when I check it with > type(result) it shows the the response is a string. Does anyone have > any > suggestions on getting relevant data? > > Thanks, > -Sean > > [1] http://www.weather.gov/forecasts/xml/ > XML data is just a string of characters. Use elementree xml parser (built into Python 2.5 available for download for prior versions) to parse it for what you want to extract. -Larry From rcdailey at gmail.com Tue Aug 21 17:07:19 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 21 Aug 2007 16:07:19 -0500 Subject: Latest models of Gibson guitars In-Reply-To: References: <1187544898.289948.322160@22g2000hsm.googlegroups.com> <1187548916.909340.37420@k79g2000hse.googlegroups.com> <1187579396.285862.186860@e9g2000prf.googlegroups.com> <9K6dnY8HnIUNHlTbnZ2dnUVZ_gGdnZ2d@comcast.com> <1187657694.106990.266830@z24g2000prh.googlegroups.com> <1187700758.572516.186610@57g2000hsv.googlegroups.com> Message-ID: <496954360708211407g22064295n56a4a3b142641e04@mail.gmail.com> lol... On 8/21/07, Tony wrote: > > I don't who is posting here stupid shit about guitars > who ever is do self fever hang your self with one of strings > > > "kaldrenon" wrote in message > news:1187700758.572516.186610 at 57g2000hsv.googlegroups.com... > > On Aug 20, 8:54 pm, Twisted wrote: > >> If the message then > >> says something absurd, like "this is a newsgroup about Python" when > >> I'm reading it in cljp, well, what do you expect? :P > > > > I think most would expect you to go, "WTF?" but then, like a rational > > person, click the helpful little "More options" link that GG provides > > (I'm assuming you use GG to read as well as to post, forgive me if I'm > > wrong) and double-check before harassing someone because you jumped to > > conclusions. > > > >> though nothing in the headers would indicate this. > > > > Newsgroups: comp.lang.java.programmer, > > microsoft.public.dotnet.framework.aspnet, comp.lang.python, > > rec.photo.digital, alt.home.repair > > From: mobile... at gmail.com > > Date: Sun, 19 Aug 2007 17:34:58 -0000 > > Local: Sun, Aug 19 2007 1:34 pm > > Subject: Latest models of Gibson guitars > > > > That's the header GG shows. Preeeetty clear. > > > > Just a tip for future reference - all's fair if you weren't aware of > > this feature of GG's interface. > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hhygcy at gmail.com Mon Aug 13 04:27:44 2007 From: hhygcy at gmail.com (Ge Chunyuan) Date: Mon, 13 Aug 2007 08:27:44 -0000 Subject: which IDE is highly recommended in Windows OS In-Reply-To: References: <1186970945.403792.51790@d55g2000hsg.googlegroups.com> Message-ID: <1186993664.769976.109710@r34g2000hsd.googlegroups.com> On Aug 13, 10:24 am, _spitFIRE wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Ge Chunyuan wrote: > > hi Group: > > > I am a new comer for Python, I wonder which IDE is recommended in > > Windows OS. > > Can anyone give some suggestion. > > > Thanks indeed > > Ge Chunyuan > > - - Stani's Python Editor > (http://www.softpedia.com/get/Programming/Coding-languages-Compilers/S...) > - - Black Adder (http://www.thekompany.com/products/blackadder/) > - - Zeus (http://www.zeusedit.com/python.html) > - - PyScripter (http://mmm-experts.com/Products.aspx?ProductId=4) > - - ActivePython (http://www.activestate.com/) > - - IDLE (http://www.python.org/idle/doc/idle2.html) > > and depending on how you define IDEs, you can also decide whether or not to > include, the following > - - emacs > - - vim > - - scite > ... > > - -- > _ _ _]{5pitph!r3}[_ _ _ > __________________________________________________ > "I'm smart enough to know that I'm dumb." > - Richard P Feynman > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (GNU/Linux) > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org > > iD8DBQFGv8DSA0th8WKBUJMRAqGcAJ9hhMp3tyS7XmBZT2+fol/A69j4jwCfXNya > xQTmmDlDF5BAfiWkrSW3TuQ= > =902n > -----END PGP SIGNATURE----- thanks buddy, I am now using ActivePython, actually it is beyond my expectation:) From jstroud at mbi.ucla.edu Fri Aug 24 16:17:06 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 24 Aug 2007 13:17:06 -0700 Subject: GUI and distrubution In-Reply-To: <92ab7$46cf1f51$4275d90a$11544@FUSE.NET> References: <1187974418.175783.50860@i38g2000prf.googlegroups.com> <92ab7$46cf1f51$4275d90a$11544@FUSE.NET> Message-ID: Kevin Walzer wrote: > anders wrote: > >> So how is the preferably way to distribute software written i Python > >> My next question is witch is the best GUI to use, also consider >> the delivery question above. >> > > These are two of the most-often-asked questions on this list (along with > "What's the best Python IDE?"). Search the list archives via Google, or > do a general Google search. Some helpful terms to get you started > include pyinstaller, py2exe, py2app, Tkinter, wxPython, PyQt, and pyGTK. One of these days, someone needs to write a tutorial on distributing for the Big 3 (Linux, OSX, and Amiga--or was that last one supposed to be M$?). James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From goldtech at worldpost.com Sun Aug 19 11:43:53 2007 From: goldtech at worldpost.com (goldtech) Date: Sun, 19 Aug 2007 08:43:53 -0700 Subject: Python syntax r prefix to a string Message-ID: <1187538233.285841.117280@e9g2000prf.googlegroups.com> Does anyone know this syntax and could link me to an explanation? Something like: Workspace = r'C:\foobar\mystuff\xyz' What's that "r" doing? Sometimes I see a "u" too. Explanation appreciated. Thanks, Lee G. From steven.bethard at gmail.com Thu Aug 23 23:01:01 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 23 Aug 2007 21:01:01 -0600 Subject: optparse - required options In-Reply-To: References: <496954360708201251r137dfaedqe632361891eae343@mail.gmail.com> <46C9F7D1.9040506@jayloden.com> <496954360708201353v19ea266cr50f144d1d71d5912@mail.gmail.com> <46CA0814.6050200@jayloden.com> Message-ID: Omari Norman wrote: > On Mon, Aug 20, 2007 at 05:31:00PM -0400, Jay Loden wrote: >> Robert Dailey wrote: >>> Well, I don't know what is wrong with people then. I don't see how >>> required arguments are of bad design. > >> I tend to agree...while "required option" may be an oxymoron in >> English, I can think of quite a few scripts I've written myself (in >> various languages) that needed at least some kind of user input to >> operate. > > The idea with optparse is not that programs should not require certain > information on the command line; rather, the idea is that this > information should be positional arguments, not 'options'. > > That is, to use the compiler example: > > compiler file > > is preferred if a file argument is necessary. > > compiler --file file > > is not preferred. I agree with the optparse philosophy, but Practicality Beats Purity. That's why I was convinced to add "required options" to argparse -- there are too many applications that want that kind of interface. *I* don't write applications with interfaces like that, but enough people do that the use case should really be supported. STeVe From nepbabucxspamfree at yahoo.ca Tue Aug 21 06:45:17 2007 From: nepbabucxspamfree at yahoo.ca (Bikal KC) Date: Tue, 21 Aug 2007 20:15:17 +0930 Subject: IDE for Python In-Reply-To: References: Message-ID: <46cac234$1_1@news.chariot.net.au> Joel Andres Granados wrote: > Hello list: > > I have tried various times to use an IDE for python put have always been > disapointed. > I haven't revisited the idea in about a year and was wondering what the > python people > use. > I have also found http://pida.co.uk/main as a possible solution. Anyone > tried it yet? Free - DrPython, Pydev extension to Eclipse, IDLE. Show me the money - Komodo, IntelliJ IDEA, Visual Python, Wing Python Do your homework and Google for them now. :-) Cheers From olsongt at verizon.net Mon Aug 13 12:03:48 2007 From: olsongt at verizon.net (olsongt at verizon.net) Date: Mon, 13 Aug 2007 09:03:48 -0700 Subject: ANN: Compyler 0.1 In-Reply-To: <1187020875.575423.58000@o61g2000hsh.googlegroups.com> References: <46bf2ea3$0$240$e4fe514c@news.xs4all.nl> <1187020875.575423.58000@o61g2000hsh.googlegroups.com> Message-ID: <1187021028.714284.255560@b79g2000hse.googlegroups.com> > > + has the exact same semantics as compiler code. I was more > This "should read exact same semantics as python code" From http Sun Aug 12 21:36:22 2007 From: http (Paul Rubin) Date: 12 Aug 2007 18:36:22 -0700 Subject: LRU cache? References: <7x8x8ixomj.fsf_-_@ruckus.brouhaha.com> <1i2peoe.18eos9adkclkcN%aleax@mac.com> Message-ID: <7xd4xsfc6h.fsf@ruckus.brouhaha.com> aleax at mac.com (Alex Martelli) writes: > So what's wrong with Evan Prodromou's lrucache.py module that's in pypi? > Haven't used it, but can't see anything wrong at a glance. Thanks, I wasn't aware of that one. I notice two things about it: 1) it's under a GPL-incompatible license (therefore also incompatible with the PSF license); that's a problem for what I'm doing. 2) it uses heapq to figure out which entry is the oldest. I guess that's not too unreasonable and maybe it's necessary. But unless I'm missing something it's never necessary to insert new records into the middle of the list-by-age. So I think it may be easiest to just keep a doubly linked list of records with the invariant that they are ordered by age, keeping track of where both ends are; plus a hash table to map indices to nodes in the linked list. On any access that hits the cache, the found node gets removed and moved to the front of the list in O(1) operations. This may be easiest with a circular list. From jr244 at kent.ac.uk Fri Aug 24 09:45:51 2007 From: jr244 at kent.ac.uk (J. Robertson) Date: Fri, 24 Aug 2007 14:45:51 +0100 Subject: Co-developers wanted: document markup language In-Reply-To: <1187956692.378840.251540@m37g2000prh.googlegroups.com> References: <87odgyyx9u.fsf@wilson.homeunix.com> <87tzqpew22.fsf@wilson.homeunix.com> <87tzqp77my.fsf@wilson.homeunix.com> <7xy7g1if24.fsf@ruckus.brouhaha.com> <87mywh717i.fsf@wilson.homeunix.com> <1187947900.676122.144490@e9g2000prf.googlegroups.com> <87absh6wn6.fsf@wilson.homeunix.com> <1187953231.106631.174870@q4g2000prc.googlegroups.com> <1187956692.378840.251540@m37g2000prh.googlegroups.com> Message-ID: olive wrote: >>> [snip] > > But few people are used to Plain Text Markup (excepted in some > scientific area maybe) and it is error prone. > It looks very much like Gummi's authors and target audience actually are part of the few people you are talking about: i.e. console-happy folks that are perfectly fine with how the math system goes in LaTeX, say, but are annoyed by the clutter besides that. I can't imagine they would want to go anywhere near an equation editor, for example. Looks like a worthwhile project to me :-) From shahmed at sfwmd.gov Tue Aug 28 08:57:51 2007 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Tue, 28 Aug 2007 08:57:51 -0400 Subject: Table update In-Reply-To: Message-ID: <14A2A120D369B6469BB154B2D2DC34D208B6D336@EXCHVS01.ad.sfwmd.gov> I am trying to use python script to update a table by incremental value based on struc_No but having problem to get right result on the value field for the 3rd and 4th same number of struc_no. I need to update the Value field only with the incremental value of 15 or so Any help is highly appreciated. Thanks Shak Input table or source table ID struc_id Struc_No Value 1 ABC 1001 10 2 EFJ 1005 15 3 HIK 1003 10 4 ILK 1005 10 5 PIO 1001 8 6 TIN 1001 12 7 MNO 1001 11 8 POW 1003 18 Output Table ID struc_id Struc_No Value Added value 1 ABC 1001 25 15 2 EFJ 1005 30 15 3 HIK 1003 25 15 4 ILK 1005 40 30 5 PIO 1001 38 30 6 TIN 1001 57 45 7 MNO 1001 71 60 8 POW 1003 48 30 From joesox at gmail.com Mon Aug 20 15:51:51 2007 From: joesox at gmail.com (JoeSox) Date: Mon, 20 Aug 2007 12:51:51 -0700 Subject: 'REPL' style IDE In-Reply-To: <1187632249.748945.158910@i13g2000prf.googlegroups.com> References: <1187632249.748945.158910@i13g2000prf.googlegroups.com> Message-ID: <785694cd0708201251q45316c16of3516eb8254fd4d8@mail.gmail.com> On 8/20/07, beginner wrote: > Hi Everyone, > > I am using the Wing IDE. It works great when developing applications, > but the workflow is like Visual Studio -- after you execute it or > debug it, the python script ends. > > What I want is an interactive interpreting environment. I want the IDE > to execute a boot script to initialize my environment and create some > basic data objects. And then I want to be able to type in command on > the command line using these objects. The IDLE that comes with Python > does this, but compared with Wing, it does not have a lot of the > convenient features. > > I am wondering if there is anything more powerful than IDLE that can > do this. I use Wing IDE. Place something like this on the bottom of your module you are debuging. Place a stop point on the line you want then start your debug! Hope that helps. def test(): c=MyClass c.do_foobar() if __name__ == '__main__': test() -- Later, Joe From kay.schluehr at gmx.net Sat Aug 11 07:19:33 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 11 Aug 2007 04:19:33 -0700 Subject: Destruction of generator objects In-Reply-To: <20070811121630.1b010eab@cube.tz.axivion.com> References: <20070808002852.6228ae91@cube.tz.axivion.com> <1186613044.494852.306970@q75g2000hsh.googlegroups.com> <20070809011441.05d7dfb6@cube.tz.axivion.com> <1186819365.988117.232230@g4g2000hsf.googlegroups.com> <20070811121630.1b010eab@cube.tz.axivion.com> Message-ID: <1186831173.814193.235420@o61g2000hsh.googlegroups.com> On Aug 11, 12:16 pm, Stefan Bellon wrote: > On Sat, 11 Aug, Kay Schluehr wrote: > > On Aug 9, 1:14 am, Stefan Bellon wrote: > > > Sorry, I forgot to mention that I am forced to using Python 2.4. > > It doesn't matter. You can use try...finally as well in Python 2.4. > > It's just not possible to use except and finally clauses in one > > statement such as: > > [snip] > > The problem is yield inside try-finally which is not possible in 2.4. > > -- > Stefan Bellon Oh, yeah... i overlooked this. Honestly, I'd recommend wrapping the generator into a function object, create the resource on construction ( or pass it ) and destroy it implementing __del__. def gen_value(self): while True: yield self.iter.next() class GeneratorObj(object): def __init__(self, obj, gen): self.iter = make_iter(obj) self.gen = gen(self) def __del__(self): destroy(self.iter) def next(self): return self.gen.next() From devraj at gmail.com Sun Aug 26 00:51:20 2007 From: devraj at gmail.com (Devraj) Date: Sun, 26 Aug 2007 04:51:20 -0000 Subject: ActiveRecord for Python/MySQL Message-ID: <1188103880.146814.110780@q4g2000prc.googlegroups.com> Hi everyone, My application uses MySQL as a backend and am using the MySQL/Python bindings. Are there any libraries that provide a database abstraction layer like Activerecords for Python?' Any resources/links will be appreciated. Thanks for your time. From daniels at dsl-only.net Thu Aug 30 23:10:47 2007 From: daniels at dsl-only.net (Scott David Daniels) Date: Thu, 30 Aug 2007 20:10:47 -0700 Subject: Pivy problem and some other stuff In-Reply-To: <5jom54Fh543U2@mid.uni-berlin.de> References: <1188501707.593319.23330@m37g2000prh.googlegroups.com> <5jom54Fh543U2@mid.uni-berlin.de> Message-ID: <13df1kmak87mbb@corp.supernews.com> Marc 'BlackJack' Rintsch wrote: A fine repy > In [57]: funcs = [a, b] > In [58]: funcs > Out[58]: [, ] > > In [59]: funcs[0]() > Out[59]: 1 > > In [60]: funcs[1]() > Out[60]: 2 and a "list comprehension" allows you to call these things no matter how long the list is. So after the above: >>> results = [f() for f in funcs] >>> print results [1, 2] From walterbyrd at iname.com Tue Aug 28 17:15:43 2007 From: walterbyrd at iname.com (walterbyrd) Date: Tue, 28 Aug 2007 14:15:43 -0700 Subject: Is it reasonably easy easy to something like this with python? In-Reply-To: References: <1188326947.527698.245770@r23g2000prd.googlegroups.com> Message-ID: <1188335743.394160.254680@x35g2000prf.googlegroups.com> On Aug 28, 1:31 pm, Gerardo Herzig wrote: > walterbyrd wrote: > The one who make that table sorteable is AJAX. Not php. The php part is > kind of trivial (so it would be `trivial' in python too). It just reads > some data and format it in an html table. Thank you, that is great to know. What if there were 1000 records, and the table was paginated? I suppose, ajax would sort the front end, and backend language, and database, would soft behind the scene, or something? From max at alcyone.com Sat Aug 4 17:37:17 2007 From: max at alcyone.com (Erik Max Francis) Date: Sat, 04 Aug 2007 14:37:17 -0700 Subject: Question -- Running Programming Python Examples In-Reply-To: <1186263007.587499.305340@57g2000hsv.googlegroups.com> References: <1186263007.587499.305340@57g2000hsv.googlegroups.com> Message-ID: chernevik at gmail.com wrote: > Here is a newbie question: how do I get the server examples in the > Preview chapter of "Progamming Python" (Lutz) to run? The code is > supposed to be a little webserver on which to run examples, but when I > run it it I get "permission denied". Running it as root gets "address > already in use". The first error is because non-root users cannot bind to ports lower than 1024. The second error means just what it says: The address is already in use, so you can't bind to port 80. Something else is already bound to it; probably you have an HTTP server already running as part of your default software installation and don't realize it. Choose another port. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis If love is the answer, could you rephrase the question? -- Lily Tomlin From sjmachin at lexicon.net Sun Aug 26 18:14:22 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 26 Aug 2007 15:14:22 -0700 Subject: my parser.py isn't imported In-Reply-To: <874pimqpei.fsf@wilson.homeunix.com> References: <874pimqpei.fsf@wilson.homeunix.com> Message-ID: <1188166462.066732.123620@i13g2000prf.googlegroups.com> On Aug 27, 1:36 am, Torsten Bronger wrote: > Hall?chen! > > I have a module parser.py in the same directory as the main module. > In the main module, I import "parser". On Linux, this works as > expected, however on Windows, it imports the stdlib parser module. > sys.path[0] points to the directory of my parser.py in both cases. > What went wrong here? Ask a literal question, get a literal answer :-) 1. Failure to consider that problems can happen [and therefore will happen [1]] when there are multiple entities with the same name. 2. Failure to RTFabulousM: """ Details of the module searching and loading process are implementation and platform specific. It generally involves searching for a ``built- in'' module with the given name and then searching a list of locations given as sys.path. """ 3. Failure to attempt enlightenment by using the -v option: """ import parser # builtin """ (on Windows) Suggestion: Avoid the confusion. Rename your module. If it is actually intended as a replacement for the builtin one, then you can do: import replacementparser as parser [1] Codex Murphius, circa 5000 BCE HTH, John From aleax at mac.com Sun Aug 19 12:03:53 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 19 Aug 2007 09:03:53 -0700 Subject: clarification References: <13cb7frnqs8f6d9@corp.supernews.com> <1i31aop.2ing3h1hcfz0dN%aleax@mac.com> Message-ID: <1i332et.1rcnw4e1f97a5kN%aleax@mac.com> samwyse wrote: ... > > brain:~ alex$ python -mtimeit -s'sos=[set(range(x,x+4)) for x in > > range(0, 100, 3)]' 'r=set()' 'for x in sos: r.update(x)' > > 100000 loops, best of 3: 18.8 usec per loop > > > > brain:~ alex$ python -mtimeit -s'sos=[set(range(x,x+4)) for x in > > range(0, 100, 3)]' 'r=reduce(set.union, sos, set())' > > 10000 loops, best of 3: 87.2 usec per loop > > > > Even in a case as tiny as this one, "reduce" is taking over 4 times > > longer than the loop with the in-place mutator -- and it only gets > > worse, as we're talking about O(N squared) vs O(N) performance! Indeed, > > this is part of what makes reduce an "attractive nuisance"...;-). [[And The set-union case, just like the list-catenation case, is O(N squared) (when approached in a functional way) because the intermediate result often _grows_ [whenever a new set or list operand adds items], and thus a new temporary value must be allocated, and the K results-so-far "copied over" (as part of constructing the new temp value) from the previous temporary value; and sum(range(N)) grows quadratically in N. The in-place approach avoids that fate by a strategy of proportional over-allocation (used by both set and lists) that makes in-place operations such as .update(X) and .extend(X) amortized O(K) where K is len(X). In the set-intersection case, the intermediate result _shrinks_ rather than growing, so the amount of data "copied over" is a diminishing quantity at each step, and so the analysis showing quadratic behavior for the functional approach does not hold; behavior may be roughly linear, influenced in minor ways by accidental regularities in the sets' structure and order (especially likely for short sequences of small sets, as in your case). Using a slightly longer sequence of slightly larger sets, with little structure to each, e.g.: random.seed(12345) # set seed to ensure total repeatability los=[set(random.sample(range(1000), 990)) for x in range(200)] at the end of the setup (the intersection of these 200 sets happens to contain 132 items), I measure (as usual on my 18-months-old Macbook Pro laptop): stmt = 'reduce(set.intersection,los)' best of 3: 1.66e+04 usec per loop stmt = 'intersect_all(los)' best of 3: 1.66e+04 usec per loop and occasionally 1.65 or 1.67 instead of 1.66 for either or both, whether with 10,000 or 100,000 loops. (Not sure whether your observations about the reduce-based approach becoming faster with more loops may be due to anomalies in Windows' scheduler, or the accidental regularities mentioned above; my timings are probably more regular since I have two cores, one of which probably ends up dedicated to whatever task I'm benchmarking while the other one runs all "background" stuff). > turn indicates that both implementations actually work about same and > your "O(n squared)" argument is irrelevant. It's indeed irrelevant when the behavior _isn't_ quadratic (as in the case of intersections) -- but unfortunately it _is_ needlessly quadratic in most interesting cases involving containers (catenation of sequences, union of sets, merging of dictionaries, merging of priority-queues, ...), because in those cases the intermediate temporary values tend to grow, as I tried to explain in more detail above. Alex From wildemar at freakmail.de Mon Aug 13 11:21:43 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 13 Aug 2007 17:21:43 +0200 Subject: Adventure-Engines in Python In-Reply-To: <46C0255A.4080707@freakmail.de> References: <46C0255A.4080707@freakmail.de> Message-ID: <46C07707.8040803@freakmail.de> Wildemar Wildenburger wrote: > I've set out to make an adventure game and now I'm trying to find a set > of python-modules to help me do that. I know of the usual non-python > suspects (AGAST, AGS, Wintermute, ...) and while I they are really good, > I'd like one that is cross platform. > OK, thanks. I should, of course, have been more specific. By saying "adventure" I mean the graphical variant (say, Monkey Island or Broken Sword), preferably but not necessarily in 2D. I've also found vidaG, but it seems dead as well. I'll keep looking but if you know something, please let me know. /W From carsten at uniqsys.com Fri Aug 3 22:16:02 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 03 Aug 2007 22:16:02 -0400 Subject: How to pass a reference to the current module In-Reply-To: References: Message-ID: <1186193762.3263.27.camel@localhost.localdomain> On Fri, 2007-08-03 at 18:31 -0700, James Stroud wrote: > Carsten Haese wrote: > > please describe less abstractly what you're trying to do. > > You sound like my former thesis adviser. Thanks. I guess. > OK. From an external source, such as configuration file, the user will > specify the *name* of a function somehow with the assumption that the > function will be coded somewhere (in the present or other modules) by > that name. Does the configuration file indicate which module contains the function? -- Carsten Haese http://informixdb.sourceforge.net From arnodel at googlemail.com Thu Aug 30 15:45:30 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 30 Aug 2007 19:45:30 -0000 Subject: subclassing Python types In-Reply-To: <1188502964.572795.89030@r23g2000prd.googlegroups.com> References: <1188500442.434722.157350@q5g2000prf.googlegroups.com> <46d717f5$0$30367$9b4e6d93@newsspool4.arcor-online.net> <1188501865.541186.272290@e9g2000prf.googlegroups.com> <1188502964.572795.89030@r23g2000prd.googlegroups.com> Message-ID: <1188503130.483093.243520@l22g2000prc.googlegroups.com> On Aug 30, 8:42 pm, Arnaud Delobelle wrote: [...] > "Unifying types and classes in Python 2.2" (http://www.python.org/ > download/releases/2.2.3/descrintro/#__new__). That's: http://www.python.org/download/releases/2.2.3/descrintro/#__new__ (damn google groups ;) -- Arnaud From python at jayloden.com Wed Aug 15 13:55:11 2007 From: python at jayloden.com (Jay Loden) Date: Wed, 15 Aug 2007 13:55:11 -0400 Subject: sub-classing the types in the builtin module datetime In-Reply-To: References: Message-ID: <46C33DFF.90704@jayloden.com> Colin J. Williams wrote: > I wish to sub-class (if that's the right word) datetime and to use a > different signature for the constructor. > > The second part has gone smoothly, but it is difficult to access the > type's methods from the sub-class instance. > > I'm beginning to wonder whether it might might be simpler to write my > own Date class. > > Does anyone have any comments please? > > Colin W. I think it would be most effective if you can post the code you're using that illustrates the issue, and what you're trying to do so that the list members can analyze the actual problem. Tracebacks etc are also welcome if applicable. -Jay From bignose+hates-spam at benfinney.id.au Fri Aug 3 20:40:57 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 04 Aug 2007 10:40:57 +1000 Subject: Emacs + python References: <4vasi.139194$wG2.61677@newsfe17.lga> Message-ID: <87zm189lnq.fsf@benfinney.id.au> hg writes: > how about a cscope equivalent ? How about reading what was posted earlier in the thread, and give us a description of what you want instead of a name that people might not recognise? -- \ "The judge asked, 'What do you plead?' I said, 'Insanity, your | `\ honour. Who in their right mind would park in the passing | _o__) lane?'" -- Steven Wright | Ben Finney From bjorns at gmail.com Fri Aug 10 23:16:28 2007 From: bjorns at gmail.com (Beorn) Date: Fri, 10 Aug 2007 20:16:28 -0700 Subject: The Future of Python Threading In-Reply-To: <1186782710.600889.245930@j4g2000prf.googlegroups.com> References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <1i2njyp.1o6yslqe7ff47N%luc@honk-honk.com> <1186782710.600889.245930@j4g2000prf.googlegroups.com> Message-ID: <1186802188.653072.236260@x40g2000prg.googlegroups.com> Btw, although overly simple (single CPU system!), this benchmark is pretty interesting: http://muharem.wordpress.com/2007/07/31/erlang-vs-stackless-python-a-first-benchmark/ About the GIL: I think I've heard Guido say the last attempt at removing the Global Interpreter Lock (GIL) resulted in a Python that was much slower... which kind-of beats the purpose. I don't think it's feasible to remove the GIL in CPython; the best hope of a GIL-free Python might be PyPy. The general trend seems to be that it's hard enough to program single- thread programs correctly, adding to that extreme concurrency awareness as required when you're programming with threads means it's practically impossible for most programmers to get the programs right. The shared-nothing model seems to be a very workable way to scale for many programs (at least web apps/services). From bj_666 at gmx.net Tue Aug 7 02:21:29 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Aug 2007 06:21:29 GMT Subject: Relative-importing * References: <1185559874.299008.167010@x40g2000prg.googlegroups.com> <871weth2gg.fsf@benfinney.id.au> <46ae3894$0$19609$426a34cc@news.free.fr> <1186200218.666444.254200@q3g2000prf.googlegroups.com> <87vebv9yrr.fsf@benfinney.id.au> <1186363732.188847.48070@q3g2000prf.googlegroups.com> <87zm15870h.fsf@benfinney.id.au> <1186454723.425679.220510@q3g2000prf.googlegroups.com> Message-ID: <5hqhb9F3ldifeU2@mid.uni-berlin.de> On Tue, 07 Aug 2007 02:45:23 +0000, rbygscrsepda wrote: > Specifically, in Python 1.5, all of the following generate the error > below: In Python *1.5*!? I somehow doubt that. ;-) > from . import * > from .sibiling_package import * > from .. import * > from ..cousin_package import * > > SyntaxError: 'import *' not allowed with 'from .' > > Importing * is a feature, but this seems like an artificial > inconsistency to me. It's as if the compiler raises an error when it > tries to import * as soon as it sees "from .", regardless of what > comes after it. So is this a bug in python? And if it happens to be a > bug, how can I alert the developers of the python compiler? I'm just guessing here but as * imports are considered bad style the developers might took the opportunity to forbid them in relative imports because relative imports are new and this doesn't break old programs. Ciao, Marc 'BlackJack' Rintsch From carsten at uniqsys.com Fri Aug 31 12:02:54 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 31 Aug 2007 12:02:54 -0400 Subject: So what exactly is a complex number? In-Reply-To: References: Message-ID: <1188576174.3479.9.camel@dot.uniqsys.com> On Thu, 2007-08-30 at 20:11 -0500, Lamonte Harris wrote: > Like in math where you put letters that represent numbers for place > holders to try to find the answer type complex numbers? Is English your native language? I'm having a hard time decoding your question. -- Carsten Haese http://informixdb.sourceforge.net From uymqlp502 at sneakemail.com Thu Aug 30 20:34:14 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Thu, 30 Aug 2007 17:34:14 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <46d75d33$0$6231$426a34cc@news.free.fr> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> <1188430887.481586.106760@l22g2000prc.googlegroups.com> <1188504811.019632.186580@x35g2000prf.googlegroups.com> <46d75116$0$401$426a74cc@news.free.fr> <1188517050.174081.265900@x40g2000prg.googlegroups.com> <46d75d33$0$6231$426a34cc@news.free.fr> Message-ID: <1188520454.996940.293030@m37g2000prh.googlegroups.com> > > That looks like new syntax to me. > > It's the syntax for decorator functions, and it's not that new - it > cames with Python 2.4, released November 30, 2004. After looking more carefully at your example, I don't think it is as clean and logical as the PEP 316 syntax. At first I thought that your pre and post-conditions applied to the class, but now I realize that they apply to the function. I prefer to see the conditions inside the function in the doc string. That just seems more logical to me. With all due respect, your proposal is interesting, but I think it overextends the "function decorator" idea a bit. A nit-pick I might have with the PEP 316 syntax is that I think "invariant" should be spelled out rather than abbreviated as "inv". The same might apply to "pre- condition" and "post-condition". But that's obviously no big deal. From Brian.McCann at viziant.net Fri Aug 24 12:18:51 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Fri, 24 Aug 2007 12:18:51 -0400 Subject: creating a tar file with python Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE2F1@efmailx> Ed, Carsten, Steve, I don't care if Steve Holden is the python God himself, He's a rude, arrogant, vulgar human who shows his true level of intellect by his use of profanity And he goes one level lower, stating he respects the python group he spews his profanity to. He chose to respond to my question, no one dragged him out of bed, as he so quickly pointed out. Re-read the thread! If your three chums are indicative to the type of people in this group Python is in sorry state -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan.behnel-n05pAM at web.de Sun Aug 12 02:21:48 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 12 Aug 2007 08:21:48 +0200 Subject: python + XUL In-Reply-To: <1186894004.913359.132000@b79g2000hse.googlegroups.com> References: <1186894004.913359.132000@b79g2000hse.googlegroups.com> Message-ID: <46BEA6FC.9050907@web.de> Madhu Alagu wrote: > Hi > > > > Python + XUL Success Stories > > > > > Thanks > > Madhu Alagu Any chance you forgot to ask a question? Stefan From aboudouvas at panafonet.gr Mon Aug 6 07:27:05 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Mon, 06 Aug 2007 04:27:05 -0700 Subject: Eclipse/PyDev question. In-Reply-To: References: <1186153119.391091.275860@r34g2000hsd.googlegroups.com> Message-ID: <1186399625.013613.40260@d55g2000hsg.googlegroups.com> > I like pydev and purchased the extensions ... there are bugs of course but > what stopped me from using it is a project were I had some very large files > (my fault). What do you mean by "very large files" ? Can't PyDev handle such ? From kay.schluehr at gmx.net Tue Aug 28 02:53:03 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 27 Aug 2007 23:53:03 -0700 Subject: Python's Suitability? In-Reply-To: References: Message-ID: <1188283983.498884.323740@g4g2000hsf.googlegroups.com> On 28 Aug., 02:28, mrc2... at cox.net (Michael R. Copeland) wrote: > Note that I'm not considering using the existing C/C++ code in my Web > application, because I don't know how to write a C/C++ Windows > application - and I'm sure the learning curve here is greater than > Python's. I'm a very old procedural-based application developer (47+ > years of programming experience), and developing Windows applications is > beyond me. As I see it you might separate the console frontend from your database/ model backend and reuse your database code. The next step would be selecting a webframework that allows you to plugin your own database driver which has to be wrapped into a Python module. For wrapping into a Python module there are several alternatives. SWIG and BOOST.Python are most natural solutions for wrapping C++ code and exposing its functionality to Python. Other options are writing a C interface to your database and use ctypes, Pythons stdlib FFI ( see Python 2.5 docs ). Not sure if there are tools yet to derive a C interface automatically from C++ classes. If so I would prefer the FFI approach. For database plugins: a framework like Pylons [1] seems to be particularly suited for this option but I would recommend requesting answers by the Pylons community directly. [1] http://pylonshq.com/ From jstroud at mbi.ucla.edu Tue Aug 14 17:28:12 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 14 Aug 2007 14:28:12 -0700 Subject: buggie in else syntax ? In-Reply-To: References: Message-ID: stef mientki wrote: > hello, > > I've the idea that the "else" syntax is not always handled correctly, > or I'm overlooking something. > > This pieces of code are automatic translation from another language, > sometimes it works, sometimes it doesn't ??? > > This piece of code works nice: > > a = 2 > > def JSM (line_nr): > print line_nr > > if a>3: > print 'asddas' > else: JSM(230) ; \ <== this is the problem line, that's ok here > print 'aaps' > > While this piece of code gives a syntax error: > > #Function button_antidender(bit in pin,sbyte in out > Button_Counter_Temp,byte in demp) return bit is > def button_antidender ( pin, button_counter_temp, demp ): > #serial_hw_write(counter) > Serial_HW_Write ( button_counter_temp ) ;JSM(226) > if JSM(227) and ( button_counter_temp >= 0 ): > if JSM(228) and ( pin == on ): > button_counter_temp = button_counter_temp + 1 > ;JSM(229) > else: JSM(230) ; > \ <=== SYNTAX ERROR > button_counter_temp = 1 > ;JSM(231) > > Traceback (most recent call last): > File "D:\data_to_test\JALsPy\JALsPy.py", line 347, in ? > Run_JALsPy_Application () > File "D:\data_to_test\JALsPy\JALsPy.py", line 327, in > Run_JALsPy_Application > JG.app.MainLoop() > File "D:\data_to_test\JALsPy\JALsPy.py", line 255, in MainLoop > import JAL_simulation_file > File "D:\data_to_test\JALsPy\JAL_simulation_file.py", line 265 > else: JSM(230) ; \ > > I guess it's not the preferred syntax, but the resemblance with the > original language it optimal. > Why is it sometimes accepted an sometimes give an error message ? > > thanks, > Stef Mientki > > Looks like you've escaped a space. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From iclark at mail.ewu.edu Wed Aug 15 15:01:52 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Wed, 15 Aug 2007 12:01:52 -0700 Subject: All names in the current module In-Reply-To: <87d4xowymq.fsf@wilson.homeunix.com> References: <87d4xowymq.fsf@wilson.homeunix.com> Message-ID: Torsten Bronger wrote: > Hall?chen! > > How can I get a list with all classes defined in the current module? > Thank you! > > Tsch?, > Torsten. > Assuming you want to see all classes in the re module: >>> import re >>> help(re) #best way >>> >>> def isclass(cls): ... try: ... return issubclass(cls, cls) ... except TypeError: ... pass ... return False ... >>> [cls for cls in dir(re) if isclass(getattr(re, cls))] ['Scanner', '_pattern_type', 'error'] Ian From bj_666 at gmx.net Wed Aug 22 15:59:34 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Aug 2007 19:59:34 GMT Subject: way to define static method References: Message-ID: <5j3it6F3qf8ssU1@mid.uni-berlin.de> On Wed, 22 Aug 2007 20:34:21 +0100, Eric CHAO wrote: > I think Python uses a very strange way to define static method in a > class. Why not make it like this? What is so strange about it? > class MyClass: > def my_static_method(self): > # self should be None as it's a static method > # just ignore self > > I'm a newcomer so maybe it's quite naive. But I just wonder why it is > designed like this. That method above isn't a static method, so why should `self` be None? Static methods are created with the `staticmethod` function which can be used as decorator: class MyClass(object): @staticmethod def my_real_static_method(): # Look ma, no `self`. :-) Static methods are just functions, on classes `classmethod`\s are often more useful. They get the class as first argument. Ciao, Marc 'BlackJack' Rintsch From bronger at physik.rwth-aachen.de Fri Aug 24 10:17:27 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 24 Aug 2007 16:17:27 +0200 Subject: Co-developers wanted: document markup language References: Message-ID: <874pip6mq0.fsf@wilson.homeunix.com> Hall?chen! David Boddie writes: > On Fri Aug 24 11:04:33 CEST 2007, Torsten Bronger wrote: > >> Paul Rubin writes: >> >>> TeX/LateX have been around forever and are well established >>> standards, as awful as they are. Why do we want ANOTHER markup >>> language? >> >> Well, because they are awful. ;-) I don't see that there is a >> bunch of already existing projects, in fact, I don't see anyone >> challenging LaTeX at all. However, competition is a good thing, >> and I think there are enough aspects about LaTeX that can be done >> better so that this project is worth being done. > > There are alternatives to LaTeX if you are prepared to look for > them. One of these is Lout: > > http://lout.sourceforge.net/ I know Lout but its syntax is not simple enough to me. Besides, it does not enforce semantic markup. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From steve at holdenweb.com Thu Aug 9 11:55:20 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 09 Aug 2007 11:55:20 -0400 Subject: tests In-Reply-To: <1186671660.912133.225810@l70g2000hse.googlegroups.com> References: <1186666919.456036.120270@d30g2000prg.googlegroups.com> <1186670584.148181.180040@r34g2000hsd.googlegroups.com> <46bb2511$0$10103$7b0f0fd3@mistral.news.newnet.co.uk> <1186671660.912133.225810@l70g2000hse.googlegroups.com> Message-ID: Jason wrote: > On Aug 9, 8:46 am, "special_dragonfly" > wrote: >> wrote in message >>> http://docs.python.org/lib/module-filecmp.html >> My understanding of reading that is that it only looks at the file names >> themselves and not their contents. So whether filename1=filename2 and in the >> case of the function below it, whether one directory has files which are in >> the other. >> Correct me if I'm wrong. >> Dom >> >> P.S. md5 or sha hash is what I'd go for, short of doing: >> >> MyFirstFile=file("file1.xls") >> MySecondFile=file("file2.xls") >> If MyFirstFile==MySecondFile: >> print "True" >> >> although this won't tell you where they're different, just that they are... > > You're incorrect. If the shallow flag is not given or is true, the > results of os.stat are used to compare the two files, so if they have > the same size, change times, etc, they're considered the same. > > If the shallow flag is given and is false, their contents are > compared. In either case, the results are cached for efficiency's > sake. > > --Jason > > > The documentation for filecmp.cmp is: > cmp( f1, f2[, shallow]) > Compare the files named f1 and f2, returning True if they seem > equal, False otherwise. > > Unless shallow is given and is false, files with identical > os.stat() signatures are taken to be equal. > > Files that were compared using this function will not be > compared again unless their os.stat() signature changes. > > Note that no external programs are called from this function, > giving it portability and efficiency. > This discussion seems to assume that Excel spreadsheets are stored in some canonical form so that two spreads with the same functionality are always identical on disk to the last bit. I very much doubt this is true (consider as an example the file properties that can be set). So really you need to define "equality". So far the tests discussed have concentrated on identifying identical files. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From robert.kern at gmail.com Thu Aug 30 13:57:11 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 30 Aug 2007 12:57:11 -0500 Subject: list index() In-Reply-To: <1188495863.242815.236900@o80g2000hse.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188495863.242815.236900@o80g2000hse.googlegroups.com> Message-ID: zzbbaadd at aol.com wrote: >> How could it not be an exception, in the plain English sense of the >> word? Most certainly you're asking for the index because you want to do >> something with the index. If the item is not found, you have no index, >> so that's a special case that must be handled separately. There is no >> logical difference between handling that special case in an except >> clause versus handling it with an if-branch. > > In my case of have done os.listdir() on two directories. I want to see > what files are in directory A that are not in directory B. > I have used exceptions in other languages and only do so on logic that > should never happen. Python is different than those languages. Exceptions are used much more frequently in Python and often for things that will *definitely* happen not just those things that shouldn't. -- 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 ldo at geek-central.gen.new_zealand Mon Aug 27 07:34:09 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 27 Aug 2007 23:34:09 +1200 Subject: Error with long running web spider References: <1187805496.980676.271830@l22g2000prc.googlegroups.com> Message-ID: In message <1187805496.980676.271830 at l22g2000prc.googlegroups.com>, Josh Volz wrote: > My problem is that I keep having an issue where the > program appears to freeze. Once this freezing happens the activity of > the program drops to zero. No exception is thrown or caught. The > program simply stops doing anything. It even stops printing out its > activity to stdout. What happens afterwards? Does it continue running as though nothing had happened? Throw an exception? >From the output that appears beforehand, does it look like the freeze is always happening in the same place? From bbxx789_05ss at yahoo.com Mon Aug 6 14:34:57 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 06 Aug 2007 11:34:57 -0700 Subject: udp, datagram sockets In-Reply-To: References: <1186416225.769753.307110@o61g2000hsh.googlegroups.com> Message-ID: <1186425297.323634.52370@57g2000hsv.googlegroups.com> On Aug 6, 11:05 am, Jean-Paul Calderone wrote: > > The network is probably dropping some of your data, causing the server > to never see the termination marker. > As far as I can tell, the output disproves that notion. If the termination character were somehow lost in transmission, then this statement: print "Received message:\n%s" % message[:-1] would produce the output: Received message: hell since the print statement chops off the last character of the received data. From pavlovevidence at gmail.com Fri Aug 31 03:32:53 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 31 Aug 2007 03:32:53 -0400 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> <1188534061.243009.89640@m37g2000prh.googlegroups.com> <1188539814.800466.6930@r23g2000prd.googlegroups.com> Message-ID: <46d7ce80$0$18840$4c368faf@roadrunner.com> On Thu, 30 Aug 2007 22:56:54 -0700, Russ wrote: >> Python really isn't suitable for in-flight controls > for various >> reasons, and mission critical concerns is a minor one (systems with > > Do you know anything about the FAA certification process for flight- > critical systems? I am not an expert on it, but I know it is very > expensive. If I am not mistaken, getting such code certified is more > expensive than developing it in the first place. Why would that be so > if, as you claim, "mission critical concerns is a minor one"? I made no such claim; you misconstrued what I wrote. I wrote that mission critical concerns are a minor reason why Python is not used, not that mission critical concerns were minor. As a matter of fact, FAA cert is a major pain, and they unit test the hell out of everything. I'm not aware of any reason why Python couldn't be certified if it passed the tests, but it likely wouldn't pass as easily as a compiled language. OTOH, spiffy features like design-by- contract aren't going to improve your chances of getting FAA cert, either. Carl Banks From larry.bates at websafe.com Mon Aug 6 16:04:08 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 06 Aug 2007 15:04:08 -0500 Subject: RTF 2 Tiff In-Reply-To: <1186427712.284976.207560@d30g2000prg.googlegroups.com> References: <1186427712.284976.207560@d30g2000prg.googlegroups.com> Message-ID: cjankowski at hbr-inc.com wrote: > Hi all, > I am trying to convert an RTF file to a Tiff image using Python. This > process will convert several hundred images daily. Currently I am > able to get the RTF file into a text format using Rtf2Txt.py, but I > loose the images contained in the RTF file. I have the same problem > when I convert to .HTML using Rtf2Html.py. I do not have a sample > that I can share because of HIPPA regulations. Can anyone please help > me? > > Thanks, > > Chris J. > Google turns up lots of solutions, but you didn't tell us what operating system you are running on. Most likely you will want to automate one of the off-the shelf solutions rather than trying to roll your own. -Larry From jmtulloss at gmail.com Thu Aug 9 05:00:27 2007 From: jmtulloss at gmail.com (Justin T.) Date: Thu, 09 Aug 2007 09:00:27 -0000 Subject: Stackless Integration Message-ID: <1186650027.043779.276520@i38g2000prf.googlegroups.com> Hi, I've been looking at stackless python a little bit, and it's awesome. My question is, why hasn't it been integrated into the upstream python tree? Does it cause problems with the current C-extensions? It seems like if something is fully compatible and better, then it would be adopted. However, it hasn't been in what appears to be 7 years of existence, so I assume there's a reason. Justin From pablo.mitchell at gmail.com Sat Aug 4 14:08:54 2007 From: pablo.mitchell at gmail.com (pablo.mitchell at gmail.com) Date: Sat, 04 Aug 2007 11:08:54 -0700 Subject: Efficient Rank Ordering of Nested Lists In-Reply-To: <1186158010.322959.47370@g4g2000hsf.googlegroups.com> References: <1186104049.022836.253470@e9g2000prf.googlegroups.com> <1186158010.322959.47370@g4g2000hsf.googlegroups.com> Message-ID: <1186250934.720441.12370@m37g2000prh.googlegroups.com> On Aug 3, 9:20 am, pyscottish... at hotmail.com wrote: > On Aug 2, 10:20 pm, "pablo.mitch... at gmail.com" > > > > wrote: > > A naive approach to rank ordering (handling ties as well) of nested > > lists may be accomplished via: > > > def rankLists(nestedList): > > def rankList(singleList): > > sortedList = list(singleList) > > sortedList.sort() > > return map(sortedList.index, singleList) > > return map(rankList, nestedList) > > > >>> unranked = [ [ 1, 2, 3, 4, 5 ], [ 3, 1, 5, 2, 4 ], [ -1.1, 2.2, > > 0, -1.1, 13 ] ] > > >>> print rankLists(unranked) > > > [[0, 1, 2, 3, 4], [2, 0, 4, 1, 3], [0, 3, 2, 0, 4]] > > > This works nicely when the dimensions of the nested list are small. > > It is slow when they are big. Can someone suggest a clever way to > > speed it up? > > Isn't there something wrong with the ordering? > > Pablo's answers are: > [ 1, 2, 3, 4, 5 ] == [0, 1, 2, 3, 4] correct > > [ 3, 1, 5, 2, 4 ] == [2, 0, 4, 1, 3] wrong? > > [ -1.1, 2.2, 0, -1.1, 13 ] == [0, 3, 2, 0, 4] wrong? > > Doing it in my head I get: > [ 3, 1, 5, 2, 4 ] == [ 1, 3, 0, 4, 2 ] > > [ -1.1, 2.2, 0, -1.1, 13 ] == [0, 3, 2, 1, 4] > > What gives? > > Did I misunderstand what "rank ordering (handling ties as well)" means? There are many ways to skin this cat. I am considering the following approach: http://en.wikipedia.org/wiki/Rank_order#Standard_competition_ranking_.28.221224.22_ranking.29 From no.0023 at gmail.com Sat Aug 11 20:50:57 2007 From: no.0023 at gmail.com (No.23) Date: Sun, 12 Aug 2007 00:50:57 +0000 Subject: Ligmail bug? Message-ID: <20070812005057.GA15805@ob41.org> #!/usr/bin/env python import libgmail from time import gmtime, strftime fp = open('/tmp/python.list', 'w') ga = libgmail.GmailAccount("No.0023 at gmail.com", "mypass") ga.login() result = self.ga.getMessagesByLabel('python.list', True) result_len = len(result) cnt = 0 if result_len: for thread in result: cnt += 1 thread_len = len(thread) print 'Thread: %d/%d Msg: %d %s' % (cnt, result_len, thread_len, thread.subject) for msg in thread: print ' Msg: %d/%d %s' % (msg.number, thread_len, msg.subject) source = msg.source.replace('\r','').lstrip() fp.write('From - ' + \ strftime("%a %b %d %H:%M:%S %Y", gmtime()) + '\n') fp.write(source) fp.write('\n\n') Thread: 1/1244 Msg: 7 \u003cb\>Deleting objects on the fly\u003c/b\> Msg: 1/7 Deleting objects on the fly Msg: 2/7 Re: Deleting objects on the fly Msg: 3/7 Re: Deleting objects on the fly Msg: 4/7 Re: Deleting objects on the fly Msg: 5/7 Re: Deleting objects on the fly Msg: 6/7 Re: Deleting objects on the fly Msg: 7/7 Re: Deleting objects on the fly Thread: 2/1244 Msg: 1 \u003cb\>A new french book on Python\u003c/b\> Msg: 1/1 A new french book on Python Thread: 3/1244 Msg: 14 \u003cb\>Destruction of generator objects\u003c/b\> Msg: 1/14 Destruction of generator objects Msg: 2/14 Re: Destruction of generator objects Msg: 3/14 Re: Destruction of generator objects Msg: 4/14 Re: Destruction of generator objects Msg: 5/14 Re: Destruction of generator objects Msg: 6/14 Re: Destruction of generator objects Msg: 7/14 Re: Destruction of generator objects Msg: 8/14 Re: Destruction of generator objects Msg: 9/14 Re: Destruction of generator objects Msg: 10/14 Re: Destruction of generator objects Msg: 11/14 Re: Destruction of generator objects Msg: 12/14 Re: Destruction of generator objects Msg: 13/14 Re: Destruction of generator objects Msg: 14/14 Re: Destruction of generator objects ...... Thread: 307/1244 Msg: 1 MailingLogger 3.2.0 Released! Msg: 1/1 MailingLogger 3.2.0 Released! Thread: 308/1244 Msg: 13 Why no maintained wrapper to Win32? Msg: 1/13 Why no maintained wrapper to Win32? Msg: 2/13 Re: Why no maintained wrapper to Win32? Msg: 3/13 Re: Why no maintained wrapper to Win32? Msg: 4/13 Re: Why no maintained wrapper to Win32? Msg: 5/13 Re: Why no maintained wrapper to Win32? Msg: 6/13 Re: Why no maintained wrapper to Win32? Msg: 7/13 Re: Why no maintained wrapper to Win32? Msg: 8/13 Re: Why no maintained wrapper to Win32? Msg: 9/13 Re: Why no maintained wrapper to Win32? Msg: 10/13 Re: Why no maintained wrapper to Win32? Msg: 11/13 Re: Why no maintained wrapper to Win32? Msg: 12/13 Re: Why no maintained wrapper to Win32? Msg: 13/13 Re: Why no maintained wrapper to Win32? Thread: 309/1244 Msg: 5 Encryption recommendation Msg: 1/5 Encryption recommendation Msg: 2/5 Re: Encryption recommendation Msg: 3/5 Re: Encryption recommendation Msg: 4/5 Re: Encryption recommendation Msg: 5/5 Re: Encryption recommendation Thread: 310/1244 Msg: 3 Simple question about logging module. Msg: 1/3 Simple question about logging module. Msg: 2/3 Re: Simple question about logging module. Msg: 3/3 Re: Simple question about logging module. Thread: 311/1244 Msg: 5 Plotting Images Msg: 1/5 Plotting Images Msg: 2/5 Re: Plotting Images Msg: 3/5 Re: Plotting Images Msg: 4/5 Re: Plotting Images Msg: 5/5 Re: Plotting Images Thread: 312/1244 Msg: 33 From D Thread: 313/1244 Msg: 4 get directory and file names Thread: 314/1244 Msg: 7 Compiling 2.5.1 on OpenBSD 4.1 Thread: 315/1244 Msg: 2 how to add a toolbar to a Frame using wxpython Thread: 316/1244 Msg: 1 create a toolbar + images using wxpython for windows Thread: 317/1244 Msg: 4 Pysqlite storing file as blob example Thread: 318/1244 Msg: 1 Nasm_with_C++_with_Python Thread: 319/1244 Msg: 2 interaction of 'with' and 'yield' Thread: 320/1244 Msg: 5 problems with logging module Thread: 321/1244 Msg: 5 win32 question in Python Thread: 322/1244 Msg: 6 File handle not being released by close Thread: 323/1244 Msg: 6 Replacing overloaded functions with closures. Thread: 324/1244 Msg: 1 Where can I get a complete user interface about pylibpcap? Thread: 325/1244 Msg: 7 making a variable available in a function from decoratorThread: 326/1244 Msg: 1 www.cerocom.com Thread: 327/1244 Msg: 6 OOP in Python book? Thread: 328/1244 Msg: 3 Help text embedding in C code? Thread: 329/1244 Msg: 16 128 or 96 bit integer types? Thread: 330/1244 Msg: 2 Re: yield keyword usage Thread: 331/1244 Msg: 11 How to write GUI and event separately in wxPython?? Thread: 332/1244 Msg: 2 ?????????Watch Satellite Channels on your PC - FREE!????????? Thread: 333/1244 Msg: 3 Database objects? Persistence? Sql Server woes Thread: 334/1244 Msg: 5 Bug? exec converts '\n' to newline in docstrings!? Thread: 335/1244 Msg: 1 RE: Free support for Python developers Thread: 336/1244 Msg: 1 Python-URL! - weekly Python news and links (Jul 30) Thread: 337/1244 Msg: 4 Making Gridded Widgets Expandable Thread: 338/1244 Msg: 3 pythonic parsing of URL Thread: 339/1244 Msg: 13 Detecting __future__ features Thread: 340/1244 Msg: 5 Events: The Python Way Thread: 341/1244 Msg: 4 Cross platform Python app deployment Thread: 342/1244 Msg: 4 encode/decode misunderstanding Thread: 343/1244 Msg: 1 Professional Grant Proposal Writing Workshop (September 2007: Simon Fraser University) Thread: 344/1244 Msg: 8 Hex editor display - can this be more pythonic? Thread: 345/1244 Msg: 1 import struct in Python z/OS Thread: 346/1244 Msg: 9 wxGlade: Who knows how to drive this application? Thread: 347/1244 Msg: 28 Any reason why cStringIO in 2.5 behaves different from 2.4? Thread: 348/1244 Msg: 15 Installing mod_python on mac os 10.4.7 Thread: 349/1244 Msg: 1 Xinetd & python server script. problem to get data from from client Thread: 350/1244 Msg: 2 ctypes:passing python class instances through c and backThread: 351/1244 Msg: 2 Bug in cPickle with packages and 'object' inherited class Thread: 352/1244 Msg: 1 What is the difference about "pycap" and "pylibpcap"? Thread: 353/1244 Msg: 1 Important new release (was: Crunchy security advisory) Thread: 354/1244 Msg: 5 Understanding mxODBC Insert Error Thread: 355/1244 Msg: 4 Split a string based on change of character Thread: 356/1244 Msg: 5 Python 2.5.1 can't find win32file? Thread: 357/1244 Msg: 2 interpreter in the background Thread: 358/1244 Msg: 5 Compiling python2.5.1 results in 3.5MB python lib? Thread: 359/1244 Msg: 7 problem with change to exceptions Thread: 360/1244 Msg: 1 Why Is This The Best Program Online ? Thread: 361/1244 Msg: 3 How to stop print printing spaces? Thread: 362/1244 Msg: 5 this must be a stupid question ... Thread: 363/1244 Msg: 2 Memory utilization (linux v. openbsd) Thread: 364/1244 Msg: 1 Test-driven design (was: Comparing Dictionaries) Thread: 365/1244 Msg: 1 Crunchy security advisory Thread: 366/1244 Msg: 1 http://MoneyCertain.com Thread: 367/1244 Msg: 1 ??????????????????FREE Satellite TV on your PC?????????????????? Thread: 368/1244 Msg: 1 great new site for IT GURUS - www.itkong.com Thread: 369/1244 Msg: 5 Tkinter -- Show Data in an Excel like Read-Only Grid Thread: 370/1244 Msg: 11 a simple string question Thread: 371/1244 Msg: 2 How to write a warning to my log file? Thread: 372/1244 Msg: 3 How to programmatically insert pages into MDI. Thread: 373/1244 Msg: 3 Tkinter program with a usable interpreter console Thread: 374/1244 Msg: 2 slow emails Thread: 375/1244 Msg: 2 Wikicodia - The code snippets wiki Thread: 376/1244 Msg: 6 Compile python with Mingw Thread: 377/1244 Msg: 10 removing items from a dictionary ? Thread: 378/1244 Msg: 4 Reading data from an ISA port Thread: 379/1244 Msg: 4 Removing certain tags from html files Thread: 380/1244 Msg: 6 Imported globals? Thread: 381/1244 Msg: 3 Packages Thread: 382/1244 Msg: 7 Factory pattern again Thread: 383/1244 Msg: 2 curses/urwid simple menu Thread: 384/1244 Msg: 7 adding a docstring to an instancemethod Traceback (most recent call last): File "/home/thoujean/bin/gmail.py", line 195, in client.archive_list(options.update, options.label) File "/home/thoujean/bin/gmail.py", line 142, in archive_list self.archive_label(label, update) File "/home/thoujean/bin/gmail.py", line 106, in archive_label for msg in thread: File "/usr/local/lib/python2.5/site-packages/libgmail-0.1.6-py2.5.egg/libgmail.py", line 1389, in __iter__ self._messages = self._getMessages(self) File "/usr/local/lib/python2.5/site-packages/libgmail-0.1.6-py2.5.egg/libgmail.py", line 1412, in _getMessages q = "in:anywhere") File "/usr/local/lib/python2.5/site-packages/libgmail-0.1.6-py2.5.egg/libgmail.py", line 429, in _parseSearchResult return self._parsePage(_buildURL(**params)) File "/usr/local/lib/python2.5/site-packages/libgmail-0.1.6-py2.5.egg/libgmail.py", line 402, in _parsePage items = _parsePage(self._retrievePage(urlOrRequest)) File "/usr/local/lib/python2.5/site-packages/libgmail-0.1.6-py2.5.egg/libgmail.py", line 383, in _retrievePage resp = self.opener.open(req) File "/usr/local/lib/python2.5/urllib2.py", line 374, in open response = self._open(req, data) File "/usr/local/lib/python2.5/urllib2.py", line 392, in _open '_open', req) File "/usr/local/lib/python2.5/urllib2.py", line 353, in _call_chain result = func(*args) File "/usr/local/lib/python2.5/urllib2.py", line 1109, in https_open return self.do_open(httplib.HTTPSConnection, req) File "/usr/local/lib/python2.5/urllib2.py", line 1076, in do_open raise URLError(err) urllib2.URLError: other information: Shell:~ >: uname -a OpenBSD ob41.org 4.1 ob41#0 i386 Shell:~ >: python Python 2.5 (r25:51908, Mar 8 2007, 20:46:47) [GCC 3.3.5 (propolice)] on openbsd4 Type "help", "copyright", "credits" or "license" for more information. >>> >>> import libgmail >>> print libgmail.Version 0.1.6 >>> -- Best Regards, No.23 ---- No.0023 at gmail.com From arkanes at gmail.com Thu Aug 30 14:04:13 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 30 Aug 2007 13:04:13 -0500 Subject: Is LOAD_GLOBAL really that slow? In-Reply-To: <1188495447.083333.271540@q4g2000prc.googlegroups.com> References: <1188495447.083333.271540@q4g2000prc.googlegroups.com> Message-ID: <4866bea60708301104vfb45180oe7e8c277730e6b57@mail.gmail.com> On 8/30/07, Rhamphoryncus wrote: > On Aug 29, 8:33 pm, Carsten Haese wrote: > > On Wed, 2007-08-29 at 19:23 -0600, Adam Olsen wrote: > > There is no loop overhead here, and after subtracting the function call > > overhead, I get 31 nanoseconds per local lookup and 63 nanoseconds per > > global lookup, so local lookups are just about twice as fast as global > > lookups. > > __builtins__ lookups are an extra dict lookup slower than just global variables, too. Don't forget those. > > True, whether this difference is significant does depend on how many > > name lookups your code makes and how much else it's doing, but if you're > > doing a lot of number crunching and not a lot of I/O, the difference > > might be significant. Also, even if using local names is only slightly > > faster than using globals, it's still not slower, and the resulting code > > is still more readable and more maintainable. Using locals is a win-win > > scenario. > > You get very small speed gains (assuming your code is doing anything > significant), for a lot of effort (trying out different options, > seeing if they're actually faster on different boxes.) The > readability cost is there, even if it is smaller than many of the > other obfuscations people attempt. If the speed gains were really > that important you should rewrite in C, where you'd get far greater > speed gains. > I've doubled the speed of a processing loop by moving globals lookups out of the loop. Rewriting in C would have taken at least a day, even with Pyrex, localizing the lookup took about 2 minutes. > So it only seems worthwhile when you really, *really* need to get a > slight speedup on your box, you don't need to get any more speedup > than that, and C is not an option. > It's not a huge optimization, but it's really easy to write if you don't mind adding fake kwargs to your functions. Just for the heck of it I also wrote a decorator that will re-write the bytecode so that any global that can be looked up at function definition will be re-written as a local (actually with LOAD_CONST). You can see it at http://code.google.com/p/wxpsvg/wiki/GlobalsOptimization. Disclaimer: While I've tested it with a variety of functions and it's never broken anything, I've never actually used this for anything except an intellectual exercise. Use at your own risk. > Fwiw, I posted this after developing yet another patch to optimize > global lookups. It does sometimes show an improvement on specific > benchmarks, but overall it harms performance. Looking into why, it > doesn't make sense that a python dictionary lookup can have less cost > than two simple array indexes, but there you go. Python dictionaries > are already damn fast. > I certainly believe that changes to pythons internals to try to make LOAD_GLOBAL itself faster can be difficult, with even "obvious" optimizations ending up slower. However, LOAD_FAST (and LOAD_CONST) are faster than LOAD_GLOBAL and, for the reason you just stated, is unlikely to change. From Shawn at Milochik.com Mon Aug 20 16:14:50 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Mon, 20 Aug 2007 16:14:50 -0400 Subject: reading a line in file In-Reply-To: <46C9F561.50405@jayloden.com> References: <93066C069973ED448DC2BCEA9C44A7383BE2B2@efmailx> <2dc0c81b0708201029k5909d919vcf0deebae74a79c7@mail.gmail.com> <93066C069973ED448DC2BCEA9C44A7383BE2B4@efmailx> <2dc0c81b0708201207p7f83f2e0l6de15fd70be252a5@mail.gmail.com> <93066C069973ED448DC2BCEA9C44A7383BE2B6@efmailx> <46C9F561.50405@jayloden.com> Message-ID: <2dc0c81b0708201314q727ca3a1s12bef74a25b20abc@mail.gmail.com> Everybody hates regexes. Except me. Discrimination! From kw at codebykevin.com Mon Aug 6 13:55:41 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 06 Aug 2007 13:55:41 -0400 Subject: wxWindows - incorrect path on installation? In-Reply-To: <1186422861.132899.50060@g4g2000hsf.googlegroups.com> References: <1186422861.132899.50060@g4g2000hsf.googlegroups.com> Message-ID: <46B7609D.2030404@codebykevin.com> frikk wrote: > This should be a very simple one, sorry! > > I installed wxWindows on my OS X box but I am unable to get my python > install to recognize the module. Unfortunately I don't know a whole > lot about where modules install to or how to configure python to see > them. IE: 'import wx' does not work - it says unknown module wx. > > Do I need to tweak a path variable or something? > > I have MacPython installed and the binary of wxWindows (wxPython) from > wxpython.com > > Thanks guys, > Blaine > What version of wxPython did you install? I don't think any of them are configured to work with Apple's system-installed Python--you would need to install Python 2.5 from the Python.org website. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From jjl at pobox.com Thu Aug 9 17:41:32 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 09 Aug 2007 21:41:32 GMT Subject: Screenscraping, in python, a web page that requires javascript? References: Message-ID: <87d4xw2xo4.fsf@pobox.com> Dan Stromberg - Datallegro writes: > Is there a method, with python, of screenscraping a web page, if that web > page uses javascript? Not pure CPython, no. > I know about BeautifulSoup, but AFAIK at this time, BeautifulSoup is for > HTML that doesn't have embedded javascript. It's not that BeautifulSoup is unhappy with JS, it's just that there's no support for executing the JS. There are some Java libraries that know how to execute JS embedded in web pages, which could be used from Jython: http://www.thefrontside.net/crosscheck http://htmlunit.sourceforge.net/ http://httpunit.sourceforge.net/ You can also automate a browser, but that still seems to be painful in one way or another. John From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Aug 3 04:20:59 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 03 Aug 2007 10:20:59 +0200 Subject: (no) fast boolean evaluation ? In-Reply-To: References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> Message-ID: <46b2e56b$0$18879$426a74cc@news.free.fr> Joshua J. Kugler a ?crit : > On Thursday 02 August 2007 15:19, Evan Klitzke wrote: >>> I discovered that boolean evaluation in Python is done "fast" >>> (as soon as the condition is ok, the rest of the expression is ignored). >> This is standard behavior in every language I've ever encountered. > > Then you've never programmed in VB (at least 6, don't know if .net still > does this). Nested IF statements. AAAAAAAAAAAAAAAAAAAACK! I do remember an even brain-deadiest language that not only didn't short-circuit boolean operators but also didn't have an "elif" statement... From robert.kern at gmail.com Wed Aug 22 13:44:50 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 22 Aug 2007 12:44:50 -0500 Subject: What Are These Import/From Statements about? In-Reply-To: References: Message-ID: W. Watson wrote: > Is there a single source that explains these statements? http://docs.python.org/tut/node8.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From cai.haibin at gmail.com Wed Aug 22 01:52:37 2007 From: cai.haibin at gmail.com (james_027) Date: Wed, 22 Aug 2007 05:52:37 -0000 Subject: for statement on empty iterable In-Reply-To: <7xejhw15r9.fsf@ruckus.brouhaha.com> References: <1187760507.951994.50310@q4g2000prc.googlegroups.com> <7xabsk3zgm.fsf@ruckus.brouhaha.com> <1187761270.713307.224570@i38g2000prf.googlegroups.com> <7xejhw15r9.fsf@ruckus.brouhaha.com> Message-ID: <1187761957.636211.107060@x40g2000prg.googlegroups.com> hi, > It sounds like you're just starting to learn the language... have you > read the online tutorial yet? That is a pretty easy introduction. > > See:http://python.org/doc/ > > Anyway, you can say > > for i in (1,2,3): > print i*5 > > to print 5, 10, and 15 on separate lines, for example. Yes i am new to python :). I am sorry I should be clarify myself ... for example l = ['j', 'a', 'm', 'e', 's'] for i in l # i want to know the nth number of times it has loop thru or something like counter? Thanks james From no at spam.com Thu Aug 2 15:11:20 2007 From: no at spam.com (Farshid Lashkari) Date: Thu, 02 Aug 2007 12:11:20 -0700 Subject: Catching SystemExit in C API code when embedding Python? In-Reply-To: <20070802141906.2581c099@cube.tz.axivion.com> References: <20070802141906.2581c099@cube.tz.axivion.com> Message-ID: Stefan Bellon wrote: > Hi all! > > I am embedding Python into a GUI application in a way that the GUI is > scriptable using Python. > > Now I have come to a problem that when the user puts a "sys.exit(0)" > into his script to end the script, not only the script is terminated, > but also the GUI application itself. This is not the intended behaviour. > > As in Python itself you can catch SystemExit, I think this should be > the way to go. But how do I catch this exception from within the C API? > > Thanks in advance for any hints. > Have a look at the following doc page for handling exceptions with the C api: http://docs.python.org/api/exceptionHandling.html Also, here is some sample code that will catch system exit exceptions: //Call python code ... //Check for system exit exception if(PyErr_Occurred()) { if(PyErr_ExceptionMatches(PyExc_SystemExit)) { //handle system exit PyErr_Clear(); } else { PyErr_Print(); } } From steve at holdenweb.com Thu Aug 2 12:22:39 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 02 Aug 2007 12:22:39 -0400 Subject: python 3.0, pywin32 and scipy In-Reply-To: <1186070475.659511.24130@q3g2000prf.googlegroups.com> References: <1186070475.659511.24130@q3g2000prf.googlegroups.com> Message-ID: vml wrote: > Hello, > > > I am trying to promote python in my job, my collegue only see matlab > and microsoft scripting language. > I understood that there willl be no backward compatibility between > python 2.x and 3.0, does it means that: > > - my script using pywin32 for the COM layer and scipy for the maths > won't work under 3.0 > - will we have the equivalent of pywin32 and scipy in python ? > > I will be incharge of designing a python module which will be a > 'matrix calculator' in our current software. Will it be compatible > with python 3.0 ? I guess no. > > What can I answer to my collegue who will say 'Python is changing and > the stuff you are doing now is useless'? > > how can I argue against matlab and c# ? > > thanks very much > Tell them that the majority of incompatibilities will be taken care of by an automated translation mechanism, and that the 2.X range will be maintained in parallel with the 3.X range, with features backported when it is feasible to do so, so there will be no *need* to migrate to 3.X until *at least* 3.1 (which will likely take us two years into the future). You might also remind them that Microsoft have continually broken backwards compatibility, and that this is a one-off deal that will make Python better and more consistent (not that they'll be interested in that, since they seem to have closed minds). Finally, look for Python users who have migrated from Matlab (of which there are many) and get their opinions on why. I have used C# on a couple of projects now and it's an OK language, but it can't hold a candle to Python, which is now firmly in the .NET environment with Microsoft's IronPython open source implementation. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From limodou at gmail.com Tue Aug 21 09:55:07 2007 From: limodou at gmail.com (limodou) Date: Tue, 21 Aug 2007 21:55:07 +0800 Subject: IDE for Python In-Reply-To: <1187698999.545439.322600@k79g2000hse.googlegroups.com> References: <1187698999.545439.322600@k79g2000hse.googlegroups.com> Message-ID: <505f13c0708210655g36ce7cf1m2cb089ce974983e1@mail.gmail.com> On 8/21/07, king kikapu wrote: > On Aug 21, 12:00 pm, Joel Andres Granados > wrote: > > Hello list: > > > > I have tried various times to use an IDE for python put have always been > > disapointed. > > > I have also tried a lot of them (IDEs) in the last year. I was finally > happy with Eclipse/Pydev but i was always wanted a more "true" IDE for > Python. > I think i found it in Eric4 http://www.die-offenbachs.de/eric/index.html > You can download from here http://www.riverbankcomputing.co.uk/pyqt/download.php > (binary installer for Windows that contains Eric and PyQt) > and have a look at it! > Maybe someone can try UliPad, I just release 3.7 version a few days before. -- I like python! UliPad <>: http://code.google.com/p/ulipad/ My Blog: http://www.donews.net/limodou From nepbabucxspamfree at yahoo.ca Tue Aug 21 08:38:24 2007 From: nepbabucxspamfree at yahoo.ca (Bikal KC) Date: Tue, 21 Aug 2007 22:08:24 +0930 Subject: C# and Python In-Reply-To: <1187693349.890687.203900@50g2000hsm.googlegroups.com> References: <1187690505.903506.79690@d55g2000hsg.googlegroups.com> <1187693349.890687.203900@50g2000hsm.googlegroups.com> Message-ID: <46cadcb7$1_4@news.chariot.net.au> >From Eric CHAO [accidently sent to me]: Maybe you could try IronPython. It's another implement in .NET platform. Not 100% compatible but for sorting, that's ok. I think it's a better way to use GUI that .NET provide. And if you download VS 2005 SDK, there is many demo projects about IronPython. On 8/21/07, Bikal KC wrote: > > subeen wrote: > > >> > > When the user clicks Quick Sort button, the quicksort.py will be >> > > called and it will sort the numbers. > > > > One way to do this: > > In your C# app, have the mouse click event handler call python > > interpreter "/path/to/python /path/to/quicksort.py". Make quicksort.py > > write to a file the result. After the quicksort.py finishes, read the > > file from your normal C# app. > > > > Cheers. > > -- > > http://mail.python.org/mailman/listinfo/python-list > > From ldo at geek-central.gen.new_zealand Fri Aug 31 19:33:32 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 01 Sep 2007 11:33:32 +1200 Subject: Is there a simple way to exit a while loop on keystroke? References: <1188578827.809840.90100@r29g2000hsg.googlegroups.com> Message-ID: In message <1188578827.809840.90100 at r29g2000hsg.googlegroups.com>, gsxg wrote: > I am new to python, and have written a simple program to read a port > via telnet. I would like it to run until any key is pressed. Did you mean "telnet" or did you mean "local terminal"? For a local terminal, the following demo script should give you a starting point: #!/usr/bin/python import sys import select import termios import tty timeout = 0.0 # nonzero to wait that long for keypress save_attrs = termios.tcgetattr(sys.stdin.fileno()) # save terminal settings for restoration--note that this script # doesn't currently trap CTRL/C, so settings will not be properly # restored if that is hit tty.setcbreak(sys.stdin.fileno()) # or can use setraw to block CTRL/C while True : (input_ready, _, _) = select.select((sys.stdin,), (), (), timeout) if sys.stdin in input_ready : break #end if sys.stdout.write("Running...\n") #end while termios.tcsetattr(sys.stdin.fileno(), termios.TCSAFLUSH, save_attrs) sys.stdout.write("Finished.\n") From philippe.martin at att.net Mon Aug 27 00:59:54 2007 From: philippe.martin at att.net (hg) Date: Mon, 27 Aug 2007 04:59:54 GMT Subject: ANN: SCF released to GPL In-Reply-To: References: Message-ID: hg wrote: > Dear all, > > I am releasing much of my work including SCF (Cross platform Smart Card > library & Tools written in Python) to the GPL license. > > If interested, go to http://www.SnakeCard.com/Source.html > > I am moving the doc to doxygen and cleaning up the code, so what you'll see > there will change in the course of the next few weeks - basically can only > get meaningful info on the classes hierarchy at this stage. > I am looking for a free subversion server resource to put the code ... if > you know of any. > > Some of the work there will be windows-only related (GINA, activeX > components ... and not coded in Python) and the applets JavaCard and > BasicCard ... I'm releasing these during the next few days. > > Regards, > > hg PS: I apologize for the "spam" ... I just changed ISP .. and my initial post did not make it (or so I thought) ... sorry. From rcdailey at gmail.com Sat Aug 11 18:59:39 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Sat, 11 Aug 2007 17:59:39 -0500 Subject: Binary, Hex, and Decimal string conversions Message-ID: <496954360708111559s1cef4212pabd14e95b27435ea@mail.gmail.com> Hi, I was wondering if there is a built in module that supports conversion in any direction between Binary, Hex, and Decimal strings? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From info at thegrantinstitute.com Wed Aug 8 06:06:11 2007 From: info at thegrantinstitute.com (Anthony Jones) Date: 08 Aug 2007 03:06:11 -0700 Subject: Professional Grant Proposal Writing Workshop (September 2007: Simon Fraser University) Message-ID: <20070808030605.7DDE7E991CD85D5A@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From JYOUNG79 at kc.rr.com Fri Aug 3 11:22:05 2007 From: JYOUNG79 at kc.rr.com (JYOUNG79 at kc.rr.com) Date: Fri, 03 Aug 2007 10:22:05 -0500 Subject: xlrd question Message-ID: When running 'python setup.py install' to install items for xlrd to work, does anybody know what items are installed and where items are installed at on a Mac (OS 10.4)? I'm assuming it mainly uses things out of the xlrd folder, but was curious if it copies files to other locations. Thanks. Jay From walterbyrd at iname.com Tue Aug 28 14:49:07 2007 From: walterbyrd at iname.com (walterbyrd) Date: Tue, 28 Aug 2007 11:49:07 -0700 Subject: Is it reasonably easy easy to something like this with python? Message-ID: <1188326947.527698.245770@r23g2000prd.googlegroups.com> This is made with a php5 framework called qcodo. http://examples.qcodo.com/examples/dynamic/inline_editing.php With qcodo it's easy to make grids that are sortable and inline editable. Qcodo grids work from the database - not an xml table or array. Qcodo handles complex data relations, and fairly large datadabes. I like python better than php, but I don't know of any python tools to create these sorts of grids. From no.reply at here.com Sun Aug 19 20:33:36 2007 From: no.reply at here.com (Anonymous) Date: Mon, 20 Aug 2007 01:33:36 +0100 Subject: Python question (PyNoob) Message-ID: <3uOdnbA4Bc27fFXbnZ2dnUVZ8vidnZ2d@bt.com> I have exp with C/C++ (and a few other langs). I want to use Python to start doing the ff: 1). Data Munging (text processing) - instead of Perl 2). Automating my build process 3). (Possibly) some web data retrieval jobs Can anyone point me to resurces/possibly scripts that can get me up to speed (to do these 3 things) ASAP, without having to learn the basics of programming? From Andy.cheesman at bristol.ac.uk Thu Aug 2 12:16:15 2007 From: Andy.cheesman at bristol.ac.uk (Andy Cheesman) Date: Thu, 02 Aug 2007 17:16:15 +0100 Subject: beginner in python In-Reply-To: References: Message-ID: <46B2034F.10703@bristol.ac.uk> It looks like you are doing some sort of molecular science thing. Have you come across openbabel and the python bindings pybel (http://openbabel.sourceforge.net/wiki/Python#Pybel). I don't know how well they work but they might save you some effort. Also, check out pymol,(http://pymol.sourceforge.net/) they might have some of the functionality which you desire already coded! HTH Andy Steve Holden wrote: > Beema shafreen wrote: >> hi everybody, >> I am beginner in python >> I have to calculate the euclidean distance between the atoms from a pdb >> file >> i have written the the code and its shows me some error , >> the code: >> import re >> import string >> import math >> ab =[] >> x_value = [] >> y_value = [] >> z_value = [] >> fh = open("1K5N.pdb",'r') >> for atom in fh.readlines(): >> a = atom.strip() >> pattern= re.compile('^ATOM.*') >> atom_file= pattern.search(a) >> if atom_file: >> atom_data = atom_file.group() >> x_coordinate = atom_data[31:38] >> y_coordinate = atom_data[39:46] >> z_coordinate = atom_data[47:54] >> x_value.append(x_coordinate) >> y_value.append(y_coordinate) >> z_value.append(z_coordinate) >> for x in range(len(x_value)): >> x_co = float(x_value[x])-float(x_value[x+1]) >> y_co = float(y_value[x])-float(y_value[x+1]) >> z_co = float(z_value[x])-float(z_value[x+1]) >> data = math.sqrt(x_co)*(x_co)+(y_co)*(y_co)+(z_co)*(z_co) >> print data >> ~ >> and the error ,message >> File "pdb_fetching.py", line 22, in ? >> x_co = float(x_value[x])-float(x_value[x+1]) >> IndexError: list index out of range >> >> >> can you suggest me the mistake i have made >> > suppose you have an x_value list of length 6. Valid indexes go from 0 to > 5. Then x is going to start at 0 and go up to 5. The last time around > the loop the expression "x_value[x+1]" is going to try and use 6 as an > index, thus trying to address past the end of the list. > > Since the data values are the RMS differences between successive points, > there are only five differences for a six-element list. > > Try using > > for x in range(len(x_value)-1): > > instead. > > By the way, you presented your question very well - all necessary > information was there, and you didn't put in any mistaken guesses about > what might be going wrong. Well done, and welcome to Python! You will > find you can learn it very quickly. > > regards > Steve From shawn.o.weekly at gmail.com Mon Aug 6 14:01:16 2007 From: shawn.o.weekly at gmail.com (bhamdeveloper) Date: Mon, 06 Aug 2007 11:01:16 -0700 Subject: can't import SimpleXMLRPCDisptacher from SimpleXMLRPCServer Message-ID: <1186423276.861160.63610@g4g2000hsf.googlegroups.com> from my server I can't import SimpleXMLRPCDispatcher. please see http://intertubewaypoint.com/metaweblog/ for the stacktrace/error message. This onle happens on my server; I am trying to integrate the metaweblog api into my blog and it is barfing when trying to get that dispatcher. Anyone seen this and have a quick fix? From theller at ctypes.org Thu Aug 16 11:39:30 2007 From: theller at ctypes.org (Thomas Heller) Date: Thu, 16 Aug 2007 17:39:30 +0200 Subject: ctypes and C99 complex numbers In-Reply-To: <1187266067.24753.12.camel@wheeler.hlphys.uni-linz.ac.at> References: <1187266067.24753.12.camel@wheeler.hlphys.uni-linz.ac.at> Message-ID: Eugen Wintersberger schrieb: > Hi there > I want to use ctypes in connection with C functions that use complex > datatypes defined in the C99 standard. Does someone know a simple way > how to implement this? Are there any plans to integrate the C99 complex > data types in the ctypes module? I have investigated the complex data types a bit and came to the conclusion that libffi (which ctypes is based upon) would have to be extended to support these complex types. I have not looked into the newer libffi sources to find out if this support already has been added, ctypes uses an older version of libffi. By experimenting I found out that on some systems (x86 linux and x86_64 linux) I could 'emulate' the complex type by defining a structure: class Complex(Structure): _fields_ = [("real", c_double), ("imag", c_double)] def _get(self): .... def _set(self, value): .... value = property(_get, _set) but I'm afraid this is not really portable to other platforms. Thomas From DustanGroups at gmail.com Tue Aug 21 12:44:23 2007 From: DustanGroups at gmail.com (Dustan) Date: Tue, 21 Aug 2007 16:44:23 -0000 Subject: How to optimise this code? In-Reply-To: References: <1187711974.29800.1206519007@webmail.messagingengine.com> Message-ID: <1187714663.211663.90430@o80g2000hse.googlegroups.com> On Aug 21, 11:20 am, "J. Cliff Dyer" wrote: > I suspect lambda might be your friend here too for making the code less > verbose, though I never really got the hang of lambdas, even though my > first programming experience was a scheme class way back when.... Ah well. That's because it's not the same thing. From aleax at mac.com Fri Aug 31 11:56:21 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 31 Aug 2007 08:56:21 -0700 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188495863.242815.236900@o80g2000hse.googlegroups.com> <1i3ob5k.dm3jmoqx1z68N%aleax@mac.com> <1188530557.550119.27260@q3g2000prf.googlegroups.com> Message-ID: <1i3pcju.j2fvej1056nqpN%aleax@mac.com> mensanator at aol.com wrote: ... > Why wouldn't "the one obvious way" be: > > def inAnotB(A, B): > inA = set(os.listdir(A)) > inBs = set(os.listdir(B)) > return inA.difference(inBs) If you want a set as the result, that's one possibility (although possibly a bit wasteful as you're building one more set than necessary); I read the original request as implying a sorted list result is wanted, just like os.listdir returns (possibly sorted in case-independent order depending on the underlying filesystem). There's no real added value in destroying inA's ordering by making it a set, when the list comprehension just "naturally keeps" its ordering. Alex From fabioztessitore at libero.it Wed Aug 29 18:09:19 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 29 Aug 2007 22:09:19 GMT Subject: cgi References: <46d5c01b$0$36438$4fafbaef@reader5.news.tin.it> <46d5daa7$0$36441$4fafbaef@reader5.news.tin.it> Message-ID: <46d5ee8f$0$36445$4fafbaef@reader5.news.tin.it> Il Wed, 29 Aug 2007 23:11:53 +0200, Gigs_ ha scritto: > Gigs_ wrote: >> Fabio Z Tessitore wrote: >>> Are you sure your script is in the right dir? >>> >>> On my home computer, php script will work in /var/www but my python >>> script need an other dir to work properly (i don't remember which now >>> ;-)) >>> >>> bye >>> >> i think that it is in right dir because other script in same dir work. >> dir is: cgi-bin > > > sorry................... > > > > for waisting your time, > somehow in html page in form i forgot to put right script addr > > > > thx anyway > > > work now no prob, bye From http Mon Aug 6 06:11:13 2007 From: http (Paul Rubin) Date: 06 Aug 2007 03:11:13 -0700 Subject: Misleading wikipedia article on Python 3? References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> Message-ID: <7xzm15q8fy.fsf@ruckus.brouhaha.com> Carsten Haese writes: > For instance, if you never use print statements in your code, you won't > notice that print is becoming a function. If you do, you'll have to make > appropriate accommodations. Why on earth did they make this change? It just seems gratuitous. Is the assert statement also being changed? Are they going to update all the docs that say that the yield statement works like the print statement? From lisajones22 at gmail.com Mon Aug 13 11:54:11 2007 From: lisajones22 at gmail.com (Lisa Jones) Date: Mon, 13 Aug 2007 08:54:11 -0700 Subject: =?utf-8?B?4pa6RU5KT1kgZnJlZSBzYXRlbGxpdGUgdHYgb24geW91ciBwY+KXhA==?= Message-ID: <1187020451.624272.28410@e9g2000prf.googlegroups.com> The New Way To Enjoy Satellite TV on your PC! ? Watch all your favorite shows on your Computer from anywhere in the World! ? Save 1000's of $$$ over many years on cable and satellite bills ? Plus Get FREE Unlimited Downloads Movies, MP3s Music, etc !!! ? INSTANT DOWNLOAD For More Details: http://tvonpc.freeweb7.com From mcknight0219 at gmail.com Tue Aug 28 10:10:47 2007 From: mcknight0219 at gmail.com (Jimmy) Date: Tue, 28 Aug 2007 07:10:47 -0700 Subject: wxpython:how to minimize to taskbar Message-ID: <1188310247.587456.103440@i13g2000prf.googlegroups.com> I'm kinda newbie to python and wxPython. Now I'm confronting a thorny problem: how can I make my program minimize to the taskbar represented as an ico, and when there is some message from network coming, it will pop out? From ptmcg at austin.rr.com Mon Aug 13 13:40:57 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 13 Aug 2007 10:40:57 -0700 Subject: Python in Chinese Message-ID: <1187026857.622808.80470@19g2000hsx.googlegroups.com> Back in May, there was quite an extensive discussion of whether or not Python should support Unicode identifiers (with the final result being that this would be supported in Python 3). In my periodic googling for pyparsing users, I stumbled upon Zhpy, a preprocessor that renders on the fly Chinese Python keywords and indentifiers written using traditional Chinese characters into ASCII counterparts, and then executes the resulting script. I was very intrigued at the idea, and I thought back to Martin v. L?wis's PEP. The Zhpy approach will work with current versions of Python (going back to 2.3, since pyparsing requires that version). You can view examples at the pyparsing "Who's Using Pyparsing" wiki page - http://pyparsing.wikispaces.com/WhosUsingPyparsing#Zhpy. Given the breadth of response to Martin v. L?wis's post, I'm curious as to what the reaction might be to something like Zhpy. -- Paul From arnodel at googlemail.com Thu Aug 30 15:13:46 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 30 Aug 2007 19:13:46 -0000 Subject: subclassing Python types In-Reply-To: <1188500442.434722.157350@q5g2000prf.googlegroups.com> References: <1188500442.434722.157350@q5g2000prf.googlegroups.com> Message-ID: <1188501226.443493.94720@i13g2000prf.googlegroups.com> On Aug 30, 8:00 pm, zzbba... at aol.com wrote: > I have read that you can derive from the base classes such as str, > list, dict. > > I guess this would look like: > > def MyString(str): > def MyList(list): > def MyDict(dict): You mean class MyString(str): ... > How do you access the data that is contained in the super class? The same way that you access plain strings, lists or dicts: use the methods of the super class. HTH PS: it is not so often a good idea to derive a class from these types. -- Arnaud From Shawn at Milochik.com Tue Aug 14 12:59:44 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Tue, 14 Aug 2007 12:59:44 -0400 Subject: Simple python iteration question In-Reply-To: <20070814163430.GJ22017@lass.lfod.us> References: <20070814163430.GJ22017@lass.lfod.us> Message-ID: <2dc0c81b0708140959m6f68fa54u1303f23e02ae40a@mail.gmail.com> > Use the enumerate() builtin. > > >>> l = ['a', 'b', 'c'] > >>> for i, v in enumerate(l): > ... print i, v > ... > 0 a > 1 b > 2 c > > -- Just for my own sanity: Isn't this the third response advocating the use of enumerate()? Did the other responses not get through, or was this a time-delay thing? Thanks, Shawn From __peter__ at web.de Wed Aug 8 02:52:20 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 08 Aug 2007 08:52:20 +0200 Subject: Seek the one billionth line in a file containing 3 billion lines. References: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> Message-ID: Sullivan WxPyQtKinter wrote: > I have a huge log file which contains 3,453,299,000 lines with > different lengths. It is not possible to calculate the absolute > position of the beginning of the one billionth line. Are there > efficient way to seek to the beginning of that line in python? > > This program: > for i in range(1000000000): > f.readline() > is absolutely every slow.... > > Thank you so much for help. That will be slow regardless of language. However n = 10**9 - 1 assert n < sys.maxint f = open(filename) wanted_line = itertools.islice(f, n, None).next() should do slightly better than your implementation. Peter From zyzhu2000 at gmail.com Thu Aug 2 10:55:28 2007 From: zyzhu2000 at gmail.com (beginner) Date: Thu, 02 Aug 2007 14:55:28 -0000 Subject: Awkward format string In-Reply-To: <46b196aa$0$18885$426a74cc@news.free.fr> References: <1185984697.605529.157110@g12g2000prg.googlegroups.com> <46b196aa$0$18885$426a74cc@news.free.fr> Message-ID: <1186066528.232750.98700@g12g2000prg.googlegroups.com> On Aug 2, 3:32 am, Bruno Desthuilliers wrote: > beginner a ?crit : > > > Hi, > > > In order to print out the contents of a list, sometimes I have to use > > very awkward constructions. For example, I have to convert the > > datetime.datetime type to string first, construct a new list, > > s/list/tuple/ > > > and then > > send it to print. The following is an example. > > > x=(e[0].strftime("%Y-%m-%d"), e[1].strftime("%Y-%m-%d"))+e[2:] > > print >>f, "%s\t%s\t%d\t%f\t%f\t%f\t%d" % x > > > e is a tuple. x is my new tuple. > > > Does anyone know better ways of handling this? > > >>> from datetime import datetime > >>> dt = datetime(2007,8,2) > >>> dt > datetime.datetime(2007, 8, 2, 0, 0) > >>> str(dt) > '2007-08-02 00:00:00' > >>> "%s" % dt > '2007-08-02 00:00:00' > >>> dt.date() > datetime.date(2007, 8, 2) > >>> str(dt.date()) > '2007-08-02' > > Do you really need datetime objects ? If not, using date objects instead > would JustWork(tm) - at least until someone ask you to use another date > format !-) > > Else, and since you seem to have a taste for functional programming: > > from datetime import datetime > from functools import partial > > def iformat(e): > fake = lambda obj, dummy: obj > for item in e: > yield getattr(item, 'strftime', partial(fake, item))('%Y-%m-%d') > > e = (datetime(2007,8,1),datetime(2007,8,2) ,42, 0.1, 0.2, 0.3, 1138) > print tuple(iformat(e)) > print "%s\t%s\t%d\t%f\t%f\t%f\t%d" % tuple(iformat(e)) Thanks. The 'functional' taste is still under development. It hasn't reached production quality yet. :-) From grante at visi.com Mon Aug 20 14:18:14 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 20 Aug 2007 18:18:14 -0000 Subject: Hot subject: a good python editor and/or IDE? References: Message-ID: <13cjmn6htpph7ef@corp.supernews.com> On 2007-08-20, Dave Cook wrote: > On 2007-08-19, S?bastien wrote: > >> I am currently using Eclipse+PyDev when developping Python projects but >> I lack a fast, simple editor for tiny bit of scripts. So here is my >> question: what is, for you, the current best ( but still kind of light! >> ) Python editor/IDE ? A tiny precision, I am on Ubuntu so I am looking >> for a linux compatible editor. > > JED has a nice python mode for fast, simple editing. I second the Jed nomination... -- Grant Edwards grante Yow! I want EARS! I want at two ROUND BLACK EARS visi.com to make me feel warm 'n secure!! From cjw at sympatico.ca Fri Aug 17 17:32:09 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 17 Aug 2007 17:32:09 -0400 Subject: sub-classing the types in the builtin module datetime In-Reply-To: <1187294329.082872.230800@l22g2000prc.googlegroups.com> References: <1187294329.082872.230800@l22g2000prc.googlegroups.com> Message-ID: <46C613D9.5070009@sympatico.ca> attn.steven.kuo at gmail.com wrote: [My question snipped] > > > > This problem arises when you change the function signature of __new__. > I'm a little unclear as to why but it seems for the classmethods > (thosed marked with the METH_CLASS flag in the C source code), you > need to arrange to bypass the normal method resolution (I used a > metaclass > to do this): > > > > import datetime > > class Date(datetime.datetime): > pass > > class FixClassMethods(type): > def __init__(cls, classname, bases, classdict): > # add strptime if using Python 2.5 > flagged_as_meth_class = ('today', 'now', 'fromtimestamp', > 'fromordinal', 'now', 'utcnow', 'utcfromtimestamp', 'combine') > for meth in flagged_as_meth_class: > setattr(cls, meth, getattr(datetime.datetime, meth)) > > class DateChangesNewSignature(datetime.datetime): > @staticmethod > def str2ymd(strval): > yyyy, mm, dd = (int(substr) for substr in (strval[:4], > strval[4:6], strval[6:])) > return yyyy, mm, dd > > def __new__(cls, strval): > yyyy, mm, dd = DateChangesNewSignature.str2ymd(strval) > return super(DateChangesNewSignature,cls).__new__(cls, yyyy, > mm, > dd) > def __init__(self, strval): > yyyy, mm, dd = DateChangesNewSignature.str2ymd(strval) > super(DateChangesNewSignature, self).__init__(yyyy, mm, > dd) > > class DLast(DateChangesNewSignature): > __metaclass__ = FixClassMethods > > f = Date(2007,07,07) > print f > print f.today() > > f2 = DateChangesNewSignature("20070707") > print f2 > try: > print f2.today() > except TypeError, e: > print str(e) > print "Uh?" > > > f3 = DLast("20070707") > print f3 > print f3.today() > > > I get: > > 2007-07-07 00:00:00 > 2007-08-16 12:57:41.480679 > 2007-07-07 00:00:00 > __new__() takes exactly 2 arguments (9 given) > Uh? > 2007-07-07 00:00:00 > 2007-08-16 12:57:41.483104 > > > -- > Hope this helps, > Steven > Steven, Thanks, you provide an elegant solution to the datetime problem I raised. I like the illustration of metaclass usage you have have given, it's something I have had trouble grasping. You handle the examples I gave. However, on reflection,I feel that ('today', 'now', 'fromtimestamp', 'fromordinal', 'now', 'utcnow', 'utcfromtimestamp', 'combine') are completely inappropriate as methods and that they should have been set up as functions of datetime and not as methods of datetime.datetime. The difficulty I have in adopting your approach is that it would be difficult for the reader to comprehend the code. My feeling is that it should be possible to change a signature using simple Python approaches. I'll puzzle some more. Thanks again. Colin W. From arkanes at gmail.com Fri Aug 17 10:13:51 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 17 Aug 2007 09:13:51 -0500 Subject: (sort of) deterministic timing in Python In-Reply-To: <017501c7e0a6$cff9dc40$03000080@hendrik> References: <1i2si8h.1qc8f77i68gyeN%johnmfisher@comcast.net> <7xlkcbgto6.fsf@ruckus.brouhaha.com> <017501c7e0a6$cff9dc40$03000080@hendrik> Message-ID: <4866bea60708170713x402112d6o23333db400c5bc6c@mail.gmail.com> On 8/17/07, Hendrik van Rooyen wrote: > > "Paul Rubin" wrote: > > > >johnmfisher at comcast.net (John Fisher) writes: > >> mark start time > >> start event > >> event finishes > >> count time until next interval > >> start second event? > >> > >> rather than this: > >> > >> start event > >> event finishes > >> sleep for interval > >> start second event > >> ... > >> So how do I accomplish this in Python with a minimum of labour? > > > >Normally I'd use something like: > > > > from time import time > > > > t0 = time() > > start event ... event finishes > > t1 = time() > > elapsed = t1 - t0 > > sleep(interval - elapsed) > > start second event ... > > > >Am I missing something? > > Not much - only beware of cases when elapsed is greater than > interval - not sure what time.sleep(negative_number) does. > On Windows 2k3, Python 2.5 it sleeps forever (or almost forever? Maybe a signed/unsigned thing) so yeah, be careful of it. From paul at carlislegroup.com Mon Aug 6 09:20:30 2007 From: paul at carlislegroup.com (Paul Mansour) Date: Mon, 06 Aug 2007 06:20:30 -0700 Subject: (Re)announcing APL 2007 In-Reply-To: <5hnkb3F3hus4jU1@mid.individual.net> References: <5hnkb3F3hus4jU1@mid.individual.net> Message-ID: <1186406430.744134.298400@x35g2000prf.googlegroups.com> On Aug 5, 11:54 pm, Mike Kent wrote: > APL 2007 conference on Array Programming > > co-located with OOPSLA 2007 > > Sponsor: ACM SIGAPL > > Where: Montreal > > When: October 21 (tutorials) > October 22/23 (main conference program) APL2007 Roll Call: Is anyone going to this? I'm thinking about going, but I don't want to the only one to show up, as in San Diego. From wildemar at freakmail.de Thu Aug 23 20:18:57 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 24 Aug 2007 02:18:57 +0200 Subject: introspection and functions In-Reply-To: <46CDA178.4060700@bigfoot.com> References: <1187819949.515982.15450@r23g2000prd.googlegroups.com> <20070823104810.6054520f.ayaz@dev.null> <46CDA178.4060700@bigfoot.com> Message-ID: <46CE23F1.9010202@freakmail.de> Ricardo Ar?oz wrote: > Ayaz Ahmed Khan wrote: > >> "James Stroud" typed: >> >>> py> def doit(a, b, c, x=14): >>> ... pass >>> ... >>> py> doit.func_code.co_argcount >>> 4 >>> py> doit.func_code.co_varnames >>> ('a', 'b', 'c', 'x') >>> py> doit.func_defaults >>> (14,) >>> >> Neat. >> > How do you know the 14 corresponds to x ? > Well, there is one optional argument (len(doit.func_defaults)==1) and those *must* come after mendatory arguments. More generally: If a function has n optional args, they're the n last ones. There is never any ambiguity. /W From dtgeadamo at yahoo.com Sun Aug 12 08:44:58 2007 From: dtgeadamo at yahoo.com (Viewer T.) Date: Sun, 12 Aug 2007 05:44:58 -0700 Subject: Database intensive application In-Reply-To: <1186895306.237395.189530@z24g2000prh.googlegroups.com> References: <1186895306.237395.189530@z24g2000prh.googlegroups.com> Message-ID: <1186922698.918184.31210@x40g2000prg.googlegroups.com> On Aug 11, 10:08 pm, Rohit wrote: > I am a novice. I want to know whether Python can be used to develop > client/server database and web applications like .NET. Which is the > best book/source to learn Python? O'reilly's Learning Python by David Ascher and Mike Lutz has a reputation for being the best book for learning Python and Yes, Python has awesome database support and can satisfy almost all database needs. From bert.heymans at gmail.com Fri Aug 24 09:09:28 2007 From: bert.heymans at gmail.com (Bert Heymans) Date: Fri, 24 Aug 2007 06:09:28 -0700 Subject: Regular expression use In-Reply-To: References: Message-ID: <1187960968.808605.20050@i38g2000prf.googlegroups.com> Nick, In "Mastering Regular Expressions" by Jeffrey E. F. Friedl your question is answered in the first 6 chapters. Seriously, that's what it takes. It's a really good book. Cheers Bert On Aug 24, 12:58 pm, n... at cus.cam.ac.uk (Nick Maclaren) wrote: > For reasons that I won't explain, as they are too complicated > and not terribly relevant, I am interested in discovering what > people actually use regular expressions for. Not the subject > domain, but the construction of the regular expressions. > > I know about computer scientists and parsing, and I know about > the use of relatively simple ones for things like extracting > HTML links from Web pages. But I don't have much feel for the > (probably rare but difficult) uses of more complex ones for > other purposes. I have heard of several such uses, but don't > have an overall idea of what is going on. > > Any pointers appreciated, to more-or-less anything. > > Regards, > Nick Maclaren. From jcd at sdf.lonestar.org Tue Aug 21 12:20:35 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 21 Aug 2007 12:20:35 -0400 Subject: How to optimise this code? In-Reply-To: <1187711974.29800.1206519007@webmail.messagingengine.com> References: <1187711974.29800.1206519007@webmail.messagingengine.com> Message-ID: <46CB10D3.8040604@sdf.lonestar.org> David N Montgomery wrote: > class testCase: > def __init__(self, tc): > if tc == 1:self.testCase1() > if tc == 2:self.testCase2() > if tc == 3:self.testCase3() > if tc == 4:self.testCase4() > if tc == 5:self.testCase5() > if tc == 6:self.testCase6() > > def testCase1(self): > print "tc1" > > def testCase2(self): > print "tc2" > > def testCase3(self): > print "tc3" > > def testCase4(self): > print "tc4" > > def testCase5(self): > print "tc5" > > def testCase6(self): > print "tc6" > > > def testCaseX(self): > print "tcX" > > totalNumberOfTestCases = 6 > x = 0 > while x <= totalNumberOfTestCases: > x += 1 > testCase(x) > > > This template code is working, but I envisage having 100+ test cases and > am concerned about my useage of if statements. I would be grateful for > any pointers as to how I can run all tests cases, regardless of how > many, in a more efficient manner. > > Thank you in advance. > try binding each function to an element of a list, and then processing across the list. This might look like: def testCase1: return "tc1" def testCase2: return "tc2" testCaseList = [] testCaseList.append(testCase1) testCaseList.append(testCase2) for testCase in testCaseList: testCase() Also, as python allows direct iteration over a list, you'll find that you don't need to create loops on an incrementor variable. Just loop on the list itself. I suspect lambda might be your friend here too for making the code less verbose, though I never really got the hang of lambdas, even though my first programming experience was a scheme class way back when.... Ah well. Hope this helps. Cheers, Cliff From googlegroupie at coloraura.com Sun Aug 19 16:12:56 2007 From: googlegroupie at coloraura.com (Daniel Pitts) Date: Sun, 19 Aug 2007 20:12:56 -0000 Subject: A/C Systems! In-Reply-To: <1187545327.963222.223220@w3g2000hsg.googlegroups.com> References: <1187545194.099278.217330@w3g2000hsg.googlegroups.com> <1187545327.963222.223220@w3g2000hsg.googlegroups.com> Message-ID: <1187554376.345506.82660@i38g2000prf.googlegroups.com> On Aug 19, 10:42 am, carairconditionersm... at gmail.com wrote: > On Aug 19, 7:39 pm, Cartun... at gmail.com wrote: > > > Everything you need to know about car air conditioners... > > >http://car-air-conditioning.spamspot.spam/ > > Great website man, I found everything I need Perhaps you did, after all, you advertise it all over. However, I fail to see the relevance to a Java newsgroup. Don't you know that targeted advertising has far better return? From lycka at carmen.se Thu Aug 9 10:49:09 2007 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 09 Aug 2007 16:49:09 +0200 Subject: Something in the function tutorial confused me. In-Reply-To: <1186383024.384152.87480@l70g2000hse.googlegroups.com> References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> Message-ID: Lee Fleming wrote: > Hello, > I have a simple question. Say you have the following function: > > def f(x, y = []): ... > But this, the code that "fixes" the list accumulation confounds me: > def f(x, y=None): > if y is None: y = [] ... > In other words, what's going on here? How is it that y accumulates > argument values between function calls in the first function, but > doesn't in the second one? I think the important thing to understand here is the distinction between names/variables and objects/values in Python. While you could interpret C code like this... void f() { ... int i = 5; ... int j = i; ... } ... as "create a place in the namespace of the f function where you can fit an integer value, and put the value 5 there. Later, create another place in the namespace of f which is also big enough for an integer. Copy the contents of the location named 'i', to the location named 'j'." You would instead interpret this similar Python code... def f(): ... i = 5 ... j = i ... ... as "create an integer object with the value 5. Then define a name/tag/variable in the namespace of function f which refers to the integer object with the value 5. Later, make a new name/tag/variable in the namespace of f which refers to the same object (happens to be an integer with the value 5) as i refers to." The semantics is very different. If you understand this, Python will seem much less magical, and you will never ask meaningless questions as whether Python uses call by reference or call by value. It's all a matter of understanding that all the juicy bits in the Python data model is in the actual values or objects. That's the stuff with type safety, a location in memory, qualities such as mutability etc. A "variable" is basically just a reference to an arbitrary object in a particular namespace. Assignments semantics is not about copying data as in C, and it's nothing arbitrarily defined in classes as in C++. It's all about deciding which object a name refers to. From irmen.NOSPAM at xs4all.nl Tue Aug 7 13:37:04 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 07 Aug 2007 19:37:04 +0200 Subject: distutils In-Reply-To: <1186489676.042901.236140@w3g2000hsg.googlegroups.com> References: <1186489676.042901.236140@w3g2000hsg.googlegroups.com> Message-ID: <46b8adc7$0$240$e4fe514c@news.xs4all.nl> vedrandekovic at v-programs.com wrote: > Hello again, > > Is there any patch for python "distutils", for this > >>>> from distutils import log,dir_util > ImportError: cannot import name log > > > Regards, > Vedran > Are you sure you haven't written a module yourself called distutils.py ? (that one will hide the standard distutils module) --irmen From michele.simionato at gmail.com Fri Aug 10 01:26:11 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 10 Aug 2007 05:26:11 -0000 Subject: Deleting objects on the fly In-Reply-To: <1186705500.227658.163170@q3g2000prf.googlegroups.com> References: <1186705500.227658.163170@q3g2000prf.googlegroups.com> Message-ID: <1186723571.250731.65040@q3g2000prf.googlegroups.com> On Aug 10, 2:25 am, Godzilla wrote: > Hello, > > I wish to know whether I should delete objects created on the fly via > the "del obj" statement. I noticed the RAM usage increased whenever > the application is being run for a long time. I am creating lots of > objects (messages) on the fly for communication between threads. > > Rather than having python's gc to do the work, does it make a > difference if I force a deletion? > > Thanks. Probably not, 'del x' just decrements the reference count, but it is the gc who does the real job. See http://docs.python.org/ref/customization.html#l2h-175 Do you have reference cycles in your application? You should tell us something more. Michele Simionato From zyzhu2000 at gmail.com Thu Aug 2 21:31:58 2007 From: zyzhu2000 at gmail.com (beginner) Date: Thu, 02 Aug 2007 18:31:58 -0700 Subject: Efficient Rank Ordering of Nested Lists In-Reply-To: <1186104049.022836.253470@e9g2000prf.googlegroups.com> References: <1186104049.022836.253470@e9g2000prf.googlegroups.com> Message-ID: <1186104718.857998.14040@z24g2000prh.googlegroups.com> On Aug 2, 8:20 pm, "pablo.mitch... at gmail.com" wrote: > A naive approach to rank ordering (handling ties as well) of nested > lists may be accomplished via: > > def rankLists(nestedList): > def rankList(singleList): > sortedList = list(singleList) > sortedList.sort() > return map(sortedList.index, singleList) > return map(rankList, nestedList) > > >>> unranked = [ [ 1, 2, 3, 4, 5 ], [ 3, 1, 5, 2, 4 ], [ -1.1, 2.2, > 0, -1.1, 13 ] ] > >>> print rankLists(unranked) > > [[0, 1, 2, 3, 4], [2, 0, 4, 1, 3], [0, 3, 2, 0, 4]] > > This works nicely when the dimensions of the nested list are small. > It is slow when they are big. Can someone suggest a clever way to > speed it up? Indexing the sorted list with a dictionary will speed it up a little. From SSchukat at dspace.de Fri Aug 31 12:05:37 2007 From: SSchukat at dspace.de (Stefan Schukat) Date: Fri, 31 Aug 2007 17:05:37 +0100 Subject: win32com problem: more than one instance In-Reply-To: <46D80B44.3050708@timgolden.me.uk> Message-ID: <1B3F2E002D9AD04BBC1A27B370F29EB9023807@exchange2003.dspace.de> Hello Thomas, excel registers its COM objects with REGCLS_SINGLEUSE that means one COM object is created per process. In Solidworks it seems that that they register with REGCLS_MULTIPLEUSE, which means on process can serve more than one COM object. Hence you have no chance to get multiple instances running in any COM client. Stefan > -----Original Message----- > From: python-list-bounces+sschukat=dspace.de at python.org > [mailto:python-list-bounces+sschukat=dspace.de at python.org] On > Behalf Of Tim Golden > Sent: Friday, August 31, 2007 1:36 PM > To: Thomas Rademacher > Cc: python-list at python.org > Subject: Re: win32com problem: more than one instance > > Thomas Rademacher wrote: > > Hello, > > > > I start my script convert.py simultaneously in any > dos-shells several > > times. But I get every time the same solidworks instance. > > I see in the proccess (task) manager only one > solidworks.exe Therefore > > I get for all simultaneous conversions the same output file. > > I *think* -- and I'm really hoping someone more knowledgeable > can chip in here -- that it's down to the particular COM > object implementation. ie Excel may choose to offer you > separate instances (or whatever they're called) while > SolidWorks may not. > > TJG > -- > http://mail.python.org/mailman/listinfo/python-list > From aleax at mac.com Sun Aug 26 01:14:36 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 25 Aug 2007 22:14:36 -0700 Subject: Need a better understanding on how MRO works? References: <1i3evke.1rwf8pn10k1h30N%aleax@mac.com> Message-ID: <1i3f78x.1pxexgx6emjfhN%aleax@mac.com> Steven W. Orr wrote: ... > Thanks Alex. I am humbled, though I was before I started. > I really don't have a lot of understanding of what you're saying so I'll > probably have to study this for about a year or so. > > * (I need to look up what dictproxy is.) I don't have any idea what the > ramifications are of your use of the word DISTINCT. Are you somehow > suggesting that new.classobj does a deep copy of the globals copy that's > passed to it? No, most definitely NOT deep!!!, but type.__new__ does "a little" of what you've said (a shallow copy, which is not quite "a copy" because it embeds [some of] the entries in slots). new.classobj determines the metaclass (from the bases, or a __metaclass__ entry in the dictionary) and calls it to generate the new class. For modern style classes, the class is type; for old-style legacy classes, it's types.ClassType, and they're not exactly identical in behavior (of course not, or there would no point in having both:-). > > * Also, I'd like to understand what the difference is between > nclass = new.classobj(name,(D1,),globals()) > vs. > def classfactory(): > class somename(object): > def somestuff(): > pass > return somename > G1 = classfactory() > globals()[name] = G1 > > Does new.classobj do anything special? No, new.classobj does essentially the same thing that Python does after evaluating a class statement to prepare the class's name, bases and dictionary: finds the metaclass and calls it with these arguments. A key difference of course is that a class statement prepares the class dictionary as a new, ordinary, distinct dictionary, while new.classobj accepts whatever dictionary you give it (so you can, though shouldn't, do strange things such as pass globals()...:-). Alex From exhuma at gmail.com Thu Aug 16 03:19:18 2007 From: exhuma at gmail.com (exhuma.twn) Date: Thu, 16 Aug 2007 00:19:18 -0700 Subject: twisted.web's xmlrpc with digest authencitation Message-ID: <1187248758.702385.204390@d55g2000hsg.googlegroups.com> I recently found a link[1] which demonstrates how to secure a xml-rpc service with basic HTTP-auth. But this get's send in clear-text over the net. There's also the HTTP-Digest auth mechanism which is apparently supported as well by twisted[2]. How do I secure an xml-rpc service using digest-auth then? If this works, all my troubles are suddenly gon and I am sold for twisted ;) [1]: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/526625 [2]: http://twistedmatrix.com/trac/ticket/1475 From carsten at uniqsys.com Fri Aug 24 11:24:30 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 24 Aug 2007 11:24:30 -0400 Subject: creating a tar file with python In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE2EE@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> <93066C069973ED448DC2BCEA9C44A7383BE2ED@efmailx> <46CE4D3D.7020106@holdenweb.com> <93066C069973ED448DC2BCEA9C44A7383BE2EE@efmailx> Message-ID: <1187969070.3385.20.camel@dot.uniqsys.com> On Thu, 2007-08-23 at 23:27 -0400, Brian McCann wrote: > > > Steve, > > I ran the code as you suggested, didn't work, tried variations of it > didn't work, > If you don't know the answer don't pretend you do! > > Apology not accepted, please don't wake up! > > Future correspondence on any python questions from you go to trash. You clearly have no idea who you're talking to. I suggest you Google for '"Steve Holden" Python' to get a clue. Good luck finding any more help here. -Carsten From duncan.booth at invalid.invalid Tue Aug 7 09:13:49 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Aug 2007 13:13:49 GMT Subject: ensuring GNU readline isn't used References: Message-ID: Josh Paetzel wrote: > Is there a way to ensure that GNU readline isn't used (even though > support may have been compiled in?). I'm experiencing a licensing > problem, I'd like to use the "cmd" module, for example, but my code is > proprietary and hence, if cmd uses readline, I can't use cmd. I think you have misread the GPL: just because your non-GPL code *can* be used with something covered by the GPL doesn't mean your code is infected by the GPL. Your code doesn't require a GPL module to run (you can use a version of cmd compiled without readline), and you aren't attempting to distribute it with a GPL module, so you don't need to care how the end user chooses to run it. From bcc at nospam.net Wed Aug 8 17:44:41 2007 From: bcc at nospam.net (Bryan) Date: Wed, 08 Aug 2007 14:44:41 -0700 Subject: How to reset sys.exec_prefix? Message-ID: Somehow on my linux box I scrood things up and I lost my python path info. If I check sys.exec_prefix or sys.prefix it shows '/usr/local/', where it should show '/usr/'. Is there a config file somewhere that I can change to fix this, or do I need to do a rebuild/reinstall? Hope not. Thanks, B From steve at holdenweb.com Tue Aug 21 12:54:56 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 21 Aug 2007 12:54:56 -0400 Subject: str().join() isn't working In-Reply-To: <1187634895.387910.179500@m37g2000prh.googlegroups.com> References: <496954360708200905i2100b32ag5983ab729e5d216f@mail.gmail.com> <1187634895.387910.179500@m37g2000prh.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Aug 20, 1:16 pm, "Robert Dailey" wrote: [...] > When you use join, you join the items in the list with each other to > form one long string. In your statement, your script tries to > concatenate 2 lists to each other before it does the join, which is > impossible in Python. The "+" operator is only for addition and for > two or more strings. > Bzzzt! >>> ["you", "can't", "add", "lists?"] + ["-", "nonsense!"] ['you', "can't", 'add', 'lists?', '-', 'nonsense!'] >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Aug 19 08:45:49 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 19 Aug 2007 14:45:49 +0200 Subject: How to make a module function visible only inside the module? References: <1187484334.091530.90420@m37g2000prh.googlegroups.com> <1i32pg7.b0y3h92vjygwN%raims@dot.com> <1187488017.198905.242610@j4g2000prf.googlegroups.com> Message-ID: <5iqsbtF3qanv6U3@mid.individual.net> beginner wrote: > Thanks a lot. I was using two underscores, __module_method() as my > static method convention, and then I had some problems calling > them from inside class methods. *Please* do yourself and other people that sometime may have to read your code a favor and write code at least loosely oriented to PEP 8. BTW, Python has no "static methods" at module level. And I suppose what you call "class methods" actually aren't. Regards, Bj?rn -- BOFH excuse #183: filesystem not big enough for Jumbo Kernel Patch From google at tyeon.com Wed Aug 29 21:21:11 2007 From: google at tyeon.com (google at tyeon.com) Date: Wed, 29 Aug 2007 18:21:11 -0700 Subject: How to use os.putenv() ? Message-ID: <1188436871.549201.315170@g4g2000hsf.googlegroups.com> >>> >>> import os >>> >>> os.environ['PATH'] 'C:\\WINNT\\system32;C:\\WINNT;C:\\WINNT\\System32\\Wbem;%C:\\WINNT%\ \system32;%C:\\WINNT%;%C:\\WINNT%\\System32\\Wbem' >>> >>> os.putenv('PATH', 'C:\\WINNT\\system32') >>> >>> os.environ['PATH'] 'C:\\WINNT\\system32;C:\\WINNT;C:\\WINNT\\System32\\Wbem;%C:\\WINNT%\ \system32;%C:\\WINNT%;%C:\\WINNT%\\System32\\Wbem' >>> What am I doing wrong? How do I change the value of an environment variable? From deets at nospam.web.de Mon Aug 6 11:44:46 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 06 Aug 2007 17:44:46 +0200 Subject: boolean operations on sets References: <1186409631.147290.323400@22g2000hsm.googlegroups.com> Message-ID: <5hotveF3l5gmkU1@mid.uni-berlin.de> Flavio wrote: > Hi, I have been playing with set operations lately and came across a > kind of surprising result given that it is not mentioned in the > standard Python tutorial: > > with python sets, intersections and unions are supposed to be done > like this: > In [7]:set('casa') & set('porca') > Out[7]:set(['a', 'c']) > > In [8]:set('casa') | set('porca') > Out[8]:set(['a', 'c', 'o', 'p', 's', 'r']) > > and they work correctly. Now what is confusing is that if you do: > > In [5]:set('casa') and set('porca') > Out[5]:set(['a', 'p', 'c', 'r', 'o']) > > In [6]:set('casa') or set('porca') > Out[6]:set(['a', 'c', 's']) > > The results are not what you would expect from an AND or OR > operation, from the mathematical point of view! aparently the "and" > operation is returning the the second set, and the "or" operation is > returning the first. > > If python developers wanted these operations to reflect the > traditional (Python) truth value for data structures: False for empty > data structures and True otherwise, why not return simply True or > False? > > So My question is: Why has this been implemented in this way? I can > see this confusing many newbies... It has nothing to do with sets - it stems from the fact that certain values in python are considered false, and all others true. And these semantics were introduced at a point where there was no explicit True/False, so the operators were defined in exact the way you observed. Consider this: "foo" or "bar" -> "foo" So - nothing to do with sets. Diez From fw3 at hotmail.co.jp Thu Aug 2 20:00:13 2007 From: fw3 at hotmail.co.jp (wang frank) Date: Fri, 03 Aug 2007 00:00:13 +0000 Subject: Tkinter or wxpython? In-Reply-To: Message-ID: Hi, I want to build a GUI to execut python script. I found TKinter and wxpython. Which one is easier for a newbie? and which one is better? Thanks Frank _________________________________________________________________ ?????????????????????????????????????? ? http://clk.atdmt.com/GBL/go/msnjpqjl0060000010gbl/direct/01/ From steven.bethard at gmail.com Mon Aug 27 10:36:52 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 27 Aug 2007 08:36:52 -0600 Subject: Parser Generator? In-Reply-To: <1188218409.525240.300590@o80g2000hse.googlegroups.com> References: <1188159150.755231.239390@o80g2000hse.googlegroups.com> <1188185192.735485.237740@57g2000hsv.googlegroups.com> <1188218409.525240.300590@o80g2000hse.googlegroups.com> Message-ID: Paul McGuire wrote: > On Aug 26, 10:48 pm, Steven Bethard wrote: >> In Japanese and Chinese tokenization, word boundaries are not marked by >> different classes of characters. They only exist in the mind of the >> reader who knows which sequences of characters could be words given the >> context, and which sequences of characters couldn't. >> >> The closest analog would be to ask pyparsing to find the words in the >> following sentence: >> >> Thepyparsingmoduleprovidesalibraryofclassesthatclientcodeusestoconstructthe?grammardirectlyinPythoncode. >> >> Most approaches that have been even marginally successful on these kinds >> of tasks have used statistical machine learning approaches. > > You mean like this? > > from pyparsing import * > > knownWords = ['of', 'grammar', 'construct', 'classes', 'a', > 'client', 'pyparsing', 'directly', 'the', 'module', 'uses', > 'that', 'in', 'python', 'library', 'provides', 'code', 'to'] > > knownWord = oneOf( knownWords, caseless=True ) > sentence = OneOrMore( knownWord ) + "." > > mush = > "ThepyparsingmoduleprovidesalibraryofclassesthatclientcodeusestoconstructthegrammardirectlyinPythoncode." > > print sentence.parseString( mush ) > > prints: > > ['the', 'pyparsing', 'module', 'provides', 'a', 'library', 'of', > 'classes', 'that', 'client', 'code', 'uses', 'to', 'construct', > 'the', 'grammar', 'directly', 'in', 'python', 'code', '.'] > > In fact, this is almost the exact scheme used by Zhpy for extracting > Chinese versions of Python keywords, and mapping them back to English/ > Latin words. Of course, this is not practical for natural language > processing, as the vocabulary gets too large. And you can get > ambiguous matches, such as a vocabulary containing the words ['in', > 'to', 'into'] - the runtogether "into" will always be assumed to be > "into", and never "in to". Yep, and these kinds of things occur quite frequently with Chinese and Japanese. The point was not that pyparsing couldn't do it for a small subset of characters/words, but that pyparsing is probably not the right solution for general purpose Japanese/Chinese tokenization. Steve From bj_666 at gmx.net Wed Aug 1 02:15:28 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Aug 2007 06:15:28 GMT Subject: Extending Python by Adding Keywords & Data types References: <1185913739.879602.212950@w3g2000hsg.googlegroups.com> <5h9n66F3j641tU5@mid.uni-berlin.de> <1185932558.472578.103690@o61g2000hsh.googlegroups.com> Message-ID: <5hamnvF3inuf2U2@mid.uni-berlin.de> On Wed, 01 Aug 2007 01:42:38 +0000, Maximus Decimus wrote: > Since, I am an amateur in using python, could you please be more > specific. For new data types, you had asked to implement the classes. > I intend to use C for implementing these data types. So where do i > need to implement these classes ie under which file or module in the > python package. Like Ben Finney said, first do something about the amateur status and work through the tutorial. Everything in Python is an object. And classes are a way to define templates for new objects. After you know classes better, ask yourself how you would implement the already existing data types with classes yourself and then you'll get an idea how to create new data types. If you want to implement new types in C there's a tutorial in the docs called ?Extending and Embedding? and a reference of the Python/C API. But maybe you should start with implementing them in Python and only convert those parts to C code that are *really* to slow in the prototype. Really means measure and don't guess. A nice step between Python and C is Pyrex, a Python-like language with some restrictions but also C data types. Pyrex is then translated to C and can be compiled as Python extension module. Ciao, Marc 'BlackJack' Rintsch From brian at rkspeed-rugby.dk Wed Aug 1 16:48:31 2007 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: Wed, 01 Aug 2007 19:48:31 -0100 Subject: Floats as keys in dict References: <1i25pz7.3m2bya88wujkN%aleax@mac.com> Message-ID: Steve Holden writes: > Alex Martelli wrote: [snip] Thanks a lot for your intersting answers. I will start out taking a look at bisect. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk From arkanes at gmail.com Sun Aug 19 19:12:47 2007 From: arkanes at gmail.com (Chris Mellon) Date: Sun, 19 Aug 2007 18:12:47 -0500 Subject: desperately in need of a tool In-Reply-To: <1187560418.339131.283470@i38g2000prf.googlegroups.com> References: <1187560418.339131.283470@i38g2000prf.googlegroups.com> Message-ID: <4866bea60708191612o56dbda64id210a561808de125@mail.gmail.com> On 8/19/07, yagyala wrote: > Hi. > > I recently started working for a company that has just implemented its > first set of software standards. So far, so good. Here's the problem: > one of those standards is that the comments for each routine must > indicate every other routine that it calls. As I try to keep my > routines small, and factor out methods alot, this can lead to an > enormous ammount of extra typing. I really, really, really don't want > to do this by hand. Does anyone know of a tool that could do this for > me, or at least a tool that can tell what other routines a given > routine calls that I could program against? (Preferably something that > works under pydev, but I'm not going to be choosy.) > > I'm sure some will wonder about the reasoning of this standard. The > company primarily has experience writing scientific alogorythms which > can get rather long. It makes a bit more sense to document all > routines called for a very long routine, but for short routines that > primarily call other routines, as most mine do, well.... > > Thanks. > To the extent that it's useful to do this at all in Python (dynamic method invocation is impossible determine, and polymorphic method invocations you can't pinpoint), pycallgraph (http://pycallgraph.slowchop.com/) can do this. > -- > http://mail.python.org/mailman/listinfo/python-list > From 3dbernard at gmail.com Fri Aug 31 14:10:07 2007 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 31 Aug 2007 14:10:07 -0400 Subject: [python 3.0] reload() gone? Message-ID: <61d0e2b40708311110l5a13819fh4e6b2aafe928b44d@mail.gmail.com> I read in the Python 3.0 documentation that reload() was removed, without further explanations. http://docs.python.org/dev/3.0/whatsnew/3.0.html?highlight=reload So what are we supposed to do to reload modules? Thanks Bernard From rcdailey at gmail.com Thu Aug 16 18:26:09 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 16 Aug 2007 17:26:09 -0500 Subject: Pass by reference or by value? In-Reply-To: <46C4CCAD.3080104@holdenweb.com> References: <496954360708161402x58faba47x7a6eae6e68f81d4@mail.gmail.com> <496954360708161501s541bddb7vfe168e4863f7f1e@mail.gmail.com> <46C4CCAD.3080104@holdenweb.com> Message-ID: <496954360708161526o5b6a0fffof2fbd5227244e709@mail.gmail.com> Thanks Steve for your explanation. It was very helpful. I think I understand it now. By the way, by the .set method I meant: class Integer: def __init__( self, number=0 ): self._int = number def set( self, number ): self._int = number # later on.... mutableInt = Integer( 5 ) def change_me( var ): var.set( 6 ) Of course, I'd probably use overloaded operators in a more realized example. On 8/16/07, Steve Holden wrote: > > Robert Dailey wrote: > > So immutable objects cannot be modified directly? I guess this means > > integers are immutable and the act of assigning to one is a completely > > new definition? > > Correct. A new value is bound to the name or item on the left-hand side > - remember, all variables are pointers to values, there's no way to > replace the value of a variable because of the automatic dereferencing. > And yes, immutable objects can't be modified. At all, period. Hence the > name. > > > So if I were to create a class called Integer and give > > it a .set() method, this would allow me to create mutable integers, and > > thus passing in an object of type class Integer would allow me to modify > > the value from inside the function? > > > Well, the .set() method wouldn't be called automatically on an > assignment statement but yes, if you passed an Integer object into your > function and called its .set() method from inside then it should work. > > As long as you get your mutable integer implementation correct, of > course ;-). I'd suggest delegating everything except the .set() method > to the underlying integer value. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Wed Aug 1 19:58:03 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 01 Aug 2007 16:58:03 -0700 Subject: Extending Python by Adding Keywords & Data types In-Reply-To: <1185999017.188830.88860@d55g2000hsg.googlegroups.com> References: <1185913739.879602.212950@w3g2000hsg.googlegroups.com> <1185973687.883520.227540@k79g2000hse.googlegroups.com> <1185999017.188830.88860@d55g2000hsg.googlegroups.com> Message-ID: <1186012683.676225.261070@k79g2000hse.googlegroups.com> On Aug 1, 3:10 pm, Maximus Decimus wrote: > > Your code snippet was quite simple and it explained me very well than > the tutorial. HAts off to u!! > Thanks! > > I am doing my research in Pervasive space environments filled with > sensors and actuators. I am just trying to modify an existing language > which suits that kind of environment. Pervasive space environment is > filled with sensors and actuators and everything depends on their > state and behavior ie on the sensor readings and actuator states. So > why not express a language variable in terms of sensors and actuators? > THis is my idea of working around and trying to introduce new data > types for these sensor and actuator variables which store sensor > readings and actuator states. > > I think this explains a bit clearly on what I am looking > for..Suggestion and ideas are kindly appreciated. > > Thanks in advance and for your time. You got me thinking about a little exercise I did a long time ago, using overloaded operators to help model circuits of resistors in series and parallel. Here is one way to model some physical objects using notation that is particular to their own domain (and even counter to the conventional uses of that notation, as noted in the docstrings). See below: class Resistor(object): def __init__(self,r): self.resistance = r def __sub__(self,other): """R1-R2 looks like two resistors in series, nevermind that we are using a subtraction operator to perform what is essentially an addition operation. Think of the horizontal line as a circuit connecting the two resistors.""" return Resistor(self.resistance + other.resistance) def __or__(self,other): "R1 | R2 looks like two resistors in parallel, sort of" return Resistor(float(self.resistance * other.resistance) / float(self.resistance + other.resistance)) def colorCode(self): """insert nifty routine here to convert self.resistance to sequence of color bands""" pass def __repr__(self): return "Resistor(%s)" % self.resistance r1 = Resistor(100) r2 = Resistor(200) print r1-r2 # resistors in series print r1 | r2 # resistors in parallel print r1 | r1 | r2 # three resistors in parallel, not so easy math print (r1 - r1) | r2 # two resistors in series in parallel with another print r1 - (r1 | r1) Prints: Resistor(300) Resistor(66.6666666667) Resistor(40.0) Resistor(100.0) Resistor(150.0) This is just using vanilla Python with some tricky operator interpreting. You can also do some syntax manipulation using the import hooks (first shown to me by Wilson Fowlie). Here is an example of modeling an in- memory state machine, with some customized syntax. (http:// www.geocities.com/ptmcg/python/stateMachine.html) This is more involved, and requires a custom parser, but let's not get distracted down that path... Just some more alternatives to mucking about in the Python compiler. -- Paul From zzbbaadd at aol.com Thu Aug 30 19:39:24 2007 From: zzbbaadd at aol.com (zzbbaadd at aol.com) Date: Thu, 30 Aug 2007 16:39:24 -0700 Subject: list index() In-Reply-To: <87fy20d2lt.fsf@benfinney.id.au> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <87hcmhebwv.fsf@benfinney.id.au> <1188492060.983148.90000@r34g2000hsd.googlegroups.com> <87fy20d2lt.fsf@benfinney.id.au> Message-ID: <1188517164.844790.109150@q4g2000prc.googlegroups.com> On Aug 30, 4:28 pm, Ben Finney wrote: > zzbba... at aol.com writes: > > On Aug 30, 12:09 am, Ben Finney > > wrote: > > > It's letting you know that the item isn't in the list. There's no > > > sensible return value from an "index" function in that condition. > > > for str: > > find( sub[, start[, end]]) > > [...] > > Return -1 if sub is not found. > > > -1 is used in other languages as well. > > It is no more sensible there than in the 'str.find' method, which is a > historical wart. One man's sensible is another man's insensible. For instance, some people feel -1 as a valid index into a list is sensible. Other's find it insensible. > > -- > \ "Hey Homer! You're late for English!" "Pff! English, who needs | > `\ that? I'm never going to England!" -- Barney & Homer, _The | > _o__) Simpsons_ | > Ben Finney From horpner at yahoo.com Mon Aug 13 09:37:26 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 13 Aug 2007 13:37:26 GMT Subject: Adventure-Engines in Python References: <46c02fdd$0$14405$afc38c87@news.optusnet.com.au> Message-ID: On 2007-08-13, Richard Jones wrote: > Wildemar Wildenburger wrote: >> Are there any? > > An adventure game was written for one of the PyWeek challenges: > > http://www.pyweek.org/e/aerunthar/ > > You might be able to use that as a starting point. Here's an abondoned (since Python 2.2), but basically complete system: http://members.nuvox.net/~zt.wolf/PAWS.htm For a taste of what it looked like, see the PAWS section of Roger Firth's IF system comparison page, _Cloak of Darkness_. http://www.firthworks.com/roger/cloak/ http://www.firthworks.com/roger/cloak/paws/index.html This contains a P.A.W.S version of the very simple example game. The author of the example is somewhat suspect, however. As far as I know, no full game was ever written in PAWS. Once you try it, you'll possibly see why no interactive fiction system distributed as a library for a general-purpose language has ever caught on. Every system that's enjoyed even moderate success has been a language+library implementation. -- Neil Cerutti From exarkun at divmod.com Tue Aug 14 15:44:31 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 14 Aug 2007 15:44:31 -0400 Subject: curses library In-Reply-To: <20070814214551.1cb50566.ghirai@ghirai.com> Message-ID: <20070814194431.4947.517778923.divmod.quotient.21969@ohm> On Tue, 14 Aug 2007 21:45:51 +0300, Ghirai wrote: >On Tue, 14 Aug 2007 18:27:16 GMT >Neil Cerutti wrote: > >> On 2007-08-14, Ghirai wrote: >> > I need to write a console application. >> > >> > Are there any wrappers around curses/ncurses? >> > Or any other similar libraries? >> >> The answer depends on your chosen platform. Python hasn't got a >> cross-platform console library as one of its included batteries. >> >> First try the curses module. It does come with Python on systems >> with a curses port. >> >> For Windows, there's the Effbot's console module. >> http://effbot.org/zone/console-index.htm >> >> Or go to plan B: Use a Tkinter or other GUI interface's text >> widget. > >Forgot to say, i don't need it to work on windows :) You might be interested in insults: API docs: http://twistedmatrix.com/documents/current/api/twisted.conch.insults.html Examples: http://twistedmatrix.com/projects/conch/documentation/examples/ Jean-Paul From frikker at gmail.com Thu Aug 16 15:53:49 2007 From: frikker at gmail.com (frikk) Date: Thu, 16 Aug 2007 12:53:49 -0700 Subject: Accessing Windows Network Share? In-Reply-To: References: <1187287133.737105.169960@19g2000hsx.googlegroups.com> <1187289961.104183.104910@50g2000hsm.googlegroups.com> Message-ID: <1187294029.192682.299110@g4g2000hsf.googlegroups.com> On Aug 16, 3:03 pm, "Chris Mellon" wrote: > On 8/16/07, frikk wrote: > > > > > > > On Aug 16, 2:43 pm, "Chris Mellon" wrote: > > > On 8/16/07, frikk wrote: > > > > > I previously posted about accessing SharePoint over the web. Well I > > > > have since given up any easy means of doing this, since something else > > > > has perked my interest. Instead of going tohttp://sharepoint/site, > > > > why not just access \\sharepoint\site\ directly? > > > > > So my question is this - How do I access that network share? > > > > > If I go to start -> run, and type in "\\SharPointServer\Site\Folder", > > > > windows explorer will pop up with it. I suppose I could have a little > > > > batch script that python runs to map the drive to a local letter, like > > > > J:, but this does not seem necessary. > > > > > Suggestions? > > > > > This does not work, for obvious reasons: > > > > >>> import glob.glob > > > > >>> glob.glob("\\\\server\\folder\\*") > > > > [] > > > > I don't see whats "obvious" about this. Access to windows shares is > > > handled by Windows in a VFS layer, and glob and all other Python file > > > access works fine over them for me.- Hide quoted text - > > > > - Show quoted text - > > > Haha ok, you're right its not obvious. Sorry for that. > > > But that code does not work - should it? > > > Do you have an example of glob working over a file share, not a > > network mapped drive? > > import glob > glob.glob(r"\\localhost\c$\python25\libs\*") > ['\\\\localhost\\c$\\python25\\libs\\bz2.lib', > '\\\\localhost\\c$\\python25\\libs\\libpython25.a', > '\\\\localhost\\c$\\python25\\libs\\pyexpat.lib', > '\\\\localhost\\c$\\python25\\libs\\python25.lib', > '\\\\localhost\\c$\\python25\\libs\\select.lib', > '\\\\localhost\\c$\\python25\\libs\\unicodedata.lib', > '\\\\localhost\\c$\\python25\\libs\\winsound.lib', > '\\\\localhost\\c$\\python25\\libs\\_bsddb.lib', > '\\\\localhost\\c$\\python25\\libs\\_ctypes.lib', > '\\\\localhost\\c$\\python25\\libs\\_ctypes_test.lib', > '\\\\localhost\\c$\\python25\\libs\\_elementtree.lib', > '\\\\localhost\\c$\\python25\\libs\\_hashlib.lib', > '\\\\localhost\\c$\\python25\\libs\\_msi.lib', > '\\\\localhost\\c$\\python25\\libs\\_socket.lib', > '\\\\localhost\\c$\\python25\\libs\\_sqlite3.lib', > '\\\\localhost\\c$\\python25\\libs\\_ssl.lib', > '\\\\localhost\\c$\\python25\\libs\\_testcapi.lib', > '\\\\localhost\\c$\\python25\\libs\\_tkinter.lib'] > > I do it all the time. I'd double check your slash escaping (consider > using r'') and pathnames.- Hide quoted text - > > - Show quoted text - I must have been doing it wrong. Thanks! That works great! From bignose+hates-spam at benfinney.id.au Mon Aug 6 19:37:32 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 07 Aug 2007 09:37:32 +1000 Subject: Emacs + python. References: <00tzrdm1zd.fsf@googlemail.com> Message-ID: <87myx48car.fsf@benfinney.id.au> Hadron writes: > Sorry to repeat, but I had to reinstall and lost all my news. Fortunately, there's no need to repeat, because the forum is archived both as a Usenet newsgroup and a mailing list. -- \ "What you have become is the price you paid to get what you | `\ used to want." -- Mignon McLaughlin | _o__) | Ben Finney From zyzhu2000 at gmail.com Wed Aug 1 13:16:37 2007 From: zyzhu2000 at gmail.com (beginner) Date: Wed, 01 Aug 2007 17:16:37 -0000 Subject: Assertion in list comprehension In-Reply-To: References: <1185982643.001546.138180@e16g2000pri.googlegroups.com> Message-ID: <1185988597.055293.106540@q3g2000prf.googlegroups.com> On Aug 1, 11:28 am, "Chris Mellon" wrote: > On 8/1/07, beginner wrote: > > > > > > > Hi, > > > Does anyone know how to put an assertion in list comprehension? I have > > the following list comprehension, but I want to use an assertion to > > check the contents of rec_stdl. I ended up using another loop which > > essentially duplicates the functions of list comprehension. It just > > look like a waste of coding and computer time to me. > > > I just wish I could put the assertions into list comprehensions. > > > x=[(rec_stdl[0].st/10000.0, > > rec_stdl[0].cl, > > rec_stdl[0].bb, > > rec_stdl[0].bo, > > rec_stdl[1].bb, > > rec_stdl[1].bo, > > rec_stdl[0].ex > > ) > > for rec_stdl in rec_by_ex if len(rec_stdl)==2 > > ] > > > #duplicated loop > > if __debug__: > > for rec_stdl in rec_by_ex: > > l=len(rec_stdl) > > assert(l<=2 and l>0) > > if l==2: > > assert(rec_stdl[0].c=="C" and rec_stdl[1].c=="P") > > assert(rec_stdl[0].ex==rec_stdl[1].ex) > > assert(rec_stdl[0].st==rec_stdl[1].st) > > assert(rec_stdl[0].cp==rec_stdl[1].cp) > > First: All your asserts are wrong. Assert is a statement, not a > function. These specific ones will behave as expected, but it's easy > to accidentally write ones that always pass this way. Do you mean I should not use the parentheses? > Secondly: This is a waste of code, because if __debug__ is not defined > asserts will be skipped by the compiler. You could use the same loop > block for both branches. I know. My original question was how. Dan suggested to write a checker function. > Thirdly: This sort of testing is precisely what unit tests and/or > doctests are for. Agreed. From james.p.news at gmail.com Tue Aug 21 18:45:00 2007 From: james.p.news at gmail.com (james.p.news at gmail.com) Date: Tue, 21 Aug 2007 22:45:00 -0000 Subject: libgmail failure In-Reply-To: <1187733545.529286.78980@50g2000hsm.googlegroups.com> References: <1187730447.621592.93740@q4g2000prc.googlegroups.com> <1187733545.529286.78980@50g2000hsm.googlegroups.com> Message-ID: <1187736300.755595.227150@x35g2000prf.googlegroups.com> Thanks for the suggestion. I've tried logging in and sending email manually and it works just fine. Thanks though, James From http Thu Aug 16 00:46:29 2007 From: http (Paul Rubin) Date: 15 Aug 2007 21:46:29 -0700 Subject: ElementTree surprise Message-ID: <7xd4xoxf16.fsf@ruckus.brouhaha.com> I have a doc with a bunch of fields like: stuff other stuff and sometimes I use ElementTree to parse the doc and I use the .text attribute to get "stuff" or "other stuff" in the spam and penguin examples. I'd expect .text to be the empty string in the parrot example, but instead it is None. I can fix my script to deal with this, but it's surprising. Is it intentional? I could understand it being None if the doc had said but that is different. Disclaimer: I'm not even slightly an XML expert, I just find myself having to deal with a lot of it. From gagsl-py2 at yahoo.com.ar Wed Aug 15 12:39:57 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 15 Aug 2007 13:39:57 -0300 Subject: Simple python iteration question References: <20070814163430.GJ22017@lass.lfod.us> Message-ID: En Wed, 15 Aug 2007 10:37:16 -0300, Cameron Laird escribi?: > Shawn Milochik wrote: >> Just for my own sanity: Isn't this the third response advocating the >> use of enumerate()? Did the other responses not get through, or was >> this a time-delay thing? >Yes, for a variety of reasons, it's easy for it to happen that > all three-or-more enumerate-responders independently saw the > original question, but not any of their colleagues' responses. > > Sometime we'll tell a few Usenet funnies about The Old Days > when transport included tape-backup-driven-by-private-car. "Never underestimate the bandwidth of a station wagon full of tapes hurtling down the highway" (Andrew S. Tanenbaum, Computer Networks, 1996; maybe the origin is much older) -- Gabriel Genellina From wpdster at gmail.com Tue Aug 14 13:26:46 2007 From: wpdster at gmail.com (Patrick Doyle) Date: Tue, 14 Aug 2007 13:26:46 -0400 Subject: pure python gaussian blur In-Reply-To: <1187108679.401416.224060@19g2000hsx.googlegroups.com> References: <1187108679.401416.224060@19g2000hsx.googlegroups.com> Message-ID: On 8/14/07, Gerdus van Zyl wrote: > Does anyone have a relatively fast gaussian blur implemented in pure > python? Below is my attempt but it takes 2.9 seconds for a 320x240 > image. Image comes from byte string: self.array = > array.array('B',srcstring). Would some sort of matrix multiplication > be faster? I don't have experience in that. > > I don't want to use PIL or http://filters.sourceforge.net/ to avoid > the 300kb dll just for a simple blur. > The one time I tried something similar (implementing a signal processing function in Python), I found NumPy to be _significantly_ faster -- which makes sense, since all of the matrix arithmetic was implemented in hard coded, compiled C code instead of interpreted byte code. --wpd From uymqlp502 at sneakemail.com Fri Aug 31 15:17:26 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Fri, 31 Aug 2007 12:17:26 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1i3p8lm.19738kn1q0gkouN%aleax@mac.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> <7xwsvcc9yz.fsf@ruckus.brouhaha.com> <1i3p8lm.19738kn1q0gkouN%aleax@mac.com> Message-ID: <1188587846.687895.69240@q5g2000prf.googlegroups.com> Alex Martelli wrote: > Russ specifically mentioned *mission-critical applications* as being > outside of Python's possibilities; yet search IS mission critical to > Google. Yes, reliability is obtained via a "systems approach", Alex, I think you are missing the point. Yes, I'm sure that web searches are critical to Google's mission and commercial success. But the point is that a few subtle bugs cannot destroy Google. If your search engines and associated systems have bugs, you fix them (or simply tolerate them) and continue on. And if a user does not get the results he wants, he isn't likely to die over it -- or even care much. Online financial transactions are another matter altogether, of course. User won't die, but they will get very irate if they lose money. But I don't think that's what you are talking about here. From uymqlp502 at sneakemail.com Thu Aug 30 18:11:12 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Thu, 30 Aug 2007 15:11:12 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> <1188430887.481586.106760@l22g2000prc.googlegroups.com> <1188504811.019632.186580@x35g2000prf.googlegroups.com> Message-ID: <1188511872.294065.5090@z24g2000prh.googlegroups.com> > Things get vetted *before* they get added to the core, not after. I realize that. I meant that it would get vetted in the process of putting it into the core. That would provide more confidence that it was done the best possible way -- or close to it. From frikker at gmail.com Thu Aug 16 14:46:01 2007 From: frikker at gmail.com (frikk) Date: Thu, 16 Aug 2007 11:46:01 -0700 Subject: Accessing Windows Network Share? In-Reply-To: References: <1187287133.737105.169960@19g2000hsx.googlegroups.com> Message-ID: <1187289961.104183.104910@50g2000hsm.googlegroups.com> On Aug 16, 2:43 pm, "Chris Mellon" wrote: > On 8/16/07, frikk wrote: > > > > > > > I previously posted about accessing SharePoint over the web. Well I > > have since given up any easy means of doing this, since something else > > has perked my interest. Instead of going tohttp://sharepoint/site, > > why not just access \\sharepoint\site\ directly? > > > So my question is this - How do I access that network share? > > > If I go to start -> run, and type in "\\SharPointServer\Site\Folder", > > windows explorer will pop up with it. I suppose I could have a little > > batch script that python runs to map the drive to a local letter, like > > J:, but this does not seem necessary. > > > Suggestions? > > > This does not work, for obvious reasons: > > >>> import glob.glob > > >>> glob.glob("\\\\server\\folder\\*") > > [] > > I don't see whats "obvious" about this. Access to windows shares is > handled by Windows in a VFS layer, and glob and all other Python file > access works fine over them for me.- Hide quoted text - > > - Show quoted text - Haha ok, you're right its not obvious. Sorry for that. But that code does not work - should it? Do you have an example of glob working over a file share, not a network mapped drive? From bdesth.quelquechose at free.quelquepart.fr Wed Aug 29 09:35:48 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 29 Aug 2007 15:35:48 +0200 Subject: Accessing docstrings at runtime? In-Reply-To: References: <011b01c7ea69$95512fe0$e6003dcc@worf2> Message-ID: <46d5bf47$0$291$426a74cc@news.free.fr> Chris Mellon a ?crit : > On 8/29/07, Kenneth Love wrote: > >>How do I print the docstring for a class property? (snip) > You're looking at an instance, not at the class. y.x is going through > the descriptor lookup and is returning the string, so the __doc__ is > the the __doc__ of the string object, as you see. > > If you want to look at the property directly, look it up in the class object: > > C.x.__doc__ Or type(y).x.__doc__ if you don't know the class of y. From owntheweb at gmail.com Wed Aug 29 21:46:11 2007 From: owntheweb at gmail.com (Ultrus) Date: Thu, 30 Aug 2007 01:46:11 -0000 Subject: replacing xml elements with other elements using lxml In-Reply-To: <1188428655.300330.213430@r29g2000hsg.googlegroups.com> References: <1188399381.188639.289480@57g2000hsv.googlegroups.com> <46D5A272.2000509@web.de> <1188428655.300330.213430@r29g2000hsg.googlegroups.com> Message-ID: <1188438371.064824.13020@l22g2000prc.googlegroups.com> Ah! I figured it out. I forgot that the tree is treated like a list. The solution was to replace the element with the first child, then use Python's insert(i,x) function to insert elements after the first one. lxml rocks! From thomas at jollans.com Mon Aug 6 12:59:44 2007 From: thomas at jollans.com (Thomas Jollans) Date: Mon, 6 Aug 2007 18:59:44 +0200 Subject: udp, datagram sockets In-Reply-To: <1186416225.769753.307110@o61g2000hsh.googlegroups.com> References: <1186416225.769753.307110@o61g2000hsh.googlegroups.com> Message-ID: <200708061859.44884.thomas@jollans.com> On Monday 06 August 2007, 7stud wrote: > I'm trying to understand datagrams. My client program sends a message > to the server, and then the server infinitely loops over the recv() to > make sure all the data was received. I'm trying to use an * to signal > the end of the message, so that the server can break out of the > infinite while loop used to check the recv(). However, my server > repeatedly outputs the client message over and over again. Can anyone > tell me why? > > When I start the server, I get the following debug output as > expected: > > --------- > debug: start outer while loop > #this infinite while loop endlessly listens for messages from the > client > > debug: recv while loop > #this infinite while loop checks to make sure the whole message was > received > ----------- > > and then the recv() blocks and waits for data to be sent by the > client. But when I start the client, the server repeatedly outputs the > client message over and over again. My expectation was that after > processing the message from the client, the server would block the > next time it executed the recv() statement and wait for more data from > the client. > > client: > ---------- > import socket > > s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > > message = "hello*" #asterisk to delimit end of message > msg_size = len(message) > total_sent = 0 > > print "debug:", total_sent, msg_size > > while total_sent < msg_size: > size_sent = s.sendto(message[total_sent:], ("localhost", 7777) ) > total_sent += size_sent > > print "debug:", total_sent, msg_size > > print 'debug: while loop ended' > s.close() > ----------- > > Here's the client output: > > ------------- > debug: 0 6 > debug: 6 6 > debug: while loop ended > --------------- > > > server: > ------------------ > import socket > import sys > > s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > s.bind(("", 7777)) > > try: > while True: #This loop listens endlessly for messages. > print "debug: start outer while loop" > > #Receive messages from client: > my_list = [] > while True: #This loop checks to see if the whole message was > received. > print "debug: recv while loop" > > data = s.recv(1024) > my_list.append(data) > > if data.rfind("*"): > message = "".join(my_list) > print "Received message:\n%s" % message[:-1] > break > > > #Send messages back to client: > total_sent = 0 > while total_sent < len(message): > print "debug: send while loop" > > size_sent = s.sendto(message[total_sent:], ("localhost", > 7777) ) > total_sent += size_sent > > print "debug:", total_sent, len(message) > > finally: > s.close() > -------------------------- > > Here's the server output: > > --------------- > debug: start outer while loop > debug: recv while loop > Received message: > hello > debug: send while loop > debug: 6 6 > debug: start outer while loop > debug: recv while loop > Received message: > hello > debug: send while loop > debug: 6 6 > .... > .... > .... > ------------------ You don't make any attempt to break out of the outer loop. (break breaks the innermost loop) From arkanes at gmail.com Wed Aug 1 14:07:55 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 1 Aug 2007 13:07:55 -0500 Subject: Assertion in list comprehension In-Reply-To: <1185991170.993822.175970@z24g2000prh.googlegroups.com> References: <1185982643.001546.138180@e16g2000pri.googlegroups.com> <1185988597.055293.106540@q3g2000prf.googlegroups.com> <1185991170.993822.175970@z24g2000prh.googlegroups.com> Message-ID: <4866bea60708011107i59e46f6fwb64c8f2bade01721@mail.gmail.com> On 8/1/07, beginner wrote: > On Aug 1, 12:35 pm, "Chris Mellon" wrote: > > On 8/1/07, beginner wrote: > > > I see. In fact I want to whole block surrounded by __debug__ to be > optimized away in non-debug runs. If the logic of my program is > correct, the asserts are guaranteed to be true, no matter what the > input is. It is not input checking. > I inferred as much. That's why placing it in a unit or doctest is even better. From stephen.y4ng at gmail.com Tue Aug 14 15:09:51 2007 From: stephen.y4ng at gmail.com (stephen.y4ng at gmail.com) Date: Tue, 14 Aug 2007 19:09:51 -0000 Subject: try/finally exceptions dying Message-ID: <1187118591.965164.6120@w3g2000hsg.googlegroups.com> Hello all, In order to churn through a whole bunch of data sets (some good, some bad..) and get all the errors at the end, (the data will be updated to make it all good later on) I implemented a try/finally block with a higher level handler to catch errors before they propagate to the default handler and crash the program. Something like this: def doStuff(args): if(args says we should keep going): try: stuff finally: update args doStuff(updated args) def runWithErrorHandling(): try: doStuff(args) except (exception1, exception2), data: append exception data to a list of errors runWithErrorHandling() unfortunately, this churns through all the data and I only get the last exception that occurred in the error list, not all of them, as I expected. What is going on? I thought finally always propagated the exception all the way up the stack until it was handled. Any thoughts are appreciated. Stephen From sjmachin at lexicon.net Fri Aug 31 17:54:26 2007 From: sjmachin at lexicon.net (John Machin) Date: Fri, 31 Aug 2007 14:54:26 -0700 Subject: strings (dollar.cents) into floats In-Reply-To: <1188586725.667740.255700@o80g2000hse.googlegroups.com> References: <877incd20i.fsf@benfinney.id.au> <46d75cf3$0$7698$9b4e6d93@newsspool2.arcor-online.net> <1188575044.874256.42960@50g2000hsm.googlegroups.com> <46d84a47$0$1346$834e42db@reader.greatnowhere.com> <1188586725.667740.255700@o80g2000hse.googlegroups.com> Message-ID: <1188597266.831144.201450@m37g2000prh.googlegroups.com> On Sep 1, 4:58 am, MRAB wrote: > On Aug 31, 5:39 pm, David H Wild wrote:> In article , > > Chris Mellon wrote: > > > > I believe that to the degree that "real" accounting was done in those > > > currencies it did in fact use non-decimal bases. Just as people don't > > > use decimal time values (except us crazy computer folk), you're write > > > 1 pound 4 shillings, not 1.333... pounds. > > > When I worked on the British Railways National Payroll system, about 35 > > years ago, we, in common with many large users, wrote our system to deal > > with integer amounts of pennies, and converted to pounds, shillings and > > pence in the output part of the system. > > So you never handled halfpennies? Or farthings? From yinglcs at gmail.com Sun Aug 19 02:55:34 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: Sun, 19 Aug 2007 06:55:34 -0000 Subject: Python library for RTSP protocol Message-ID: <1187506534.781746.317970@z24g2000prh.googlegroups.com> Hi, Can you please tell me if there is a Python library which can talk RTSP/RTP protocol? i.e. i would like to write a script in python to download a video via a RTSP server? Thank you. From cbarton at metavr.com Sun Aug 5 07:31:23 2007 From: cbarton at metavr.com (Campbell Barton) Date: Sun, 05 Aug 2007 21:31:23 +1000 Subject: Best programs written completly in Python In-Reply-To: <20070805112006.GA3558@gmail.com> References: <20070805112006.GA3558@gmail.com> Message-ID: <46B5B50B.8040803@metavr.com> O.R.Senthil Kumaran wrote: > * Franz Steinh?usler [2007-08-05 12:14:38]: > >> wWhat are the best programs in your opinion, written entirly >> in pyhton, divided into categories like: >> a) Games >> b) Utilities/System >> c) Office >> d) Web/Newsreader/Mail/Browser > > Its a difficult question to answer as the software are aplenty and there is no > judgement basis as this one is the best. > > Head on to www.python.org and see for yourself for programs under each > category. > > And moreover, "written entirely in python" is a constrain to find the > programs. Why do you need such a list for? Of course this is totally objective, but that dosnt mean its not a valid question. If you were starting out a project were thinking of writing it in python, you might want to look at whats out there - maybe python has limitations which stops it being a good choice in some situations (for instance?)- on the other hand you might want to see some shining examples that prove the capabilities of python ;) 'Being written entirely in python' - is a bit tricky, often these applications rely on some specific extension or make heavy use of a backend that dosnt come with python (like pygame, pygtk, or py-gstreamer). Games - See Pygame http://www.pygame.org/projects/6 Utilities/System * meld is a really nice diffing tool for linux - http://meld.sourceforge.net * ubuntu have some of their install tools in python. * txt2tags - a great markup language for doc writing. - http://txt2tags.sourceforge.net/ * sound recording/editing - http://www.jokosher.org Office?? - no idea, openoffice can be scripted in python. Web - * isnt bit torrent python?, probably lots of stuff but I dont know of them ;) From mark.dufour at gmail.com Mon Aug 20 08:31:40 2007 From: mark.dufour at gmail.com (Mark Dufour) Date: Mon, 20 Aug 2007 14:31:40 +0200 Subject: Shed Skin Python-to-C++ compiler 0.0.23 Message-ID: <8180ef690708200531r7eca18b1y96c65b72b0ddce35@mail.gmail.com> Hi all, I have just released Shed Skin 0.0.23. It doesn't contain the type inference scalability improvements I was working on, but it does have quite a few bug fixes and minor feature additions. Here's a list of changes: -support for __iadd__, __imul__ and such (except __ipow__ and __imod__) -some overdue set optimizations -fix for string formatting problem (%% did not always work) -extension module stability fixes -fix for particular inheritance problem -other minor bugfixes, cleanups, and error messages I could really use some systematic help in pushing Shedskin further. Some ideas: -send in bug reports - these are extremely valuable and motivating to me, yet I don't receive many.. -find out why test 148 is currently broken under windows -add datetime, re or socket support -look into supporting custom classes in generated extension modules -write a Shedskin tutorial for 'novice' programmers -systemically test performance and suggest and work on improvements -investigate replacements for std::string and __gnu_cxx::hash_set -perform janitorial-type work in ss.py and lib/builtin.?pp -support extension modules under OSX (OSX gives me accute mental RSI) -add more tests to unit.py Thanks, Mark Dufour. -- "One of my most productive days was throwing away 1000 lines of code" - Ken Thompson From xavier.martinezhidalgo at gmail.com Wed Aug 29 05:07:41 2007 From: xavier.martinezhidalgo at gmail.com (xavim) Date: Wed, 29 Aug 2007 09:07:41 -0000 Subject: Error handling in file generation (Pythonic way: with / decorators?) In-Reply-To: <1188377932.955314.104570@r29g2000hsg.googlegroups.com> References: <1188377932.955314.104570@r29g2000hsg.googlegroups.com> Message-ID: <1188378461.388224.164030@50g2000hsm.googlegroups.com> On Aug 29, 10:58 am, xavim wrote: > (...) > try: > (...) > except: > os.remove(dictpath) This should read:: try: (...) except: os.remove(dictpath) raise Sorry. From victor.lebrun at gmail.com Thu Aug 2 12:01:15 2007 From: victor.lebrun at gmail.com (vml) Date: Thu, 02 Aug 2007 16:01:15 -0000 Subject: python 3.0, pywin32 and scipy Message-ID: <1186070475.659511.24130@q3g2000prf.googlegroups.com> Hello, I am trying to promote python in my job, my collegue only see matlab and microsoft scripting language. I understood that there willl be no backward compatibility between python 2.x and 3.0, does it means that: - my script using pywin32 for the COM layer and scipy for the maths won't work under 3.0 - will we have the equivalent of pywin32 and scipy in python ? I will be incharge of designing a python module which will be a 'matrix calculator' in our current software. Will it be compatible with python 3.0 ? I guess no. What can I answer to my collegue who will say 'Python is changing and the stuff you are doing now is useless'? how can I argue against matlab and c# ? thanks very much From eggie5 at gmail.com Thu Aug 9 22:28:34 2007 From: eggie5 at gmail.com (eggie5) Date: Fri, 10 Aug 2007 02:28:34 -0000 Subject: beginner whitespace question In-Reply-To: References: <1186703261.136506.208660@x35g2000prf.googlegroups.com> <1186703525.591462.122140@m37g2000prh.googlegroups.com> <1186704161.334597.218750@z24g2000prh.googlegroups.com> <1186707164.095766.243480@q3g2000prf.googlegroups.com> <1186708404.901323.204730@g12g2000prg.googlegroups.com> Message-ID: <1186712914.174266.300080@j4g2000prf.googlegroups.com> On Aug 9, 6:31 pm, James Stroud wrote: > James Stroud wrote: > > def __unicode__(self): That's so goofy..... > > return self.choice > > Laughing to hard at the tab & spaces thing to notice the lack of > indentation here. > > James > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ From aisaac at american.edu Fri Aug 31 10:36:58 2007 From: aisaac at american.edu (Alan Isaac) Date: Fri, 31 Aug 2007 14:36:58 GMT Subject: create Powerpoint via com In-Reply-To: <1188567291.037504.232850@r34g2000hsd.googlegroups.com> References: <1188500822.869925.194430@e9g2000prf.googlegroups.com> <1188567291.037504.232850@r34g2000hsd.googlegroups.com> Message-ID: >>How about chart creation (in Ppt 2003)? >>I do not see how to do this with Python. kyosohma at gmail.com wrote: > You probably need to browse the COM object using PythonWin, which is a > part of the ActiveState distro. You can also use Python's builtin > function, dir, to find out various methods of COM. > > Here's some info in messing with charts in Excel, which should be > similar to chart manipulation in PowerPoint. > > http://mail.python.org/pipermail/python-win32/2005-June/003511.html > http://mail.python.org/pipermail/python-win32/2003-March/000839.html > http://www.thescripts.com/forum/thread21565.html > http://mathieu.fenniak.net/plotting-in-excel-through-pythoncom/ Thanks! Alan From evan at yelp.com Thu Aug 2 01:22:53 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 1 Aug 2007 22:22:53 -0700 Subject: access the name of my method inside it In-Reply-To: <1185973639.234450.305690@g12g2000prg.googlegroups.com> References: <1185959202.302467.276080@x35g2000prf.googlegroups.com> <5hb1ebF3inuf2U6@mid.uni-berlin.de> <1185973639.234450.305690@g12g2000prg.googlegroups.com> Message-ID: On 8/1/07, james_027 wrote: > Hi, > > On Aug 1, 5:18 pm, Marc 'BlackJack' Rintsch wrote: > > On Wed, 01 Aug 2007 09:06:42 +0000, james_027 wrote: > > > for example I have this method > > > > > def my_method(): > > > # do something > > > > > # how do I get the name of this method which is my_method here? > > > > Why do you need this? There are ways but those are not really good for > > production code. > > > > I am going to use this in Django. I am trying to implement a > permission here, where in the database store the methods that the user > are allowed to execute. for example if the method is def > create_event(): the method will look for create_event in the database > to see if it allow to be execute. > > Thanks. > james I would suggest instead setting an attribute on the function object via a decorator, and then have your mod_python handler check for the presence of that attribute on the function that is being called, rather than doing a DB lookup. -- Evan Klitzke From vedrandekovic at v-programs.com Tue Aug 7 13:28:49 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Tue, 07 Aug 2007 10:28:49 -0700 Subject: distutils In-Reply-To: References: <1186489676.042901.236140@w3g2000hsg.googlegroups.com> <1186497517.224280.126070@22g2000hsm.googlegroups.com> Message-ID: <1186507729.075722.21300@57g2000hsv.googlegroups.com> On 7 kol, 18:00, Steve Holden wrote: > vedrandeko... at v-programs.com wrote: > > On 7 kol, 14:53, Steve Holden wrote: > >> vedrandeko... at v-programs.com wrote: > >>> Hello again, > >>> Is there any patch for python "distutils", for this > >>>>>> from distutils import log,dir_util > >>> ImportError: cannot import name log > >> What version of Python are you running with? It looks as though there > >> may be something wrong with your installation if it's recent: > > >> sholden at bigboy ~/Projects/Python > >> $ python > >> Python 2.5.1 (r251:54863, May 18 2007, 16:56:43) > >> [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin > >> Type "help", "copyright", "credits" or "license" for more information. > >> >>> from distutils import log > >> >>> import distutils.log > > > Hello, > > > My version of python is 2.4 and I'am running it with Windows XP > > Your installation must be corrupted, then: > > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > C:\Steve>\python24\python > Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> from distutils import log > >>> > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- Hi, Is there any other solution I need this for script installing with setuptools,now I was install and Python 2.5 too,but same error again. PS: I was try your previously example also: cd c:\Python24\python then: >>> from distutils import log - but same error again any other solution? Regards, Vedran From mirandacascade at yahoo.com Tue Aug 14 15:24:11 2007 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: Tue, 14 Aug 2007 12:24:11 -0700 Subject: post xml payload with urllib In-Reply-To: References: Message-ID: <1187119451.527124.192460@x35g2000prf.googlegroups.com> On Aug 14, 11:57 am, brad wrote: > Has anyone sent an xml payload via post using urllib? Haven't used urllib, but have used urllib2 to do a POST. Might something like this work... import urllib2 logon_request = """ "the_password" "the_user" """ req = urllib2.Request("https://127.0.0.1/api/version/xml", data=logon_request) openObj = urllib2.urlopen(req) response = openObj.read() From steve at holdenweb.com Fri Aug 31 11:05:01 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 31 Aug 2007 11:05:01 -0400 Subject: Setting a read-only attribute In-Reply-To: <1188509700.915517.178440@z24g2000prh.googlegroups.com> References: <1188509700.915517.178440@z24g2000prh.googlegroups.com> Message-ID: tleeuwenburg at gmail.com wrote: > I have an object and wish to set an attribute on it which, > unfortunately for me, is read-only. > > How can I go about this? > This seems like a bizarre requirement. Why is the attribute read-only in the first place? How is the read-only mechanism enforced? Is the object created in Python or in an extension module? Do you have any evidence that "setting" the attribute will effect the required change in the behavior of the object. A little more information would be helpful. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From cai.haibin at gmail.com Wed Aug 1 09:07:19 2007 From: cai.haibin at gmail.com (james_027) Date: Wed, 01 Aug 2007 13:07:19 -0000 Subject: access the name of my method inside it In-Reply-To: <5hb1ebF3inuf2U6@mid.uni-berlin.de> References: <1185959202.302467.276080@x35g2000prf.googlegroups.com> <5hb1ebF3inuf2U6@mid.uni-berlin.de> Message-ID: <1185973639.234450.305690@g12g2000prg.googlegroups.com> Hi, On Aug 1, 5:18 pm, Marc 'BlackJack' Rintsch wrote: > On Wed, 01 Aug 2007 09:06:42 +0000, james_027 wrote: > > for example I have this method > > > def my_method(): > > # do something > > > # how do I get the name of this method which is my_method here? > > Why do you need this? There are ways but those are not really good for > production code. > I am going to use this in Django. I am trying to implement a permission here, where in the database store the methods that the user are allowed to execute. for example if the method is def create_event(): the method will look for create_event in the database to see if it allow to be execute. Thanks. james From gagsl-py2 at yahoo.com.ar Fri Aug 24 15:21:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 24 Aug 2007 16:21:25 -0300 Subject: how to tar with python References: <93066C069973ED448DC2BCEA9C44A7383BE2EF@efmailx> Message-ID: En Fri, 24 Aug 2007 10:03:30 -0300, Brian McCann escribi?: > I'm trying to tar the contents of a directory "test" which contains > 3 files foo1.xml ,foo2.xml, foo3.xml > in my current directory /home/pythonbox/tmp I have the directory "test" > if I run the below script it fails with the below error, but the files > exist in the directory test Add a print statement and see what you get: > tfile = tarfile.open("files.tar.gz", 'w:gz') > files = os.listdir("test") > for f in files: print f > tfile.add(f) > tfile.close See -- Gabriel Genellina From larry.bates at websafe.com Thu Aug 2 10:34:16 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 02 Aug 2007 09:34:16 -0500 Subject: Determining if file is valid image file In-Reply-To: <1186064275.652416.250540@d55g2000hsg.googlegroups.com> References: <1186064098.587590.91210@g4g2000hsf.googlegroups.com> <1186064275.652416.250540@d55g2000hsg.googlegroups.com> Message-ID: Andr? wrote: > On Aug 2, 11:14 am, Andr? wrote: >> Other than installing PIL, is there a "simple" way using Python only >> to determine if a file is a valid image file? >> >> I'd be happy if I could at least identify valid images files for gif, >> jpeg and png. Pointers to existing modules or examples would be >> appreciated. >> >> The reason why I'd prefer not using PIL is that I'd like to bundle >> such a function/module in my app. >> >> Andr? > > I should have added: I'm interesting in validating the file *content* > - not the filename :-) > And what's wrong with bundling PIL in your application? -Larry From steve at holdenweb.com Thu Aug 16 18:16:13 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 16 Aug 2007 18:16:13 -0400 Subject: Pass by reference or by value? In-Reply-To: <496954360708161501s541bddb7vfe168e4863f7f1e@mail.gmail.com> References: <496954360708161402x58faba47x7a6eae6e68f81d4@mail.gmail.com> <496954360708161501s541bddb7vfe168e4863f7f1e@mail.gmail.com> Message-ID: <46C4CCAD.3080104@holdenweb.com> Robert Dailey wrote: > So immutable objects cannot be modified directly? I guess this means > integers are immutable and the act of assigning to one is a completely > new definition? Correct. A new value is bound to the name or item on the left-hand side - remember, all variables are pointers to values, there's no way to replace the value of a variable because of the automatic dereferencing. And yes, immutable objects can't be modified. At all, period. Hence the name. > So if I were to create a class called Integer and give > it a .set() method, this would allow me to create mutable integers, and > thus passing in an object of type class Integer would allow me to modify > the value from inside the function? > Well, the .set() method wouldn't be called automatically on an assignment statement but yes, if you passed an Integer object into your function and called its .set() method from inside then it should work. As long as you get your mutable integer implementation correct, of course ;-). I'd suggest delegating everything except the .set() method to the underlying integer value. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From kyosohma at gmail.com Tue Aug 7 09:29:03 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 07 Aug 2007 06:29:03 -0700 Subject: get position is scrolled wxScrolledWindow In-Reply-To: References: Message-ID: <1186493343.051931.238670@i38g2000prf.googlegroups.com> On Aug 6, 11:20 pm, Astan Chee wrote: > Hi, > I have a wxScrolledWindow, and some things drawn on it. I've hooked the > left click event to a certain function I've got. Anyway, everytime I do > a event.GetPosition() on the position of the mouse on the > wxScrolledWindow, it returns the physical location or position of the > mouse. Does anyone have any examples or advice on how to get the real or > position of the window including where it has been scrolled? > Thanks > Astan This sounds like a job for the wxPython list. You should try posting there: http://www.wxpython.org/maillist.php I also found this: http://aspn.activestate.com/ASPN/Mail/Message/wxpython-users/3536900 Mike From iclark at mail.ewu.edu Fri Aug 17 18:51:49 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Fri, 17 Aug 2007 15:51:49 -0700 Subject: Question on SPE and pwintypes.dll In-Reply-To: <1187357898.740425.33170@r29g2000hsg.googlegroups.com> References: <1187357898.740425.33170@r29g2000hsg.googlegroups.com> Message-ID: Gerry wrote: >... but the OS wasn't migrated ... There's your problem right there. It's hard to run most software these days without an OS. Ian From frikker at gmail.com Fri Aug 3 08:54:57 2007 From: frikker at gmail.com (frikk) Date: Fri, 03 Aug 2007 12:54:57 -0000 Subject: Memory Leak with Tkinter Canvas (Python 2.5 Win32) In-Reply-To: References: <1186068851.011344.322980@i13g2000prf.googlegroups.com> Message-ID: <1186145697.617374.189030@o61g2000hsh.googlegroups.com> On Aug 3, 2:26 am, "Hendrik van Rooyen" wrote: > "frikk" wrote: > > 1. ....... Am I somehow leaving > > objects laying around that aren't being deleted? Is create_rectangle > > not the appropriate function to use?) > > Try calling the canvas's delete method with the old rectangle before > making a new one. > > - Hendrik Hey guys- Both of your suggestions were perfect - I was just unaware I was actually creating new *object* instead of drawing on the canvas. noob mistake. Thanks again! -Blaine From Dominic at PLEASEASK.co.uk Thu Aug 9 10:46:49 2007 From: Dominic at PLEASEASK.co.uk (special_dragonfly) Date: Thu, 9 Aug 2007 15:46:49 +0100 Subject: tests References: <1186666919.456036.120270@d30g2000prg.googlegroups.com> <1186670584.148181.180040@r34g2000hsd.googlegroups.com> Message-ID: <46bb2511$0$10103$7b0f0fd3@mistral.news.newnet.co.uk> wrote in message news:1186670584.148181.180040 at r34g2000hsd.googlegroups.com... > On Aug 9, 4:04 pm, brad wrote: >> kyoso... at gmail.com wrote: >> > You should be able to read chunks of each file in binary mode and do a >> > compare to check for equality. Some kind of loop should do the trick. >> >> Why not a simple md5 or sha with the hash library? > > Or even: > > http://docs.python.org/lib/module-filecmp.html > My understanding of reading that is that it only looks at the file names themselves and not their contents. So whether filename1=filename2 and in the case of the function below it, whether one directory has files which are in the other. Correct me if I'm wrong. Dom P.S. md5 or sha hash is what I'd go for, short of doing: MyFirstFile=file("file1.xls") MySecondFile=file("file2.xls") If MyFirstFile==MySecondFile: print "True" although this won't tell you where they're different, just that they are... From junkeun.park at gmail.com Thu Aug 9 19:06:14 2007 From: junkeun.park at gmail.com (Jun-geun Park) Date: Thu, 09 Aug 2007 19:06:14 -0400 Subject: Threaded Design Question In-Reply-To: <1186683909.797328.68770@i13g2000prf.googlegroups.com> References: <1186683909.797328.68770@i13g2000prf.googlegroups.com> Message-ID: half.italian at gmail.com wrote: > Hi all! I'm implementing one of my first multithreaded apps, and have > gotten to a point where I think I'm going off track from a standard > idiom. Wondering if anyone can point me in the right direction. > > The script will run as a daemon and watch a given directory for new > files. Once it determines that a file has finished moving into the > watch folder, it will kick off a process on one of the files. Several > of these could be running at any given time up to a max number of > threads. > > Here's how I have it designed so far. The main thread starts a > Watch(threading.Thread) class that loops and searches a directory for > files. It has been passed a Queue.Queue() object (watch_queue), and > as it finds new files in the watch folder, it adds the file name to > the queue. > > The main thread then grabs an item off the watch_queue, and kicks off > processing on that file using another class Worker(threading.thread). > > My problem is with communicating between the threads as to which files > are currently processing, or are already present in the watch_queue so > that the Watch thread does not continuously add unneeded files to the > watch_queue to be processed. For example...Watch() finds a file to be > processed and adds it to the queue. The main thread sees the file on > the queue and pops it off and begins processing. Now the file has > been removed from the watch_queue, and Watch() thread has no way of > knowing that the other Worker() thread is processing it, and shouldn't > pick it up again. So it will see the file as new and add it to the > queue again. PS.. The file is deleted from the watch folder after it > has finished processing, so that's how i'll know which files to > process in the long term. > > I made definite progress by creating two queues...watch_queue and > processing_queue, and then used lists within the classes to store the > state of which files are processing/watched. > > I think I could pull it off, but it has got very confusing quickly, > trying to keep each thread's list and the queue always in sync with > one another. The easiset solution I can see is if my threads could > read an item from the queue without removing it from the queue and > only remove it when I tell it to. Then the Watch() thread could then > just follow what items are on the watch_queue to know what files to > add, and then the Worker() thread could intentionally remove the item > from the watch_queue once it has finished processing it. > > Now that I'm writing this out, I see a solution by over-riding or > wrapping Queue.Queue().get() to give me the behavior I mention above. > > I've noticed .join() and .task_done(), but I'm not sure of how to use > them properly. Any suggestions would be greatly appreciated. > > ~Sean > 1) Use a (global) hash table and a mutex on it. Before a worker thread starts processing a file, have the worker acquire the mutex, add the filename into a global dictionary as a key, and release the mutex. Then, when the watcher thread attempts to read a file, it only has to check whether the filename is on the table. If different files may have a same name, you can also use size or some other signatures. Also, I think basic operations on primitive types on Python are atomic so you don't actually need mutex, but in threaded programs, it's always a good habit to use mutexes explicitly. 2) If the watcher thread doesn't spend much time in "recognizing" files to process, simply make the watcher thread reads many(or all) files in the directory, put them all in the queue, and wait until all items in the queue are processed using .join(). Workers can indicate that the processing of the last dequeued item is done by calling .task_done() (As soon as all items are flaged "task_done()", join() will unblock.) After processing of files on the queue are all done, watcher can move or remove processed files and read the directory again. Of course, you need to keep track of "recognized" files of that turn. From horpner at yahoo.com Tue Aug 7 10:37:52 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 07 Aug 2007 14:37:52 GMT Subject: All leading tabs or all leading spaces - why isn't that enforced? References: Message-ID: On 2007-08-07, Omari Norman wrote: >> I suppose we Pythonistas are just too permissive for our own good. >> Consider the opportunity to use mixed tabs and spaces a piece of rope of >> your preferred length ... > > I thought I remembered reading somewhere that Python 3000 will > ban tabs as indentation characters, but now I can't turn up a > link for it... Tabs are going to be banned in the C Style Guide for Python 3000 source code, but they aren't being banned from Python 3000 code. -- Neil Cerutti The concert held in Fellowship Hall was a great success. Special thanks are due to the minister's daughter, who labored the whole evening at the piano, which as usual fell upon her. --Church Bulletin Blooper From yozara at terra.es Fri Aug 24 07:44:54 2007 From: yozara at terra.es (Zara) Date: Fri, 24 Aug 2007 13:44:54 +0200 Subject: Regular expression use References: Message-ID: On 24 Aug 2007 10:58:46 GMT, nmm1 at cus.cam.ac.uk (Nick Maclaren) wrote: > >For reasons that I won't explain, as they are too complicated >and not terribly relevant, I am interested in discovering what >people actually use regular expressions for. Not the subject >domain, but the construction of the regular expressions. > >I know about computer scientists and parsing, and I know about >the use of relatively simple ones for things like extracting >HTML links from Web pages. But I don't have much feel for the >(probably rare but difficult) uses of more complex ones for >other purposes. I have heard of several such uses, but don't >have an overall idea of what is going on. > >Any pointers appreciated, to more-or-less anything. > In the linked project, regular expression are used to parse communication protocol responses, file contents, and interporocess communcation (at least). They may not be pretty elegant solutions, but this is the first project I made in python (and also with regex)!! NOTE: I am the author, and I swear the application is free of viruses, it has been fully developed with a python and a WingWare standar installation, and it will only deposit some files on your $python$/Lib/site-packages folder. Any comments welcome. NOTE2: Software in spanish, but it should not be pretty difficult to follow (I hope!) best regards, Zara http://www.albalaing.com/Firmware.aspx?id_firmware=2359 From proteusguy at gmail.com Tue Aug 21 12:45:41 2007 From: proteusguy at gmail.com (proteusguy at gmail.com) Date: Tue, 21 Aug 2007 16:45:41 -0000 Subject: yet another indentation proposal In-Reply-To: References: Message-ID: <1187714741.642908.139930@x40g2000prg.googlegroups.com> On Aug 18, 2:22 pm, "Aaron" wrote: > Hello all. > > I realize that proposals dealing with alternatives to indentation have been > brought up (and shot down) before, but I would like to take another stab at > it, because it is rather important to me. > > I am totally blind, and somewhat new to Python. I put off learning Python > for a long time, simply because of the indentation issue. There is no easy > way for a screenreader user, such as my self, to figure out how much a > particular line of code is indented. A sited person simply looks down the > column to make sure that everything lines up. I, on the other hand, > generally find my self counting a lot of spaces. Very interesting 'reading' code verbally. I would think this would be far less efficient than using a braille line display, especially if there were a multi-line display which I'm not sure exists (but should). Anyway, as someone who is a very fond of python's use of indentation for flow control, I also see that it is not always appropriate for EVERY form of computing I'd like to apply python too and I wish there were an alternative control flow form which was considered valid in all respects but frowned upon when not used in the exception cases intended. Also it should be a form in which a parser could easily convert back and forth from at ease so you could code in one format and deploy in another. Besides your excellent example, the context that I have in mind is embedded python running in a web browser ala javascript. You absolutely cannot count on whitespace when your code is going through the parser/converter gauntlet that the typical html page must go through before being delivered to its requestor. As a student of language design I find javascript an abomination and have long wondered whether or not this dependency on whitespace hasn't taken python out of the running from being a very popular and appropriate contender. (I realize that the restricted execution environment of old python was abandoned but maybe browser python is a strict subset?) I really am not at the point of making this a proposal. Really I'm just curious as to whether or not I'm the only person who thinks this and would like to see if the concept has any traction. This is no low impact concept so I'm not holding my breath. I will say, however, that the web browser would be a far more pleasant development environment if it spoke python rather than javascript. I feel strongly that its the best internet service language (wonderful std libs) and its OO and functional paradigm would play nicely in a browser environment. I have python on all my computers regardless of operating system and cpu. I have python embedded in C++ apps and C++ apps embedded in python. Python runs on my phone! Python runs on the JVM and the CLR. Python runs everywhere - except my browser. ...just dreaming... -- Ben From aleax at mac.com Sun Aug 19 16:04:17 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 19 Aug 2007 13:04:17 -0700 Subject: Parser Generator? References: <_6mdnZxbdNKTVFrbnZ2dnUVZ_tqtnZ2d@comcast.com> Message-ID: <1i33g9h.1i48q26dmp7l5N%aleax@mac.com> Jack wrote: > Thanks for the suggestion. I understand that more work is needed for natural > language > understanding. What I want to do is actually very simple - I pre-screen the > user > typed text. If it's a simple syntax my code understands, like, Weather in > London, I'll > redirect it to a weather site. Or, if it's "What is ... " I'll probably > redirect it to wikipedia. > Otherwise, I'll throw it to a search engine. So, extremelyl simple stuff ... """ NLTK ? the Natural Language Toolkit ? is a suite of open source Python modules, data sets and tutorials supporting research and development in natural language processing. """ Alex From jvines at arl.army.mil Fri Aug 3 12:16:04 2007 From: jvines at arl.army.mil (Vines, John (Civ, ARL/CISD)) Date: Fri, 3 Aug 2007 12:16:04 -0400 Subject: Idlelib TreeWidget (UNCLASSIFIED) Message-ID: <56D23B61D58733478FA4E0C1434AAC582834C6@ARLABML02.DS.ARL.ARMY.MIL> Classification: UNCLASSIFIED Caveats: NONE Does anyone have any experience using the idlelib TreeWidget module? I am using it to display XML files and would like to include some editing capabilities. Does anyone have any examples I could take a look at? Thanks, John Classification: UNCLASSIFIED Caveats: NONE -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleax at mac.com Wed Aug 1 11:04:58 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 1 Aug 2007 08:04:58 -0700 Subject: Floats as keys in dict References: Message-ID: <1i25pz7.3m2bya88wujkN%aleax@mac.com> Brian Elmegaard wrote: > I am making a script to optimiza by dynamic programming. I do not know > the vertices and nodes before the calculation, so I have decided to > store the nodes I have in play as keys in a dict. > > However, the dict keys are then floats and I have to round the values > of new possible nodes in each step. When profiling I see that the most > time consuming part of my script is rounding. > > Is there a faster way than round() or is there a better way to test > than 'in' or should I store the keys in another way than a dict? You may want to consider keeping a sorted list and using standard library module bisect for searches and insertions -- its behavior is O(log N) for a search, O(N) for an insertion, but it might be that in your case saving the rounding could be worth it. Otherwise, you need to consider a different container, based either on comparisons (e.g. AVL trees, of which there are several 3rd party implementations as Python extensions) or on a hashing function that will give the same hash for two numbers that are "close enough" (e.g., hash ignoring the lowest N bits of the float's mantissa for some N). round() operates on decimals and that may not be as fast as working on binary representations, but, to be fast, a helper function giving the "hash of a binary-rounded float" would have to be coded in C (or maybe use psyco). Alex From dejanews at email.com Sat Aug 18 07:13:45 2007 From: dejanews at email.com (samwyse) Date: Sat, 18 Aug 2007 06:13:45 -0500 Subject: unexpected optparse set_default/set_defaults behavior In-Reply-To: <1187359921.637383.268380@22g2000hsm.googlegroups.com> References: <1187359921.637383.268380@22g2000hsm.googlegroups.com> Message-ID: mbeachy at gmail.com wrote: > Some rather unexpected behavior in the set_default/set_defaults > methods for OptionParser that I noticed recently: [...] > Why does set_default not raise an exception when passed a key that it > doesn't recognize? > > Bad typysts bewaer. > > The only reason I can think not to raise an exception is so that > defaults can be defined before the options are added. Is there some > use case that I'm not thinking of here? I realize that changing this > could break some existing scripts, but I'm still tempted to file this > as a bug. If you file it as a bug then I can assure you that you'll be told of a long list of use-cases that depend on that feature. From gdamjan at gmail.com Wed Aug 1 13:45:31 2007 From: gdamjan at gmail.com (Damjan) Date: Wed, 01 Aug 2007 19:45:31 +0200 Subject: Python IMAP web-access Message-ID: <46b0c675$0$90272$14726298@news.sunsite.dk> Is there some project that implements web access to an IMAP store? Maybe something AJAXy like http://roundcube.net/?? -- damjan From gagsl-py2 at yahoo.com.ar Mon Aug 20 23:46:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 20 Aug 2007 20:46:16 -0700 Subject: mode parameter in popen2-4 In-Reply-To: <46c9ed0d$0$8173$88260bb3@free.teranews.com> References: <46c9ed0d$0$8173$88260bb3@free.teranews.com> Message-ID: <1187667976.155385.33740@g4g2000hsf.googlegroups.com> On 20 ago, 17:26, Tobiah wrote: > In the popen docs, a file like object is returned, > and may be read to or written to depending on the > 'mode' parameter ('r', or 'w'). > > Why is the mode parameter needed for popen2 and greater, > when both a stdin and stdout object is returned? One > wouldn't want to 'append' to a stream.... is it because > binary mode can still be turned on and off this way? Exactly. For popen[234] the mode parameter can be either 't' or 'b', not 'r' or 'w' - which you could have learned easily reading the documentation at and -- Gabriel Genellina From bohemaida at gmail.com Mon Aug 6 18:22:05 2007 From: bohemaida at gmail.com (Bo) Date: Mon, 06 Aug 2007 15:22:05 -0700 Subject: step through .py file in a .NET application written in C# in Visual Studio Message-ID: <1186438925.541501.235800@g4g2000hsf.googlegroups.com> Hello All, I am experimenting IronPython in Visual Studio. Here is what I have, what I did and what I want 1. I have installed Visual Studio SDK 4.0 according to this blog http://blogs.msdn.com/aaronmar/archive/2006/02/16/a-bit-more-on-ironpython.aspx If I run Visual Studio under Experimental Hive, a Python file opened is color coded. 2. Also, my computer has apparently installed some IronPython DLL because my Visual Studio can recoginize the following class: IronPython.Hosting.PythonEngine. If I declare something like the following in Visual Studio: public static class MyPythonClass { private static IronPython.Hosting.PythonEngine MY_ENGINE; //suppose I have created an instance of PhythonEngine and assigned to MY_ENGINE ............ } If I do "Go to Definition" of PythonEngine, I can navigate to the Definition of PythonEngine, but it is from MetaData. 3. In my .NET application (written in C#) , I can invoke the execution of an external python file using something like: MyPythonClass.MY_ENGINE.ExecuteFile("myPythonFileWithAbsolutePath.py") The python file (myPythonFileWithAbsolutePath.py) can be executed all right, but I want to step through it to debug it. Any suggestions on how to do it? Thanks a bunch. Bo From bj_666 at gmx.net Wed Aug 22 03:47:32 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Aug 2007 07:47:32 GMT Subject: File Read Cache - How to purge? References: <1187669203.698637.81990@i38g2000prf.googlegroups.com> <87veb9xb7y.fsf@mulj.homelinux.net> <87ir781afk.fsf@mulj.homelinux.net> Message-ID: <5j280kF3sh73oU2@mid.uni-berlin.de> On Wed, 22 Aug 2007 06:05:03 +0200, Hrvoje Niksic wrote: > Nick Craig-Wood writes: > >> If you are running linux > 2.6.18 then you can use >> /proc/sys/vm/drop_caches for exactly that purpose. >> >> http://www.linuxinsight.com/proc_sys_vm_drop_caches.html > > That URL claims that you need to run "sync" before dropping the cache, > and so do other resources. I wonder if that means that dropping the > cache is unsafe on a running system. Of course not. It means that dirty pages are not dropped, so if you really want to invalidate as much cache memory as possible you have to ``sync`` before. Ciao, Marc 'BlackJack' Rintsch From vedrandekovic at v-programs.com Thu Aug 16 15:29:51 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Thu, 16 Aug 2007 12:29:51 -0700 Subject: wxpython log redirect Message-ID: <1187292591.151231.41440@b79g2000hse.googlegroups.com> Hello, Why this wx example don't return \nHELLO WORLD and other text in same window: import wx import logging import sys def nekaj(): print "\nHELLO WORLD" class WxLog(logging.Handler): def __init__(self, ctrl): logging.Handler.__init__(self) self.ctrl = ctrl def emit(self, record): self.ctrl.AppendText(self.format(record)+"\n") class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="logging test") sizer = wx.BoxSizer(wx.VERTICAL) log = wx.TextCtrl(self, style=wx.TE_MULTILINE) rootLogger = logging.getLogger('') rootLogger.setLevel(logging.DEBUG) hdlr = WxLog(log) hdlr.setFormatter(logging.Formatter('%(levelname)s | %(name)s | %(message)s [@ %(asctime)s in %(filename)s:%(lineno)d]')) rootLogger.addHandler(hdlr) rootLogger.debug(str(sys.stdout)) nekaj() # goes to the function nekaj if __name__ =="__main__": app = wx.App(0) frame = MainFrame() frame.Show() app.MainLoop() Regards, Vedran From istvan.albert at gmail.com Wed Aug 29 09:08:32 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Wed, 29 Aug 2007 13:08:32 -0000 Subject: Haskell like (c:cs) syntax In-Reply-To: References: Message-ID: <1188392912.357697.192080@w3g2000hsg.googlegroups.com> On Aug 29, 8:12 am, Ricardo Ar?oz wrote: > >> Caution : L[0] and L[1:] are COPIES of the head and tail of the list. > Sorry, should have written RETURN copies instead of ARE copies. L[0] does not return a copy, it does what is says, returns the object stored at index 0. i. From steve at holdenweb.com Mon Aug 6 23:52:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 06 Aug 2007 23:52:43 -0400 Subject: All leading tabs or all leading spaces - why isn't that enforced? In-Reply-To: References: Message-ID: John Nagle wrote: > One can argue over tab vs. space indentation, but mixing the two > is just wrong. Why not have CPython report an error if a file has > both leading tabs and leading spaces? I know that was proposed at > some point, but I don't think it ever went in. That would catch a > common error introduced during maintenance. > I suppose we Pythonistas are just too permissive for our own good. Consider the opportunity to use mixed tabs and spaces a piece of rope of your preferred length ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From cai.haibin at gmail.com Wed Aug 22 01:41:10 2007 From: cai.haibin at gmail.com (james_027) Date: Wed, 22 Aug 2007 05:41:10 -0000 Subject: for statement on empty iterable In-Reply-To: <7xabsk3zgm.fsf@ruckus.brouhaha.com> References: <1187760507.951994.50310@q4g2000prc.googlegroups.com> <7xabsk3zgm.fsf@ruckus.brouhaha.com> Message-ID: <1187761270.713307.224570@i38g2000prf.googlegroups.com> hi Paul, > > That doesn't crash or anything like that, but it also doesn't > set the index variable, which can cause confusion in some situations. Thanks for your quick answer ... Actually I was thinking how do I access the index inside a for statement? Can you help Thanks james From uymqlp502 at sneakemail.com Wed Aug 29 19:41:27 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Wed, 29 Aug 2007 16:41:27 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> Message-ID: <1188430887.481586.106760@l22g2000prc.googlegroups.com> > But it's always a good idea to make your software "correct and as > reliable as possible", isn't it? The problem is the external constraints > on the project. As the old saying goes: "Cheap, fast, reliable: choose > any two". If you are suggesting that "programming by contract" is not appropriate for every application, you will get no argument from me. All I am suggesting is that having the option to use it when you need it is very desirable, and it can possibly enhance the versatility of Python by making Python more suitable for *some* mission-critical applications. I once read a book on something called SPARK Ada, which also supports programming by contract. I was pleasantly surprised to discover yesterday that support for the such methods is also available for Python. However, the support would obviously be a bit stronger if it were in the core Python distribution. What I really like about the implementation I cited above is that the invariants and the pre and post-conditions can all be put right in the doc string at the beginning of each class or function. You can think of it as a detailed specification of the intent (or of some of the requirements or constraints) of the class or function -- which can be *automatically* checked during testing. It can also be used for explicit type checking. It's like having some of your most critical unit tests built right into your code. It may make your code very verbose, but it will also be very complete. From DouhetSukd at gmail.com Fri Aug 17 16:32:58 2007 From: DouhetSukd at gmail.com (DouhetSukd at gmail.com) Date: Fri, 17 Aug 2007 13:32:58 -0700 Subject: help on object programing In-Reply-To: <1187370429.041002.205500@d55g2000hsg.googlegroups.com> References: <1187370429.041002.205500@d55g2000hsg.googlegroups.com> Message-ID: <1187382778.865479.180280@r23g2000prd.googlegroups.com> > how can i define my variables so that there are valid outside the > class??? Not to be obnoxious, but your sample code has a number of fairly big conceptual issues (like subclassing self and assigning 32 at the big class level and printing 'list' which is a built-in type). Been there myself - it took me a while to understand class vs. instance variables. You are also using fairly advanced techniques such as embedded classes which look above a newbie level. I took the liberty to comment and "fix" up your code a bit so that it runs: #classes either inherit or not and signify that in parenthesis. inheriting 'self' makes no sense #for a class declaration. but it does make perfect sense to have 'self' as a param to a class method (def) class big: #class-level variable x = 32 #changed to mylist to avoid confusion with list built-in. mylist = [] #this is a normal instance method - 'self' refers to the class instance you just created. def inside (self): #is this really what you wanted? an embedded class - syntaxically correct, but not used often class small: # a new class defined inside the first y = 348 #ok, now I am referring to the mylist variable associated (bound in python-speak) to the big class. #y is defined here so no need to do anything big.mylist.append(y) # send the value to first list #same with big.x big.mylist.append(big.x) #instantiate the class, because you are calling an instance method (i.e. you need to have created an instance to use that method) #call the call mybig = big().inside() #refer to the mylist variable declared at the class, not instance level. #class level means any other calls you make will alter that variable print 'my class level mylist variable:',big.mylist console output: my class level mylist variable: [348, 32] Can you perhaps rephrase your requirements to indicate what you want to achieve? Strictly speaking, it looks like you could do this: class Big: def getlist(self): return [348,32] mylist =Big().getlist() That's probably not what you were asking for, but it does express the results you would get out of your code, especially as you are not passing in any significant parameters to the 'inside' function. OK, perhaps a bit more useful. #no inheritance - could also be class Big(object) where object is the python "root class" class Big: #initialize the class level to be empty myclasslist = [] def __init__(self): #initialize the instance level variable to be empty self.myinstancelist = [] def appendAndGet(self,x,y): #modify the instance's "personal" list self.myinstancelist.append(x) self.myinstancelist.append(y) #will now modify shared class-level variable. Big.myclasslist.append(x) Big.myclasslist.append(y) return self.myinstancelist print "Big.myclasslist without any instances around:", Big.myclasslist bigA = Big() result = bigA.appendAndGet(348,32) print "result #1:", result print "Big.myclasslist:", Big.myclasslist bigB = Big() result = bigB.appendAndGet(11,22) print "result #2:", result #and the instance also still has its myinstancelist around print "same as result #2:", bigB.myinstancelist print "Big.myclasslist:", Big.myclasslist console output: D:\user\workspace\vg\tmptesting>testc.py my class level mylist variable: [348, 32] Big.myclasslist without any instances around: [] result #1: [348, 32] Big.myclasslist: [348, 32] result #2: [11, 22] same as result #2: [11, 22] Big.myclasslist: [348, 32, 11, 22] Try perhaps Dive Into Python's class intro: www.diveintopython.org/object_oriented_framework/defining_classes.html Cheers From wildemar at freakmail.de Fri Aug 24 16:45:58 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 24 Aug 2007 22:45:58 +0200 Subject: Co-developers wanted: document markup language In-Reply-To: References: <87odgyyx9u.fsf@wilson.homeunix.com> <87tzqpew22.fsf@wilson.homeunix.com> <87tzqp77my.fsf@wilson.homeunix.com> <7xy7g1if24.fsf@ruckus.brouhaha.com> <87mywh717i.fsf@wilson.homeunix.com> <46CEAF71.3050900@freakmail.de> Message-ID: <46CF4386.9020801@freakmail.de> Robert Kern wrote: > Wildemar Wildenburger wrote: > >> Torsten Bronger wrote: >> >>> Hall?chen! >>> >>> >> Yes, you're German. Have you ever noticed that (we) Germans are >> virtually the only ones that feel the need to rub our nationality into >> everyones faces? ;) >> > > Howdy! > > We Americans do the same. ;-) > > Weeell, you guys mostly rub your ignorance about the rest of the world into everyones faces. That's a little different. There, I did it. Now I got my country invaded. But maybe that's a good thing ... at least we will get democracy and finally find happiness. /W (OK, sorry. I couldn't resist. Don't take it personally. Take it nationally. ;) ) From pyth0nc0d3r at gmail.com Fri Aug 24 13:01:25 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Fri, 24 Aug 2007 12:01:25 -0500 Subject: Fwd: How would I compile a Python file to a exe In-Reply-To: <1187974585.362430.272470@m37g2000prh.googlegroups.com> References: <1187974585.362430.272470@m37g2000prh.googlegroups.com> Message-ID: I thought I answered this lol.. ---------- Forwarded message ---------- From: vasudevram Date: Aug 24, 2007 11:56 AM Subject: Re: How would I compile a Python file to a exe To: python-list at python.org On Aug 24, 2:11 am, Charlie wrote: > Quoting Lamonte Harris : > > > Been a while and I'm wondering how I would go about doing it. > > py2exe seems to be a fairly good option for this, at least in the > world of Windows. Yes, py2exe looks good. I've tried it out. Make sure to test for the cases you'll need, though. - Vasudev ----------------------------------------- Vasudev Ram http://www.dancingbison.com http://jugad.livejournal.com http://sourceforge.net/projects/xtopdf ----------------------------------------- -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Mon Aug 27 00:12:27 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 27 Aug 2007 01:12:27 -0300 Subject: how to remove number References: <763139.69891.qm@web63115.mail.re1.yahoo.com> Message-ID: En Tue, 21 Aug 2007 06:18:26 -0300, susanti marsol escribi?: > how to remove all number in our's document? Can you be more specific? -- Gabriel Genellina From dejanews at email.com Sun Aug 19 08:03:39 2007 From: dejanews at email.com (samwyse) Date: Sun, 19 Aug 2007 12:03:39 GMT Subject: clarification In-Reply-To: <1i31aop.2ing3h1hcfz0dN%aleax@mac.com> References: <13cb7frnqs8f6d9@corp.supernews.com> <1i31aop.2ing3h1hcfz0dN%aleax@mac.com> Message-ID: Alex Martelli wrote: > Of course, hoisting the unbound method out of the loops can afford the > usual small optimization. But my point is that, in Python, these > operations (like, say, the concatenation of a sequence of lists, etc) > are best performed "in place" via loops calling mutator methods such as > update and intersection_update (or a list's extend, etc), rather than > "functionally" (building and tossing away many intermediate results). > E.g., consider: > > brain:~ alex$ python -mtimeit -s'sos=[set(range(x,x+4)) for x in > range(0, 100, 3)]' 'r=set()' 'for x in sos: r.update(x)' > 100000 loops, best of 3: 18.8 usec per loop > > brain:~ alex$ python -mtimeit -s'sos=[set(range(x,x+4)) for x in > range(0, 100, 3)]' 'r=reduce(set.union, sos, set())' > 10000 loops, best of 3: 87.2 usec per loop > > Even in a case as tiny as this one, "reduce" is taking over 4 times > longer than the loop with the in-place mutator -- and it only gets > worse, as we're talking about O(N squared) vs O(N) performance! Indeed, > this is part of what makes reduce an "attractive nuisance"...;-). [[And > so is sum, if used OTHERWISE than for the documented purpose, computing > "the sum of a sequence of numbers": a loop with r.extend is similarly > faster, to concatenate a sequence of lists, when compared to sum(sol, > [])...!!!]] Curiously, when I attempt the actual problem at hand (set intersection) rather than something altogether different (set union) on my Dell laptop running Win2K Pro, I get the following results: stmt = 'r=reduce(set.intersection, los)' best of 3: 21.9 usec per loop stmt = 'r=intersect_all(los)' best of 3: 29.3 usec per loop So, the "nuisance" is more attractive than you thought. Apparently, one can't really depend on "in place" mutator methods being more efficient that using functional techniques. BTW, the above figures reflect 10,000 iterations; using larger counts makes the difference even larger. I suspect that this is because the Python interpreter has fewer chances to be interrupted by external processes when it's using 'reduce'. This in turn indicates that both implementations actually work about same and your "O(n squared)" argument is irrelevant. P.S. Here's the source I used for the timings: from timeit import Timer setup = """ def intersect_all(los): it = iter(los) result = set(it.next()) for s in it: result.intersection_update(s) return result not7=range(2,11) not7.remove(7) los=[set(range(0,360,step)) for step in not7] """ number = 10000 repeat = 3 precision = 3 for stmt in 'r=reduce(set.intersection, los)', 'r=intersect_all(los)': t = Timer(stmt, setup) r = t.repeat(repeat, number) best = min(r) usec = best * 1e6 / number print "stmt =", repr(stmt) print "best of %d: %.*g usec per loop" % (repeat, precision, usec) From rvtol+news at isolution.nl Sat Aug 11 11:37:36 2007 From: rvtol+news at isolution.nl (Dr.Ruud) Date: Sat, 11 Aug 2007 17:37:36 +0200 Subject: I am giving up perl because of assholes on clpm -- switching to Python References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> <1185467914.814174.94600@22g2000hsm.googlegroups.com> Message-ID: Paul Boddie schreef: > let us > avoid comp.lang.python becoming some kind of linux-kernel ego trip > where anyone who has stuck around has an interest in perpetuating a > hostile atmosphere. "When did you stop beating your wife?" -- Affijn, Ruud "Gewoon is een tijger." From fabioztessitore at libero.it Sat Aug 4 13:51:21 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 04 Aug 2007 17:51:21 GMT Subject: regexp problem in Python References: <1186177312.117581.129910@d55g2000hsg.googlegroups.com> Message-ID: <46b4bc99$0$36444$4fafbaef@reader5.news.tin.it> Il Fri, 03 Aug 2007 14:41:52 -0700, Ehsan ha scritto: maybe you can use this to solve your prob: myurl = "http://www.2shared.com/download/1716611/e2000f22/ Jadeed_Mlak14.wmv?tsid=20070803-164051-9d637d11" if myurl.startswith('http') and ('wmv' in myurl or '3pg' in myurl): # myurl is the complete address you want print myurl ##################################### about re, I'm waiting for someone enlightening all us, bye Fabio From jcd at sdf.lonestar.org Fri Aug 24 13:24:07 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 24 Aug 2007 13:24:07 -0400 Subject: Using Regular Expresions to change .htm to .php in files In-Reply-To: <9afea2ac0708231305v539390dew84926f0b0dcd6974@mail.gmail.com> References: <9afea2ac0708231305v539390dew84926f0b0dcd6974@mail.gmail.com> Message-ID: <46CF1437.9020200@sdf.lonestar.org> Tim Williams wrote: > On 23/08/07, sebzzz at gmail.com wrote: > >> Hi, >> >> I have a bunch of files that have changed from standard htm files to >> php files but all the links inside the site are now broken because >> they point to the .htm files while they are now .php files. >> >> Does anyone have an idea about how to do a simple script that changes >> each .htm in a given file to a .php >> >> Thanks a lot in advance >> >> > > Something like: > > Infile = open(f_name,'r+') > Data = Infile.read() > InFile.write(Data.replace('.htm','.php')) > Infile.close() > > :) > Yeah, but you'd better make darn sure that *all* links point to .htm files (including external links), because you could very easily end up pointing to http://some.othersite.com/index.phpl And that's just no good. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Thu Aug 23 23:48:42 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 23 Aug 2007 23:48:42 -0400 Subject: Xah's Edu Corner: Under the spell of Leibniz's dream In-Reply-To: <1187908258.609624.321990@m37g2000prh.googlegroups.com> References: <1187567809.896668.228650@z24g2000prh.googlegroups.com> <1187598193.118227.270460@19g2000hsx.googlegroups.com> <46ca1e65$1_3@news.chariot.net.au> <5j4rrfF3s3h2rU1@mid.dfncis.de> <1187908258.609624.321990@m37g2000prh.googlegroups.com> Message-ID: Twisted wrote: > On Aug 23, 3:38 am, Matthias Buelow wrote: >> In comp.lang.lisp Bikal KC wrote: >> >>> I used usenet years ago then stopped for couple of years. I remember >>> seeing him/her on c.l.perl I believe doing the same thing he/she is >>> doing atm. I'd say the ultimate usenet superstar. Wow! >> I think it's some (probably mild) form of autism. >> No offense intended, Xah. > > Yeah, yeah, that's what they all say, especially when they do that > most-common of usenet things -- insult your mental health and tone it > as if it were a very compassionate and understanding suggestion to > seek medical treatment rather than the flame that it is. :P > It's already well-established that there's no point flaming Xah Lee, as he's pretty much an output-only source. See any responses from him on this thread? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From mclaugb at nospm.yahoo.com Tue Aug 7 10:48:35 2007 From: mclaugb at nospm.yahoo.com (mclaugb) Date: Tue, 7 Aug 2007 15:48:35 +0100 Subject: python system subprocess win32 Message-ID: Hello ALl, I have a compiled program "conv.exe" that works as follows: >>conv.exe ----------------------------- Please selection from the following options. press "h" for help, "p" for print, "r" for readfile. Enter your request now: ... -------------------- Is there a way to script python using the subprocess method to start this program "conv.exe" and then send a "r" to the command line to make it, say, readfile. I have tried the following but the .communicate("r) is not doing anything import subprocess import time a=subprocess.Popen("c:\\mcml\\conv.exe") time.sleep(1) (stdout, stderr) = a.communicate("r") Many thanks, Bryan From bill.scherer at verizonwireless.com Wed Aug 8 09:53:17 2007 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Wed, 08 Aug 2007 09:53:17 -0400 Subject: This bit of code hangs Python Indefinitely In-Reply-To: References: Message-ID: <46B9CACD.7030308@verizonwireless.com> brad wrote: > url_queue = Queue.Queue(256) > for subnet in subnets: > url_queue.put(subnet) > > The problem is that I have 512 things to add to the queue, but my limit > is half that... whoops. Shouldn't the interpreter tell me that I'm an > idiot for trying to do this instead of just hanging? A message such as > this would be more appropriate: > > "Hey fool, you told me to only accept 256 things and you're trying to > give me 512... what's up with that?" > If you used put_nowait(subnet), or put(subnet, False), then you would get an error. By default, put() will block when the specified limit is reached. When the queue is no longer full, the put will proceed. See the Queue module docs for complete info. HTH, Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Aug 16 05:23:22 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 16 Aug 2007 11:23:22 +0200 Subject: Changing button preferences after beeing pressed References: <1187252874.903820.79280@a39g2000hsc.googlegroups.com> Message-ID: <5iijcaF3or1vmU1@mid.individual.net> thomas.lidebrandt at gmail.com wrote: > I'm using wxPython to consruct a GUI and want to change a button > label => wx.Button.SetLabel (also have a look at the button examples) > and event handler to change after the button have been > pressed. I'm not sure if those bindings can easily be changed at runtime. Another solution is creating two buttons and only show one at a time. > The only thing I can think of is a global variable that > contrls the state of the program and constructs the button in > accordance to the defined state. Better keep the state as frame attribute and use a frame method to change it. Regards, Bj?rn -- BOFH excuse #61: not approved by the FCC From zentraders at gmail.com Mon Aug 13 22:27:15 2007 From: zentraders at gmail.com (Zentrader) Date: Mon, 13 Aug 2007 19:27:15 -0700 Subject: output object fields into a file In-Reply-To: <1187054257.243592.35360@o61g2000hsh.googlegroups.com> References: <1187054257.243592.35360@o61g2000hsh.googlegroups.com> Message-ID: <1187058435.276794.44700@i13g2000prf.googlegroups.com> On Aug 13, 6:17 pm, Alex wrote: > Hello, I am rather new to python. Maybe my thinking is in the > paradigm of C++, that makes me hard to make sense of some python > scripts (interacting with C# code) written by my colleague. I am > thinking of outputting all objects and their fields of each script > into a file. The tricky part is I am NOT quite sure of the type of > the fields. How can I output these objects and their fields into an > external file. Any code sample would be highly appreciated !!! > > Alex For now, assume that everything must be written as a string. You can use write or writelines depending on the type. http://www.penzilla.net/tutorials/python/fileio/ http://docs.python.org/lib/bltin-file-objects.html From arkanes at gmail.com Tue Aug 21 09:24:45 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 21 Aug 2007 08:24:45 -0500 Subject: C# and Python In-Reply-To: <1187699710.839869.32810@57g2000hsv.googlegroups.com> References: <1187690505.903506.79690@d55g2000hsg.googlegroups.com> <1187699710.839869.32810@57g2000hsv.googlegroups.com> Message-ID: <4866bea60708210624l610bd441l45f66eacb9d304ac@mail.gmail.com> On 8/21/07, Ant wrote: > On Aug 21, 11:01 am, subeen wrote: > > Hi, > ... > > But I want to write the GUI and number generation program in C#.net. > > When the user clicks Quick Sort button, the quicksort.py will be > > called and it will sort the numbers. > > Probably worth looking at IronPython, the Python implementation for > the .Net platform. > > -- Also Pythonnet (see the recent announce on this ML), which is a .NET/CPython bridge and supports embedding CPython as well as calling .NET code from CPython. From jstroud at mbi.ucla.edu Mon Aug 20 20:46:37 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 20 Aug 2007 17:46:37 -0700 Subject: Newbee Question In-Reply-To: <1187650036.450645.185500@a39g2000hsc.googlegroups.com> References: <1187621470.484615.7010@i13g2000prf.googlegroups.com> <1187622390.854759.162320@q3g2000prf.googlegroups.com> <1187650036.450645.185500@a39g2000hsc.googlegroups.com> Message-ID: hd1956 at yahoo.com wrote: > On Aug 20, 11:06 am, kyoso... at gmail.com wrote: > >>On Aug 20, 9:58 am, "Shawn Milochik" wrote: >> >> >> >> >> >> >>>On 8/20/07, kyoso... at gmail.com wrote: >> >>>>On Aug 20, 9:23 am, "HD1956" wrote: >>>> >>>>>This is probably a simple code. I am a truck driver who gets paid by >>>>>stops and cases. I am trying to figure out how to code my stop pay. I >>>>>get 40 cents per stop up to 22 stops, and $1.40 per stops after that. >> >>>>def calc(num): >>>> if num < 23: >>>> return 0.4 * num >>>> else: >>>> overtime = num - 22 >>>> x = 0.4 * 22 >>>> x += overtime * 1.4 >>>> return x >> >>>># Use your own brain next time >> >>>>Mike >> >>>>-- >>>>http://mail.python.org/mailman/listinfo/python-list >> >>>Mike, >> >>>I wonder if we were both just duped into helping someone with their homework... >> >>>Shawn >> >>I like to write code, so it's not a big deal when it's something so >>simple. Still, that is beyond dumb! Nice code, by the way. >> >>Mike- Hide quoted text - >> >>- Show quoted text - > > > Thanks for the help. By the way I am trying to learn the python after > work and on weekends. If it was a dumb question, to this group, I will > not bother you all again. > Without help it will take me longer to learn. Thanks > Throw out an example of what you tried with an error message and/or unexpected results. Ask particulars--this will keep you from giving truck drivers a bad name. Sticking-my-fist-out-window-and-making-pulling-down-gesture-ly yours, James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Aug 15 05:11:59 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 15 Aug 2007 11:11:59 +0200 Subject: What does r"""any text""" mean ? References: Message-ID: <5ifuasF3foe9rU1@mid.individual.net> Alexander Eisenhuth wrote: > ... as you can find in os.py at line 1 ? Please don't split your request between subject and body. String literals enclosed in triple quotes are multiline strings. String literals prefixed by "r" are raw strings. http://docs.python.org/ref/strings.html Regards, Bj?rn -- BOFH excuse #71: The file system is full of it From jjl at pobox.com Sun Aug 5 19:09:13 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 05 Aug 2007 23:09:13 GMT Subject: Misleading wikipedia article on Python 3? References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> Message-ID: <87y7gpr33a.fsf@pobox.com> "Martin v. L?wis" writes: [... snip stuff I don't follow ...] > However, it *is* a design goal to make 2.6 so that transition to > 3k becomes simpler. That's not a 3k feature, but a 2.6 one. Not sure I care about this sort of thing for the purpses of my question. I just wanted to know: is it easy to make my code so it runs on 2.6 and 3.0, without funny stuff like a code translator? Seems wikipedia said "yes" and Guido said "no". [...] > to be seen. I personally believe that many projects won't need the 2to3 > tool, if they are willing to compromise on the notations used in the > source code. OK, so there's disagreement on this point amongst the Python 3 developers. That's interesting (I don't mean that in a negative way). [...] >> It >> seems to me that if I don't understand what the Python 3 developers >> expect the practicalities to be, most other interested people won't >> either ("interested" in the opposite sense to "disinterested" rather >> than to "uninterested"). > > I think comp.lang.python is then the wrong place to find out; the py3k > list likely reaches more of these developers. OTOH, I don't know whether > they all want to participate in a survey of their expectations... I was also hoping to get a quick answer rather than a long discussion, if any Python 3 developers were around to talk to the broader range of people that read this list. You have given your answers, I wonder if anybody else will turn up. > Rather than studying people's opinions, why don't you try to port your > own projects to 3k, and report whether you found it practical to use > a single source (assuming you would prefer such a solution for your > own project)? Because that might well tell me much less than asking a Python 3 developer, and yet take far more time, and fail to inform everybody else. John From Frank.Aune at broadpark.no Thu Aug 23 09:58:50 2007 From: Frank.Aune at broadpark.no (Frank Aune) Date: Thu, 23 Aug 2007 15:58:50 +0200 Subject: Python submodules and name imports Message-ID: <200708231558.50501.Frank.Aune@broadpark.no> Hi, First take a look at: http://www.network-theory.co.uk/docs/pytut/Packages.html as I will use this module file layout as an example. If I want to do the following: from Sound import Effects ... Effects.echo.echofilte(bla bla) What will Sound/Effects/__init__.py need to contain then? I tried to define the __all__ = ['echo','surround','reverse'] parameter in the init file, but this only seems to be effective for " .. import *" statements. Is the correct way of accomplishing this to explicitly import the submodules in sound/Effects/__init__.py? I'm looking for the "official" way of doing this. Thank you, Frank Aune From half.italian at gmail.com Wed Aug 15 23:08:30 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Wed, 15 Aug 2007 20:08:30 -0700 Subject: moving files in a seperate thread (and/or with progress?) In-Reply-To: References: Message-ID: <1187233710.262456.67700@q3g2000prf.googlegroups.com> On Aug 15, 2:28 am, "Jorgen Bodde" wrote: > Hi all, > > I want to make a small batch copy tool that scans for certain files, > and copies them to a specified directory. Since the files are huge > (AVI / DIVX) typical 300 to 700 Mb, I want to provide the user with > some feedback during the file copy. > > Here is my dillemma; When I use shutil.move(..,..) I have to wait > until it's done, there is no feedback, so the GUI basically hangs. > However, shutil.move can be fast because it intelligently renames the > file when it is on the same medium, but slow when it moves to a > different one. > When I use my own implementation of a move mechanism that provides > feedback, I lose that intelligence, and I might slow down the copy > process unneccessarily. > > When I move files, feedback is handy to have, but not neccesary so I > thought I can also call shutil.move from a seperate thread so the main > GUI stays responsive. What are my options in aborting a move by > killing the thread or are there other (3rdparty) modules I might use > to get better move or copy performances? > > Just opening the file, performing a block copy myself seems like it > will slow down the transfer, but up until now I found no way to move > or copy with progress or abilities to abort the file transfer.. > > Any ideas? > > Regards, > - Jorgen The following link helped me to pull it off with Tkinter. A complicated example, but very well written. http://uucode.com/texts/pylongopgui/pyguiapp.html ~Sean From nospam at geniegate.com Thu Aug 2 09:09:26 2007 From: nospam at geniegate.com (Jamie) Date: Thu, 02 Aug 2007 13:09:26 GMT Subject: I am giving up perl because of assholes on clpm -- switching to Python References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> Message-ID: In <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d at giganews.com>, Martha_Jones at tx.net mentions: >Python is a better language, with php support, anyway, but I am fed up >with attitudes of comp.lang.perl.misc. Assholes in this newsgroup ruin >Perl experience for everyone. Instead of being helpful, snide remarks, >back-biting, scare tactings, and so on proliferate and self >reinforce. All honest people have left this sad newsgroup. Buy bye, >assholes, I am not going to miss you!!! > >Martha I've heard people tell the same story, that perl folks are... rude. Actually, I've pretty much heard (and noticed) that about linux, too. Yet, linux is still a good operating environment, so is perl. You'll find rude people everywhere you look. While it may be true that there is a higher percentage of hard-core tech folks who might lack social skills, at least they don't err.. well, maybe they do.. byte. :-) Seriously, it is one of the problems facing perl (and linux) people ARE turned away by the attitude. It is rather embarassing/unflattering when someone is critical of your work. I see a lot of ideas about things should be "made easier" but I think thats the wrong course. We really just need to be nicer to new folks. Jamie -- http://www.geniegate.com Custom web programming Perl * Java * UNIX User Management Solutions From almadhu at gmail.com Sun Aug 12 00:46:44 2007 From: almadhu at gmail.com (Madhu Alagu) Date: Sun, 12 Aug 2007 04:46:44 -0000 Subject: python + XUL Message-ID: <1186894004.913359.132000@b79g2000hse.googlegroups.com> Hi Python + XUL Success Stories Thanks Madhu Alagu From aleax at mac.com Sat Aug 11 01:36:16 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 10 Aug 2007 22:36:16 -0700 Subject: Destruction of generator objects References: <20070808002852.6228ae91@cube.tz.axivion.com> <1186618661.845525.225010@x35g2000prf.googlegroups.com> <20070809082517.6af28eaf@cube.tz.axivion.com> Message-ID: <1i2ni7t.1npenokfe2krjN%aleax@mac.com> Stefan Bellon wrote: > On Thu, 09 Aug, Graham Dumpleton wrote: > > > result = application(environ, start_response) > > try: > > for data in result: > > if data: # don't send headers until body appears > > write(data) > > if not headers_sent: > > write('') # send headers now if body was empty > > finally: > > if hasattr(result,'close'): > > result.close() > > Hm, not what I hoped for ... > > Isn't it possible to add some __del__ method to the generator object > via some decorator or somehow else in a way that works even with Python > 2.4 and can then be nicely written without cluttering up the logic > between consumer and producer? No, you cannot do what you want in Python 2.4. If you can't upgrade to 2.5 or better, whatever the reason may be, you will have to live with 2.4's limitations (there ARE reasons we keep making new releases, after all...:-). Alex From paddy3118 at googlemail.com Sun Aug 19 12:00:36 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 19 Aug 2007 16:00:36 -0000 Subject: Hot subject: a good python editor and/or IDE? In-Reply-To: References: Message-ID: <1187539236.091867.256290@w3g2000hsg.googlegroups.com> On Aug 19, 10:47 am, S?bastien wrote: > Hi folks, > > I am currently using Eclipse+PyDev when developping Python projects but > I lack a fast, simple editor for tiny bit of scripts. So here is my > question: what is, for you, the current best ( but still kind of light! > ) Python editor/IDE ? A tiny precision, I am on Ubuntu so I am looking > for a linux compatible editor. > > Cheers, > > S?bastien A hard question to answer. Why not just use the default gnome or kde editors? I've invested time in learning vim which has paid off handsomely for me. - Paddy. From steve at holdenweb.com Wed Aug 22 07:07:23 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 22 Aug 2007 07:07:23 -0400 Subject: for statement on empty iterable In-Reply-To: <1360b7230708212256l392155b9ua11d1113846b609e@mail.gmail.com> References: <1187760507.951994.50310@q4g2000prc.googlegroups.com> <7xabsk3zgm.fsf@ruckus.brouhaha.com> <1187761270.713307.224570@i38g2000prf.googlegroups.com> <1360b7230708212256l392155b9ua11d1113846b609e@mail.gmail.com> Message-ID: Amit Khemka wrote: > On 8/22/07, james_027 wrote: >> hi Paul, >> >>> That doesn't crash or anything like that, but it also doesn't >>> set the index variable, which can cause confusion in some situations. >> Thanks for your quick answer ... Actually I was thinking how do I >> access the index inside a for statement? Can you help > > Have a look at "enumerate", You can iterate over a list like: > > for i,x in enumerate(['a', 'b', 'c']): > print i, x > > It prints: > 0 a > 1 b > 2 c > Also remember that string are iterable: >>> for x in enumerate("James"): ... print x ... (0, 'J') (1, 'a') (2, 'm') (3, 'e') (4, 's') >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From cpmishra.20 at gmail.com Thu Aug 2 01:15:36 2007 From: cpmishra.20 at gmail.com (cpmishra) Date: Thu, 02 Aug 2007 05:15:36 -0000 Subject: DBUtil with modepython Message-ID: <1186031736.489064.287430@22g2000hsm.googlegroups.com> Hi all I have used DBUtil in mysql databse. when we run to program in dos command ,successfully run but when we run in apache server (locally)with modepython then given error.Pls give me suggation error: No module named DBUtils.PooledDB cp mishra From omelnyk at gmail.com Tue Aug 21 06:50:58 2007 From: omelnyk at gmail.com (Olexandr Melnyk) Date: Tue, 21 Aug 2007 13:50:58 +0300 Subject: C# and Python In-Reply-To: <1187690505.903506.79690@d55g2000hsg.googlegroups.com> References: <1187690505.903506.79690@d55g2000hsg.googlegroups.com> Message-ID: Aside from method mentioned by Tom, you can invoke your script through command line: C:\Python24\bin\python.exe file-to-sort.txt result-file.txt 2007/8/21, subeen : > > Hi, > I am a newcomer in Python. I am going to write a small Python > application that will run in windows xp. This application needs to > have GUI. Is it possible to make a C# application using visual studio > 2005 that will call the python scripts? Let me explain more here: > My program will generate a text file of 100 - 100000 random integers, > and sort those using various sorting methods. Now I have written > separate sorting scripts in Python (quick sort, insertion sort etc.). > But I want to write the GUI and number generation program in C#.net. > When the user clicks Quick Sort button, the quicksort.py will be > called and it will sort the numbers. > > regards, > Subeen > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Sincerely yours, Olexandr Melnyk http://omelnyk.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From antroy at gmail.com Mon Aug 20 03:45:25 2007 From: antroy at gmail.com (Ant) Date: Mon, 20 Aug 2007 00:45:25 -0700 Subject: Python question (PyNoob) In-Reply-To: <3uOdnbA4Bc27fFXbnZ2dnUVZ8vidnZ2d@bt.com> References: <3uOdnbA4Bc27fFXbnZ2dnUVZ8vidnZ2d@bt.com> Message-ID: <1187595925.174671.286360@57g2000hsv.googlegroups.com> On Aug 20, 1:33 am, Anonymous wrote: ... > 1). Data Munging (text processing) - instead of Perl Check out the re module (regexes) in the standard library, and the pyparsing third party library: http://pyparsing.wikispaces.com/ for more complex stuff. > 2). Automating my build process You'll want to look into the os, sys and subprocess modules. The PMOTW this week was subprocess: http://www.oreillynet.com/onlamp/blog/2007/08/pymotw_subprocess_1.html. A few weeks back it covered os: http://blog.doughellmann.com/2007/05/pymotw-os.html. In fact one of Doug Hellmann's previous articles on the getopt module may also be useful if you want your build scripts to be controlled by command line args: http://blog.doughellmann.com/2007/08/pymotw-getopt.html (Though I prefer optparse personally). > 3). (Possibly) some web data retrieval jobs urllib, urllib2 and cookielib in the standard library should do most of what you want, perhaps with the addition of beautiful soup if you need to scrape the pages for data: http://www.crummy.com/software/BeautifulSoup/ HTH. -- Ant... http://antroy.blogspot.com/ From deets at nospam.web.de Thu Aug 2 15:18:21 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 02 Aug 2007 21:18:21 +0200 Subject: XML Processing In-Reply-To: <1186080339.344993.167670@z24g2000prh.googlegroups.com> References: <1186080339.344993.167670@z24g2000prh.googlegroups.com> Message-ID: <5hep07F3jael1U2@mid.uni-berlin.de> Roman schrieb: > Is there a package that converts a string that contains special > characters in xml to to literal value. For instance, converts string > http://myhome/¶m to http://myhome/&param. import xml.sax.saxutils print xml.sax.saxutils.escape("I'm a happy & friendly guy, and 1 < 3 - never forget that!") Diez From bdesth.quelquechose at free.quelquepart.fr Mon Aug 20 13:59:15 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 20 Aug 2007 19:59:15 +0200 Subject: Where we need to use Python ? In-Reply-To: References: <1187596936.136499.200280@l22g2000prc.googlegroups.com> <46cc26ed$0$432$426a74cc@news.free.fr> Message-ID: <46ccab4c$0$410$426a74cc@news.free.fr> Terry Reedy a ?crit : > |"Bruno Desthuilliers" Terry Reedy a ?crit : > | > |> The CPython implementation of the langauge compiles Python to > proprietary > |> byte code > > |Hahem... "proprietary" is certainly not the right term here. > > a. you are being nitpicky, Possibly. > overly in my opinion Possibly too. > b. you failed to suggest a better term, True. What about "specific", then ? > hence cannot expect the same of me This is debatable, but I don't feel like debating on this. > In any case, CPython is owned by PSF (which gives it away). Its bytecode > is an private implementation detail subject to change in any .x version as > the developers see fit. Which AFAICT doesn't make it "proprietary", for the common definition of "proprietary" wrt/ softwares. Python is free software, which means that anyone can freely write either it's own Python compiler (which is basically what Jython and IronPython are) or write a compiler for any language to CPython's VM. Sorry for being so nitpicky. From ptmcg at austin.rr.com Mon Aug 20 11:30:05 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 20 Aug 2007 08:30:05 -0700 Subject: Newbee Question In-Reply-To: References: Message-ID: <1187623805.425320.93320@a39g2000hsc.googlegroups.com> On Aug 20, 9:23 am, "HD1956" wrote: > This is probably a simple code. I am a truck driver who gets paid by > stops and cases. I am trying to figure out how to code my stop pay. I > get 40 cents per stop up to 22 stops, and $1.40 per stops after that. You'll get top marks for turning in the shortest program! norm = 0.4 ot = 1.4-norm otStart = 22 calcPay = lambda stops : norm*stops+ot*max(stops-otStart,0) -- Paul From sturlamolden at yahoo.no Fri Aug 31 11:44:04 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 31 Aug 2007 08:44:04 -0700 Subject: strings (dollar.cents) into floats In-Reply-To: <46d75cf3$0$7698$9b4e6d93@newsspool2.arcor-online.net> References: <877incd20i.fsf@benfinney.id.au> <46d75cf3$0$7698$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <1188575044.874256.42960@50g2000hsm.googlegroups.com> On 31 Aug, 02:12, Wildemar Wildenburger wrote: > I've heard (ok, read) that several times now and I understand the > argument. But what use is there for floats, then? When is it OK to use them? There are fractions that can be exactly represented by floats that cannot be exactly represented by decimals. There are fractions that can be exactly represented by decimals that cannot be exactly represented by floats. Which one is better? Which do we prefer? What a float cannot do is to represent a decimal fractional number (e.g. 1.1) exactly. If we need that, we cannot use floats. A notable example is monetary computations, it covers 99% of the use for decimal numbers in computers. For this reason, we should never use floats to add 10 cents to a dollar. The use of decimals for monetary calculations is mandatory. Floats are written as decimal fractional numbers in program code, and they are printed as decimal fractional numbers on the screen. A novice programmer may for this reason easily mistake floats for being decimals. But inside the computer floats are something very different. Floats do not represent decimal fractional numbers. Floats represent binary fractional numbers. Decimal numbers are base-10, binary numbers are base-2. Floats and decimals are similar but different. It is much easier to manipulate for computers than decimals. Digital electronics by convention only has two states, TTL voltage levels 0.0 V and 5.0 V, which are taken to mean 0 and 1 in binary (or false and true in boolean) respectively. Computers work internally with binary numbers. Floats are preferred to decimals in e.g. numerical maths and other scientific computing for their better performance speed wise. Knowledge of the behaviour of floats, e.g. how they cause rounding and truncation errors, is pivotal in that field of computer science. For most purposes, we could replace floats with decimals. But then we would suffer a major speed penalty. Decimals are only "precise" if the input values can be represented precisely by decimal fractions. If we typed 1.1 and took that to mean "one dollar and 10 cents", then certainly "exactly 1.1" was what we meant. But if we ment "1.1 centigrades read from a mercury thermometer", we would actually (by convention) mean "something between 1.05 and 1.14 centigrades". Decimals also fail to be exact if we try to compute things like "1.0/3.0". 1/3 does not have an exact representation in decimal, and we get an approximation from the computer. For purposes where exact precision is not needed, decimals are neither better nor worse than floats. This accounts for 99% of the cases where fractional numbers are used on a computer. More about floating point numbers here: http://www.math.byu.edu/~schow/work/IEEEFloatingPoint.htm Sturla Molden From hvb at efrontier.com Fri Aug 3 20:20:43 2007 From: hvb at efrontier.com (harold barker) Date: Fri, 3 Aug 2007 17:20:43 -0700 Subject: Sorting Unix mailboxes Message-ID: Was your mailbox module competed? If so where can i find it? From millerdev at gmail.com Tue Aug 21 20:49:51 2007 From: millerdev at gmail.com (Daniel) Date: Tue, 21 Aug 2007 17:49:51 -0700 Subject: defaultdict of arbitrary depth In-Reply-To: <1187321113.841198.195100@22g2000hsm.googlegroups.com> References: <1187321113.841198.195100@22g2000hsm.googlegroups.com> Message-ID: <1187743791.286531.155970@m37g2000prh.googlegroups.com> Any reason why this wouldn't work? >>> from collections import defaultdict >>> def rdict(*args, **kw): ... return defaultdict(rdict, *args, **kw) ... >>> d = rdict() >>> d[1][2][3][4][5] # ... defaultdict(, {}) ~ Daniel From aahz at pythoncraft.com Wed Aug 29 10:11:00 2007 From: aahz at pythoncraft.com (Aahz) Date: 29 Aug 2007 07:11:00 -0700 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> Message-ID: In article <1188349440.309634.182800 at z24g2000prh.googlegroups.com>, Russ wrote: > >I just stumbled onto PEP 316: Programming by Contract for Python >(http://www.python.org/dev/peps/pep-0316/). This would be a great >addition to Python, but I see that it was submitted way back in 2003, >and its status is "deferred." I did a quick search on comp.lang.python, >but I don't seem to see much on it. Does anyone know what the real >status is of getting this into standard Python? Thanks. The way to get this into Python is to get people to use it as a stand-alone module. It's already in PyPI, so now it's time for some marketing. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From vedrandekovic at v-programs.com Sat Aug 11 15:50:38 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Sat, 11 Aug 2007 12:50:38 -0700 Subject: python 2.5 bug In-Reply-To: References: <1186825286.493878.80380@l70g2000hse.googlegroups.com> <5i5fktF3ml00gU1@mid.uni-berlin.de> <1186826980.346619.287670@r34g2000hsd.googlegroups.com> <46bdfb3f$0$5102$ba4acef3@news.orange.fr> Message-ID: <1186861838.057027.179250@l70g2000hse.googlegroups.com> On 11 kol, 20:58, Thorsten Kampe wrote: > * Laurent Pointal (Sat, 11 Aug 2007 20:09:03 +0200) > > > vedrandeko... at v-programs.com wrote: > > > On 11 kol, 11:59, Marc 'BlackJack' Rintsch wrote: > > >> On Sat, 11 Aug 2007 02:41:26 -0700, vedrandekovic wrote: > > >> > I was install Python 2.5 and uninstall Python 2.4 now I cannot run my > > >> > scripts, only from idle > > > IMHO Python 2.4 was registered for .py files, Python 2.5 take precedence > > when installed, but when Python 2.4 has been removed, it remove .py files > > association too (so break Python 2.5 association). > > > * manually associate .py/.pyc/.pyo files to python.exe, .pyw files to > > pythonw.exe. > > > * or reinstall Python 2.5 so that it re-setup ad-hoc associations. > > Yeah. Did the Original Poster mention any details about his problem. > Like - for instance - that he's using Windows? > > Thorsten Hello, Now I was restart my windows and python 2.5 also.Now everything works fine except python and py2exe script install ( of course something must destroy my day ) now when I run: $ cd c:\Python25\Lib\site-packages\ $ python mysetup.py py2exe 'python' is not recognized as an internal or external command, operable program or batch file. why? Regards, Vedran From soundplay at gmail.com Mon Aug 27 12:46:12 2007 From: soundplay at gmail.com (SHY) Date: Mon, 27 Aug 2007 18:46:12 +0200 Subject: passing arguments with ampersands In-Reply-To: References: <20070818112913.GA3632@gmail.com> Message-ID: that was the problem. when i manually reassociated the extension, i somehow didnt quote the argument for the filename. my bad. thanks for the various explanations and options for this :) cheers. 2007/8/20, Gabriel Genellina : > > En Sat, 18 Aug 2007 09:24:35 -0300, SHY escribi?: > > > theres no special portion of code, just the one that handles filenames > > with > > spaces. > > the problem is that when i associate a file extension to my application > > and > > i open it, the filename is not quoted before passed as an arguement. i > > dont > > know if its the problem of windows or something, or it was just my fault > > when i incorrectly associated the extension. > > How did you associate it? > Usually the registry entries are: > > HKCR\.ext = filetype > HKCR\filetype = File Description > HKCR\filetype\shell\open\command = "path\to\your\program" "%1" > > (Note the double quotes around %1) > > Get it right at the registry, and forget all that trickery joining > sys.argv parts > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From oliver.andrich at gmail.com Mon Aug 20 07:30:50 2007 From: oliver.andrich at gmail.com (oliver.andrich at gmail.com) Date: Mon, 20 Aug 2007 11:30:50 -0000 Subject: ctypes and unsigned char* In-Reply-To: <1187548845.674582.69630@w3g2000hsg.googlegroups.com> References: <1187545486.797017.308720@a39g2000hsc.googlegroups.com> <1187548845.674582.69630@w3g2000hsg.googlegroups.com> Message-ID: <1187609450.542644.50430@w3g2000hsg.googlegroups.com> On 19 Aug., 20:40, Gabriel Genellina wrote: > In the first case, use a plain c_char_p - the individual "chars" are > already unsigned in Python (that is, ord(xxx[i]) is always positive) > In the second case, first define the pointer type: > > c_ubyte_p = POINTER(c_ubyte) > your_function.restype = c_ubyte_p I will have to look into that. My function I want to wrap has the following signature unsigned char *MagickGetImageProfile(MagickWand *wand,const char *name, size_t *length) Well, the first argument and the second are straight forward, and work as expected. The last argument also works and it should take up the length of the string (unsigned char *). If I now do dll.MagickGetImageProfile.restype = c_char_p result = dll.MagickGetImageProfile(wand, "8bim", byref(length)) result is either an empty string or a 3 bytes long string, while length containes the correct length of 1086 bytes for example. I also tried dll.MagickGetImageProfile.restype = POINTER(c_ubyte) with the same result. But maybe I should do some further debugging.... Best regards, Oliver From http Mon Aug 6 07:34:35 2007 From: http (Paul Rubin) Date: 06 Aug 2007 04:34:35 -0700 Subject: Best programs written completly in Python References: Message-ID: <7xhcncc2wk.fsf@ruckus.brouhaha.com> Franz Steinh?usler writes: > b) Utilities/System I'm not sure if anyone has mentioned mercurial in this thread. It's a distributed source control system, sort of the next generation after systems like CVS/SVN. See www.selenic.com/mercurial > d) Web/Newsreader/Mail/Browser Mailman (mailing list manager)? I tend to use emacs for all the client side stuff. From sentientholon at gmail.com Wed Aug 22 14:27:07 2007 From: sentientholon at gmail.com (Frederick Polgardy) Date: Wed, 22 Aug 2007 18:27:07 -0000 Subject: How do I express a backslash in a string? In-Reply-To: <46cc723c$0$16263$88260bb3@free.teranews.com> References: <46cc723c$0$16263$88260bb3@free.teranews.com> Message-ID: <1187807227.530763.32790@i38g2000prf.googlegroups.com> On Aug 22, 1:19 pm, Tobiah wrote: > >>> "'" > "'" > >>> "\'" > "'" > >>> "\\'" > "\\'" > >>> "\\\'" > "\\'" > > This is quite different than any other language > that I am used to. Normally, a double backslash > takes away the special meaning of the last backslash, > and so you are left with a single backslash. > > How do I express the single backslash? > > Thanks, > > Tobiah It IS a single backslash - the interpreter in interactive mode displays the string literal (escaped) version of what you entered, which is, well, what you entered. If you print it instead, you'll see the actual string value. >>> '\\' '\\' >>> print '\\' \ Fred From edgrsprj at ix.netcom.com Thu Aug 30 09:12:17 2007 From: edgrsprj at ix.netcom.com (E.D.G.) Date: Thu, 30 Aug 2007 07:12:17 -0600 Subject: Important Research Project Message-ID: <13ddcvm1bsu3s94@corp.supernews.com> Important Research Project (Related to computer programming) Posted by E.D.G. on August 30, 2007 edgrsprj at ix.netcom.com This report is being posted to a number of Internet Newsgroups to see if there are any experienced computer programmers who would like to provide some assistance with an effort to develop a Perl language computer program. Interested parties can try contacting me by e-mail or by posting a response note to the comp.lang.perl.misc newsgroup. They would need to download a recent (free) MSI copy of Perl from the ActiveState Web site and get it running on a Windows XP or Vista system. http://www.activestate.com I am presently using Perl 5.8.8 but plan to upgrade to the latest version as soon as possible. People can use Windows 98 if that is the only operating system available. Perl also runs on other operating systems. But at this time I specifically need help with the Windows version. The goal is to have a single Perl program (or modules) perform functions that have been done by a sizeable collection of other language programs in the past. Help is presently needed with learning how to get Perl to generate charts and also produce standalone .exe copies of itself. The plan is to then make those .exe copies available to other scientific researchers around the world for free use along with free use updates when they become available. If other researchers wish to get Perl running on their own computers then they will probably also be given the source code for the original program for free use so that they can do their own development work. Perl was originally chosen because it is quite versatile, is a free download, and is supported both by ActiveState and quite a few independent programmers. So other researchers could get their own versions running without having to worry about viruses or cost. So far the work is fairly advanced. The effort has been underway for at least a decade. The core data generation program was formally copyrighted several years ago. My present version of Perl will send data to Windows as if it were being manually typed into the keyboard (important for controlling other programs). And it can directed to respond to most keystrokes even when another program is the active one. Unfortunately, Windows also presently responds to those keystrokes. And that complicates things a bit. Not being a professional computer programmer I have been finding it difficult to get new features such as a chart generating ability merged with and running with Perl. And the entire research project is now being slowed as a result. One of my colleagues has done an extensive amount of work with Basic. And I even offered to pay him to help with the Perl development effort. But after he downloaded a copy of Perl and examined it he decided that this would involve too much effort. I have to agree with him. Once it is possible to create charts and .exe versions the plan is for researchers around the world to develop Perl modules for generating a variety of data related to sun, moon, planet, ocean tide crest and trough, and Solid Earth Tide locations. Most of those data can already be generated with other programs. Some of the data are not yet available anywhere as far as I am aware. If the effort is unusually successful the Perl program (or modules) might eventually be converted to CGI programs that will run at one or more Internet Web sites. From tkpmep at hotmail.com Fri Aug 17 09:08:37 2007 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: Fri, 17 Aug 2007 06:08:37 -0700 Subject: Downloading multiple csv files from a website Message-ID: <1187356117.474747.189980@g4g2000hsf.googlegroups.com> I'd like to download data from the website http://www.russell.com/Indexes/performance/daily_values_US.asp. On this web page, there are links to a number of .csv files, and I'd like to download all of them automatically each day. The file names are not visible on the page, but if I click on a link, a csv file opens in Excel. I've searched this group and looked into urllib, but have not found functions or code snippets that will allow me to download and rename each file. Would someone kindly point me to appropriate libraries/functions and/or code snippets that will get me started? Thanks in advance Thomas Philips From raims at dot.com Tue Aug 14 23:25:00 2007 From: raims at dot.com (Lawrence Oluyede) Date: Wed, 15 Aug 2007 05:25:00 +0200 Subject: make images with python References: <1187147338.400947.181010@x40g2000prg.googlegroups.com> Message-ID: <1i2vg8p.1d8t42r1jzvm9iN%raims@dot.com> stefano wrote: > I need make some images using python but i'm lost :P -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From zyzhu2000 at gmail.com Wed Aug 1 18:47:07 2007 From: zyzhu2000 at gmail.com (beginner) Date: Wed, 01 Aug 2007 22:47:07 -0000 Subject: A way to re-organize a list In-Reply-To: <5hanm6F3inuf2U3@mid.uni-berlin.de> References: <1184857535.033057.49150@m3g2000hsh.googlegroups.com> <1185932029.235957.226720@e9g2000prf.googlegroups.com> <5hanm6F3inuf2U3@mid.uni-berlin.de> Message-ID: <1186008427.082119.190150@g12g2000prg.googlegroups.com> On Aug 1, 1:31 am, Marc 'BlackJack' Rintsch wrote: > On Wed, 01 Aug 2007 01:33:49 +0000, beginner wrote: > > On Jul 19, 10:05 am, beginner wrote: > >> Hi Everyone, > > >> I have a simple list reconstruction problem, but I don't really know > >> how to do it. > > >> I have a list that looks like this: > > >> l=[ ("A", "a", 1), ("A", "a", 2), ("A", "a", 3), ("A", "b", 1), ("A", > >> "b", 2), ("B", "a", 1), ("B", "b", 1)] > > >> What I want to do is to reorganize it in groups, first by the middle > >> element of the tuple, and then by the first element. I'd like the > >> output look like this: > > >> out=[ > >> [ #group by first element "A" > >> [("A", "a", 1), ("A", "a", 2), ("A", "a", 3)], #group by > >> second element "a" > >> [ ("A", "b", 1), ("A", "b", 2)], #group by second element > >> "b" > >> ], > >> [ #group by first element "B" > >> [("B", "a", 1)], > >> [("B", "b", 1)] > >> ] > >> ] > > >> All the solutions I came up with are difficult to read and even harder > >> to go back and change, and I just feel are too complicated for such a > >> simple problem. I am wondering if anyone here has some insight. > > >> If there is a 'functional' way to do this, it would be even greater. > > >> Thanks, > >> Geoffrey > > > I guess I still don't quite get functional programming. Here is my > > imperitive way to do it in O(n). > > I didn't try to follow it but are you sure about O(n)? With the inner > loop going from 0 to `level` it looks suspiciously quadratic to me. You > really should try to grasp the `itertools.groupby()` solution. > > And the result of that script looks strange: > > [[[[1, 2, 3, 4], [1, 2, 4, 5], [1, 2, 'A', 'B']]], [[[2, 2, 'A', 'C']]]] > > Aren't the two top level elements wrapped in one list too much? > Furthermore the test data doesn't contain an example where the first item > is the same but the second item is different. > > > def group_items(source_list, f_list, target=[]): > > Default arguments are evaluated *once* when the ``def`` is executed. So > all calls to this function share the same list object bound to `target`. > Call this function twice without an explicit `target` and you'll see the > problem. > > Ciao, > Marc 'BlackJack' Rintsch- Hide quoted text - > > - Show quoted text - Wow. Thanks for the life-saving response. It uncovers a serious bug about the default argument! Thank you Marc! It is actually O(n) because it scans the list of records once and exactly once. The inner loop is trying to make multi-level grouping. In f_list, you define each level of grouping. For example, f_list=[f,g] in the above code means 1) you want to put records into sub-lists so that within each sub-list, the first element of the records are the same. then 2) within each group, you want to further group them by the second element of the records. That is why the results look like the following: [ [ #first level grouping [[1, 2, 3, 4], [1, 2, 4, 5], [1, 2, 'A', 'B']] #second level grouping ], [ #first level grouping [[2, 2, 'A', 'C']] #second level grouping ] ] In the example, the inner loop is executed twice. So it loops a total of 2*n times and it is O(n). If you want to make m level grouping, the execution time would be O(m*n). I looked at itertools. It is really cool. But if I just want to make multiple nested groups, reusing the above function is going to take less code than using itertools.groupby every time. Also, in itertools.groupby, I think you have to scan the list of records multiple times to make nested groups. Although it is still O(m*n), each operation of groupby is going to be slower. The one thing I still haven't figured out, is to make nested generators of multiple nested grouping, so that I can use a multi-loop to traverse them. A loop like below: for i in big_group: for j in i: for k in j: ..... i, j, k are generators. I think short of changing my function to be recursive and the outer function 'yield' to the inner function, which calls yield to make an inner generator, it will be difficult to do. Thanks again for pointing out the default value problem. Geoffrey From mccredie at gmail.com Fri Aug 24 13:13:00 2007 From: mccredie at gmail.com (Matt McCredie) Date: Fri, 24 Aug 2007 10:13:00 -0700 Subject: I can't get value of entry box, Tinker In-Reply-To: References: Message-ID: <9e95df10708241013j3a2999f4nc3cf34979804d695@mail.gmail.com> > What/should I, can I do? Fix your code? > def login(): > global e2,e1 > print e2.get() > print e1.get() That should work. Matt From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Aug 1 06:36:50 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 01 Aug 2007 12:36:50 +0200 Subject: Extending Python by Adding Keywords & Data types References: <1185913739.879602.212950@w3g2000hsg.googlegroups.com> <5h9n66F3j641tU5@mid.uni-berlin.de> <1185932558.472578.103690@o61g2000hsh.googlegroups.com> Message-ID: <5hb622F3j36bgU1@mid.individual.net> Maximus Decimus wrote: > Since, I am an amateur in using python, | Most commonly an amateur is understood to be someone who does | something without pay or formal training. Conversely, a | professional is someone who has received training in a particular | area and who also makes a living from it. So, you're not being paid coding in Python, and/or have no "official" training. Many readers of this list share this situation, me too. > could you please be more specific. I return the question. Your statements are most vague. Please give an example of what you try to realise. > For new data types, you had asked to implement the classes. I > intend to use C for implementing these data types. So where do i > need to implement these classes ie under which file or module in > the python package. Please do yourself a favor and read. Feel free to ask again for specific problems. http://docs.python.org/tut/node3.html http://docs.python.org/tut/node11.html Regards, Bj?rn -- BOFH excuse #135: You put the disk in upside down. From david at asdf.asdf Thu Aug 23 22:54:14 2007 From: david at asdf.asdf (bambam) Date: Fri, 24 Aug 2007 12:54:14 +1000 Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com> <1187898049.734696.9500@l22g2000prc.googlegroups.com> Message-ID: <13csi2tn49esmc3@corp.supernews.com> Wos! Several different thoughts: An object using yield to return only the relevant pages, one at a time. Pop to remove the items from the list. A dictionary to map between the strings and the integers. The dictionary was particularly unexpected. Eventually, I plan to change the string ports to device names. On the other hand, it looks like the only reason I have port numbers is to use as an index in things like this. After examining your suggestion, I realised that another thing I am interested in could be generalised: I want the complement of the set of ports in pages, given a universal set in tempList. Ignoring the break condition for the moment, and my problem with int(port)/str(port), would you have offered a different solution if I had asked for the relative complement of a small set? a= ['a','b','c'] b= ['b'] c= a-b #set theoretic difference, a\b, a.~b, ['a','c'] Steve. "Zentrader" wrote in message news:1187898049.734696.9500 at l22g2000prc.googlegroups.com... > Does page count change? i.e. is it necessary to retrieve it in every > loop or > tempList = ['1','2','3','4','5','6','7','8'] > sampleList=[] > page_count = self.parent.GetPageCount() > > for i in range(page_count): > > Also, once pagefound is set to True, all pages following will not be > appended to sampleList because it is not initialized to False under > the "for i in range(self.parent.GetPageCount())" loop. > > Finally, if I understand the logic and question correctly, you want > something like > tempList = ['1','2','3','4','5','6','7','8'] > sampleList=[] > page_count = self.parent.GetPageCount() > for port in tempList: > for i in range(page_count): > page=self.parent.GetPage(i) > if (hasattr(page, "port")) and (page.port != int(port)) : > sampleList.append(port) > > or perhaps (I'm not sure) > tempList = [1, 2, 3, 4, 5, 6, 7, 8] > sampleList=[] > page_count = self.parent.GetPageCount() > for i in range(page_count): > page=self.parent.GetPage(i) > if (hasattr(page, "port")) and (page.port not in tempList) : > sampleList.append(port) > HTH > From miki.tebeka at gmail.com Mon Aug 13 20:42:39 2007 From: miki.tebeka at gmail.com (Miki) Date: Tue, 14 Aug 2007 00:42:39 -0000 Subject: import * is not allowed ?? In-Reply-To: References: Message-ID: <1187052159.056797.252460@q4g2000prc.googlegroups.com> Hello Stef, > can anyone explain a little bit more what this error message means: > > import * is not allowed in function 'JAL_MAIN_RUN' because it contains > a nested function with free variables (JAL_simulation_file.py, line 22) > > what are "free variables" ? http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-10.html#%_idx_590 HTH, -- Miki http://pythonwise.blogspot.com From mensanator at aol.com Mon Aug 20 13:01:53 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 20 Aug 2007 10:01:53 -0700 Subject: I Need help from all the group participants In-Reply-To: References: Message-ID: <1187629313.357121.196370@q4g2000prc.googlegroups.com> On Aug 20, 9:16 am, Boris Ozegovic wrote: > Hi, > > I am working on some system, and the communication will take place through > the chatterbot which will be written in AIML (interpreter is written in > Python). English is not my mother tongue, so I need huge favor: if all of > you can write two sentences, so that I could have greater pattern base. > The first sentence is finding someone's heart rate, example: "Please, can > you tell me John's heart rate", and the other one is setting the alarm when > someone's heart rate is lower then x, and greater than y, example: "Can > you, please, send me information when John's heart rate is lower than 60, > and greater than 100". You can manipulate time (right now, now, right this > moment), and everything else you can think about. The only sentence that comes to mind is: "I hope I never find myself in a hospital that uses your system." > > -- > Ne dajte da nas la?ljivac Bandi? truje:http://cnn.blog.hr/arhiva-2007-06.html#1622776372 From steve at holdenweb.com Tue Aug 7 21:39:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 07 Aug 2007 21:39:05 -0400 Subject: Something in the function tutorial confused me. In-Reply-To: <46B8626A.2070303@bigfoot.com> References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <1186424693.529497.217040@w3g2000hsg.googlegroups.com> <46B8626A.2070303@bigfoot.com> Message-ID: Ricardo Ar?oz wrote: > Lee Fleming wrote: >> Thanks for all the help, everyone. I guess I was confused with default >> arguments that were mutable and immutable. I will continue to look >> over these posts until I understand what is happening. >> >> I cannot believe the number of helpful responses I got! >> > > Apparently he didn't understand. > Neither did I. > > Either (i)y's initial value (None or []) is saved somewhere to be > retrieved every time the function is called without 2nd argument, or > (ii) y keeps the value it has when last exiting the function (if there > is a third option, please mention it). > > (i) (a) whenever the function is called without 2nd argument the value > None is retrieved and assigned to y, thus causing [] to be assigned to y > by the 'if' statement. > (i) (b) But then if it is "def f(x, y = [])" the list [] should be ALSO > saved somewhere and when the function is called without 2nd argument it > should be retrieved and assigned to y, thus y would always be [] when > you enter the function without 2nd arg. > > (ii) (b) if y keeps the value it has when last exiting the function that > would explain that the second time you call it the list returned will > have two members. > (ii) (a) But then if it is "def f(x, Y = None)" when the "if" is > evaluated the empty list is assigned to y. So y will NO LONGER be None. > The second time the function is called y is NOT None (remember it keeps > it's last value) and the function returns a list with two members. > > So, as I see it, the behavior is not coherent, the function treats y > differently according to the value it has assigned. > > Please correct me! OK. The difference is that [] is a mutable value, while None is immutable. So when the function starts out with [] as y's value, and the value gets changed, the same value is used the next time the function is called and the second call sees the mutated value. When the function starts out with None as y's value any assignment to y causes it to reference a different value (since None is immutable). So the next time the function is called y is pointing at the None that it was pointing at the last time the function was called (since None cannot be mutated). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Aug 12 16:20:15 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 12 Aug 2007 22:20:15 +0200 Subject: wxPython - drawing without paint event References: <1186710391.148396.113490@d30g2000prg.googlegroups.com> <1186738813.373909.96230@x35g2000prf.googlegroups.com> <1186796567.331348.42450@q3g2000prf.googlegroups.com> <5i5l0dF2lortaU1@mid.individual.net> <1186883988.585048.16590@m37g2000prh.googlegroups.com> <5i8befF3o5no1U1@mid.individual.net> <1186928595.014008.61950@b79g2000hse.googlegroups.com> Message-ID: <5i98bsF3nmbavU1@mid.individual.net> 7stud wrote: > I don't. "wxPython in Action" is by far the worst computer book > I've ever purchased. It's poorly organized, poorly written, and > full of mistakes--and it's expensive. The fact that the authors > foist that piece of junk on unsuspecting newbies is a crime. Your opinion (I've seen much worse). But any suggestions what's better for a beginner? The (incomplete) tutorial surely not. Regards, Bj?rn -- BOFH excuse #88: Boss' kid fucked up the machine From indu_shreenath at yahoo.co.in Thu Aug 9 03:20:49 2007 From: indu_shreenath at yahoo.co.in (Indu Shreenath) Date: Thu, 9 Aug 2007 08:20:49 +0100 (BST) Subject: how to get output. In-Reply-To: <5hvrhhF3m15c7U1@mid.uni-berlin.de> Message-ID: <392550.47462.qm@web8601.mail.in.yahoo.com> Hey, I did write the following, but it does not work. import subprocess as sp try: = sp.Popen("DIR . /AD /B", stdout=sp.PIPE) result = p.communicate()[0] print result except: print "error" This throws error. DIR . /AD /B will list out only directories in the current directory. Thanks, Indu "Diez B. Roggisch" wrote: indu_shreenath schrieb: > Hey, > I want to get the output of "DIR /AD /B" command to a varriable using > python. How can I do this? Using the subprocess-module. However, I'm not sure what DIR /AD /B does - but there are many functions in module os that might deliver what you want without invoking an external command. Diez -- http://mail.python.org/mailman/listinfo/python-list --------------------------------- 5, 50, 500, 5000 - Store unlimited mails in your inbox. Click here. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick at craig-wood.com Tue Aug 21 14:30:06 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 21 Aug 2007 13:30:06 -0500 Subject: File Read Cache - How to purge? References: <1187669203.698637.81990@i38g2000prf.googlegroups.com> <5ivl9fF3rafecU1@mid.uni-berlin.de> Message-ID: Wolfgang Draxinger wrote: > Marc 'BlackJack' Rintsch wrote: > > > You mean reading the file without actually reading it!? :-) > > Linux provides its specific syscall 'readahead' that does exactly > this. It isn't in the posix module, but you can use it with ctypes like this >>> from ctypes import * >>> libc = CDLL("libc.so.6") >>> libc.readahead <_FuncPtr object at 0xb7de9714> >>> f=open("z","rb") >>> f.fileno() 3 >>> libc.readahead(f.fileno(), 0, 0x1000000) 0 >>> (That example could do with more ctypes magic to set the types and the return type of readahead...) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From stefan.behnel-n05pAM at web.de Tue Aug 21 02:44:27 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 21 Aug 2007 08:44:27 +0200 Subject: urllib2.urlopen(url) pulling something other than HTML In-Reply-To: <1187642916.824037.298750@o80g2000hse.googlegroups.com> References: <1187635452.841155.88720@a39g2000hsc.googlegroups.com> <1187641080.516885.122350@g4g2000hsf.googlegroups.com> <1187642916.824037.298750@o80g2000hse.googlegroups.com> Message-ID: <46CA89CB.5030809@web.de> dogatemycomputer at gmail.com wrote: > I personally think the application itself "feels" more complicated > than it needs to be but its possible that is just my inexperience. I'm > going to do some reading about the HTMLParser module. I'm sure I > could make this spider a bit more functional in the process. That's because you are using the standard library to parse HTML. While HTMLParser can do what you want it to, it's rather hard to use, especially for new users. If you want to give lxml.html a try, a web spider would be something like this: import lxml.html as H def crawl(url, page_dict, depth=2, link_type="a"): html = H.parse(url).getroot() html.make_links_absolute() page_dict[url] = (link_type, html) for element, attribute_type, href in html.iterlinks(): if href not in page_dict: if element.tag in ("a", "img"): # ignore other link types crawl(href, page_dict, depth-1, element.tag) page_dict = {} crawl("httt://www.google.com", page_dict, 2) # and now do something with the pages in page_dict. lxml can actually do a lot more for you, just look through the docs to get an idea. You can find lxml here: http://codespeak.net/lxml lxml.html is not yet released, though. Its first release (as part of lxml 2.0) is expected around the end of august. You can find some docs here: http://codespeak.net/lxml/dev and you can (easily) install it from Subversion sources: http://codespeak.net/svn/lxml/trunk Have fun, Stefan From ronysk at hotmail.com Mon Aug 6 04:00:27 2007 From: ronysk at hotmail.com (ronysk) Date: Mon, 6 Aug 2007 01:00:27 -0700 (PDT) Subject: Python/C API, Numeric Python, Type Conversion Message-ID: <12012369.post@talk.nabble.com> Hi, I am posting here to seek for help on type conversion between Python (Numeric Python) and C. Attachment A is a math function written in C, which is called by a Python program. I had studied SWIG and Python/C API a bit. I was able to pass numeric array (Numeric Python) into the C function and access/change these arrays. Problem I am having is that I couldn't quite get the array converted back to some PyObject or something that Python Interpreter can understand. So, alternatively I passed an empty numeric array as well as other arguments, and had return value(result) stored in that chunk of place. It sort of worked. However, if such function was called few times, it would result in segmentation fault. This is a lousy way to get around the return type matter, and probably is causing seg fault. Besides a correct type conversion, a proper SWIG interface probably could've saved all the fuss, maybe? ( attachment B is the SWIG interface I am using for this function) I am trying to study more on C API section of NumPy document, and to gain more knowledge off SWIG(which I only understand very basic way of it). Any feedback will be great. Thanks for your time, friends. Truly appreicate your precious time. Ronnie P.S. Those PyObject pointers are created with Numeric.Array( data, Numeric,Float64). Attachment A [code=c] /* ******************************************************************************* * * Function Name : * cressman() * * Usage : * PyObject* cressman * (int nx,int ny,PyObject* result,PyObject* us,PyObject* rlats, PyObject* * rlons, int nst,float disinf,float slon,float elon,float slat,float elat) * * Description : * Objective analysis by Cressman method * * Aumument : * nx(I) : x-dimension of grid data * ny(I) : y-dimension of grid data * result(I): an empty result set * us(I) : input station data * rlons(I) : x-coordinate of station * rlats(I) : y-coordinate of station * nst(I) : number of station data * disinf(I): influence radius distance(km) * slon(I) : x-coordinate of start grid longitude * elon(I) : x-coordinate of end grid longitude * slat(I) : y-coordinate of start grid latitude * elat(I) : y-coordinate of end grid latitude * * Data Files : None * * Called Function : * ardist() * * Return Value : * data : grid data value * * Linking Lib : None * *************************************************************************** */ PyObject* cressman (int nx,int ny,PyObject* result,PyObject* us,PyObject* rlats, PyObject* rlons, int nst,float disinf,float slon,float elon,float slat,float elat) { if( nst < 1) return; // initialization float xdelta,ydelta,disinf2,wsum,usum,xx,yy; float **data; float data_ave, sum; int i,j,k,count; // PyObject(python-C API) related PyArrayObject *p_us, *p_rlats, *p_rlons, *p_result; double *array_us, *array_rlats, *array_rlons, *array_result; p_us= (PyArrayObject *) us; p_rlats= (PyArrayObject *) rlats; p_rlons= (PyArrayObject *) rlons; p_result= (PyArrayObject *) result; if ( nst != p_us->dimensions[0]) return; array_us = (double*) p_us->data; array_rlats = (double*) p_rlats->data; array_rlons = (double*) p_rlons->data; array_result = (double*) p_result->data; // find out data avg sum=0; count=0; for (i=0;ispv) { sum+=array_us[i]; count++; } } if (count!=0) data_ave= sum / count; xdelta = (elon - slon)/(nx -1); ydelta = (elat- slat)/(ny -1); disinf2 = pow(disinf,2); for( i = 0; i < ny; i++) { for( j = 0; j < nx; j++) { wsum = 0.; usum = 0.; xx = slon + j*xdelta; yy = slat + i*ydelta; for( k = 0; k < nst; k++) { if( array_us[k] <= spv ) continue; //ardist just a function that calculates distance between 2 points float adist = ardist(array_rlons[k],array_rlats[k],xx,yy); if( adist > disinf ) continue; float adist2 = pow(adist,2); float w = (disinf2 - adist2)/(disinf2+adist2); wsum = wsum + w; usum = usum + (w*array_us[k]); } if( wsum != 0 ) //data[i][j] = usum/wsum; array_result[i*nx+j] = usum/wsum; else //data[i][j] = data_ave; array_result[i*nx+j] = data_ave; } } return result; } [/code] Attachment B - SWIG interface [code] /* objmod.i */ %module objmod %{ /* Put header files here or function declarations like below */ PyObject* cressman(int nx,int ny,PyObject* result,PyObject* us, PyObject* rlats,PyObject* rlons,int nst,float disinf, float slon,float elon,float slat,float elat); float ardist(float rlon,float rlat,float xx,float yy); %} extern PyObject* cressman(int nx,int ny,PyObject* result,PyObject* us, PyObject* rlats,PyObject* rlons,int nst,float disinf, float slon,float elon,float slat,float elat); extern float ardist(float rlon,float rlat,float xx,float yy); [/code] -- View this message in context: http://www.nabble.com/Python-C-API%2C-Numeric-Python%2C-Type-Conversion-tf4222760.html#a12012369 Sent from the Python - python-list mailing list archive at Nabble.com. From steve at holdenweb.com Wed Aug 1 06:56:36 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 01 Aug 2007 06:56:36 -0400 Subject: Python end of file marker similar to perl's __END__ In-Reply-To: <46b023ee$0$6528$9b622d9e@news.freenet.de> References: <1185940391.135261.130950@i38g2000prf.googlegroups.com> <1185947061.985093.306840@22g2000hsm.googlegroups.com> <46b023ee$0$6528$9b622d9e@news.freenet.de> Message-ID: Stargaming wrote: > On Wed, 01 Aug 2007 05:44:21 +0000, Michele Simionato wrote: > >> On Aug 1, 5:53 am, beginner wrote: >>> Hi All, >>> >>> This is just a very simple question about a python trick. >>> >>> In perl, I can write __END__ in a file and the perl interpreter will >>> ignore everything below that line. This is very handy when testing my >>> program. Does python have something similar? >> I wished from something like that. What you can do at the moment, is to >> comment or triple quote the code you don't want to run. > > Or, if in a function body, you could insert a `return` statement. When in > top-level code, invoking `sys.exit` (or exit/quit) can do the trick. A > ``raise Exception`` might help, too, but could be kinda distracting > sometimes. > > So, there is no general purpose solution as perl has it (I guess that > __END__ works everywhere at least), rather different solutions for > different cases. I think you have missed the point. A return statement or call to sys.exit() doesn't remove the requirement that the rest ofthe source file be legal Python. In a Perl program you can put anything you like after __END__. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From horpner at yahoo.com Thu Aug 2 09:08:41 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 02 Aug 2007 13:08:41 GMT Subject: Python end of file marker similar to perl's __END__ References: <1185940391.135261.130950@i38g2000prf.googlegroups.com> <1185976656.753817.27980@x40g2000prg.googlegroups.com> Message-ID: On 2007-08-02, Magnus Lycka wrote: > Neil Cerutti wrote: >> On 2007-08-01, Cameron Laird wrote: . >>> I want to re-emphasize the "triple-quote it" tip mentioned >>> earlier in this thread. I think the original questioner >>> will find this quite satisfying, if I understand his situ- >>> ation at all. >>> >>> *I* certainly have source code with embedded "junk" >>> commented out as multi-line strings. >> >> I used to do that, but now that I use doctests so much it's >> infeasible to comment out arbitrary code that way, since they >> can't necessarily nest. > > If you consistently use e.g. ''' for doc strings, you can use > """ to comment out code blocks. But then I couldn't use """ in my docstrings! ;) Actually, I wound up converting all my multiline doctests to use concatenation instead, since they were ruining my syntax highlighting performance in Vim. -- Neil Cerutti We shall reach greater and greater platitudes of achievement. --Richard J. Daley From dejanews at email.com Sun Aug 19 08:58:36 2007 From: dejanews at email.com (samwyse) Date: Sun, 19 Aug 2007 12:58:36 GMT Subject: Development for dual core machine In-Reply-To: <1187515287.226791.186700@j4g2000prf.googlegroups.com> References: <1187515287.226791.186700@j4g2000prf.googlegroups.com> Message-ID: <08Xxi.28398$RX.5261@newssvr11.news.prodigy.net> Andy wrote: > Hi guys, > > I'm sorry, I'm not sure this is the correct group to be asking this > kind of question... > > I'm going to develop a software package that includes a web server > (and PHP code) , a database, and some Python code of course. I am > being strongly suggested to make it to work on a dual- or multi-core > computer, but I'm confused on how to take advantage of the multiple > CPUs. > >>From what I read, I think that simply by making the package run in > several separate processes (web server, database server, Python > interpreter, etc.), and/or using multiple threads (which I will > anyway) the package should be able to use multiple CPUs. > > Is my understanding correct? So actually, all I have to do is just > write my multi-threaded Python code as usual? And how is it decided > which process and which threads go to CPU 1, CPU 2, etc.? Perhaps the > BIOS? > > Any advice greatly appreciated. > Andy > The Python interpreter is not multi-cpu aware, so using Python threads won't work on multiple CPUs. If your tasks are CPU-bound, then fork multiple processes. Most web servers (Apache) can handle this automatically for you. From steve at holdenweb.com Mon Aug 6 23:49:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 06 Aug 2007 23:49:52 -0400 Subject: Relative-importing * In-Reply-To: <1186454723.425679.220510@q3g2000prf.googlegroups.com> References: <1185559874.299008.167010@x40g2000prg.googlegroups.com> <871weth2gg.fsf@benfinney.id.au> <46ae3894$0$19609$426a34cc@news.free.fr> <1186200218.666444.254200@q3g2000prf.googlegroups.com> <87vebv9yrr.fsf@benfinney.id.au> <1186363732.188847.48070@q3g2000prf.googlegroups.com> <87zm15870h.fsf@benfinney.id.au> <1186454723.425679.220510@q3g2000prf.googlegroups.com> Message-ID: rbygscrsepda at gmail.com wrote: > On Aug 6, 12:19 am, Ben Finney > wrote: >> rbysam... at gmail.com writes: >>> (In addition, it probably would make the program somewhat slower to >>> have an internal class inside every module, and performance is >>> important to me, as I'm planning to use this project in a future >>> game. >> This is known as "premature optimisation", and it's harmful. It's >> folly to avoid a core part of the language because you're worried >> about hypothetical performance issues. >> >> Instead, write your program so that it's easy to understand and >> maintain; then, if it's noticeably slow, *measure* the performance >> using profiling so you know exactly what is slow; then, and only then, >> work on speeding up the slow parts. >> >>> These modules are not going to have full-fledged object construction >>> and so forth. I don't want to construct and use objects at all >> If that's truly what you desire, you're using the wrong >> language. Everything inPythonis an object, even if you don't use >> object-oriented programming. >> >>> it seems like a waste of time and memory to me to inherit __new__, >>> __del__, and so on. >> You've stated that you're a beginner to programming, so you probably >> are unaware that this statement has no basis in how class inheritance >> actually works. The point is that inherited behaviour is implemented >> in *one* place, not that it's repeated everywhere. >> >> Moreover, this is a further expression of your tendency for premature >> optimisation. You should aim instead to write code naturally (learning >> what's natural when you're a beginner), and only once you have >> something that *works* should you think about performance issues. >> >>> All that I want these modules to do is to encapsulate varying >>> information and behavior for /other/ objects to use.) >> This sounds like an ideal case for seeting up a class hierarchy for >> this move behaviour. >> >>> But regardless of if it's the "right thing to do", do you all think >>> it's an unintended bug? >> Do we think what is an unintended bug? >> >> I think if you go out of your way to avoid the class inheritance >> system for implementing what looks strongly like a hierarchy of >> behaviour, you will have design bugs. Hopefully now that you're >> reading this thread, they won't be *unintended* bugs; whether you >> *intentionally* proceed with a buggy design is up to you :-) >> >> -- >> \ "With Lisp or Forth, a master programmer has unlimited power | >> `\ and expressiveness. WithPython, even a regular guy can reach | >> _o__) for the stars." -- Raymond Hettinger | >> Ben Finney > > I understand what you're saying; thank you for the advice. :) But > unfortunately, my original question wasn't completely answered. > > I wasn't asking about if my own program had a bug, in the first place. > I was asking if the error I talked about in the first post was a bug > in the Python compiler itself. It's undocumented, and so it seems > unintended--especially since importing * is a feature built in to > Python on purpose, whether or not it's easily abused or if it's > useful. > > Here's the error again--whenever you try to import * from a relative > package like ., .., .sibling, ..cousin, and any other package name > starting with "*", you get an error. > > Specifically, in Python 1.5, all of the following generate the error > below: > > from . import * > from .sibiling_package import * > from .. import * > from ..cousin_package import * > > SyntaxError: 'import *' not allowed with 'from .' > > Importing * is a feature, but this seems like an artificial > inconsistency to me. It's as if the compiler raises an error when it > tries to import * as soon as it sees "from .", regardless of what > comes after it. So is this a bug in python? And if it happens to be a > bug, how can I alert the developers of the python compiler? > > Again, thank you! :) > Well, since the error message is quite explicit I think we can rule out any thought that the compiler is behaving in an unintended way. In other words, it's *not* a bug, but an intentional device to keep the naughty such as yourself on the straight and narrow. There is a quite explicit syntax check in ast.c precisely to exclude the possibility of "from ... import *" with relative module names, so you are going to have to live with that. It looks like the answer to a change request is going to be same as from __future__ import braces which I recommend you try ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From aleax at mac.com Sun Aug 26 01:14:37 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 25 Aug 2007 22:14:37 -0700 Subject: Does shuffle() produce uniform result ? References: Message-ID: <1i3f9na.25k9c68wblrkN%aleax@mac.com> tooru honda wrote: ... > def rand2(): > while True: > randata = urandom(2*1024) > for i in xrange(0, 2*1024, 2): > yield int(hexlify(randata[i:i+2]),16) # integer > in [0,65535] another equivalent possibility, which might probably be faster: import array ... def rand2(): while True: x = array.array("H") x.fromstring(urandom(2*4000)) for i in x: yield i Alex From JHoover at fbi.gov Tue Aug 7 14:53:01 2007 From: JHoover at fbi.gov (Gordon Airporte) Date: Tue, 07 Aug 2007 14:53:01 -0400 Subject: Heterogeneous lists Message-ID: This is one of those nice, permissive Python features but I was wondering how often people actually use lists holding several different types of objects. It looks like whenever I need to group different objects I create a class, if only so I can use more meaningful names than '[2]' for the items. How often do these show up in your code? Is this simply the upshot of the underlying arrays holding only object references of some sort? From j.spies at hccnet.nl Sun Aug 19 18:04:40 2007 From: j.spies at hccnet.nl (Jaap Spies) Date: Mon, 20 Aug 2007 00:04:40 +0200 Subject: Python on Computation, Math and Statistics In-Reply-To: References: Message-ID: W. Watson wrote: > I would hope Python is doing a lot of standard computations beyond > arithmetic. Trig functions and more. Comments? Try SAGE: http://www.sagemath.org/ Jaap Permanents are here forever. From gagsl-py2 at yahoo.com.ar Tue Aug 28 01:05:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 28 Aug 2007 02:05:23 -0300 Subject: an eval()-like exec() References: <1188241165.418263.165730@k79g2000hse.googlegroups.com> Message-ID: En Mon, 27 Aug 2007 15:59:25 -0300, Abel Daniel escribi?: > Hi! > > A python interactive interpreter works by having the user type in some > code, compiling and running that code, then printing the results. For > printing, the results are turned into strings. This last stage is done by calling sys.displayhook - you can replace that function with your own one, and get the object to be printed. Any of your previous attempts (using compile(...,"single")+eval, using exec, or creating your own code.InteractiveInterpreter) should work with this. -- Gabriel Genellina From oliver.andrich at gmail.com Sun Aug 19 13:44:46 2007 From: oliver.andrich at gmail.com (oliver.andrich at gmail.com) Date: Sun, 19 Aug 2007 17:44:46 -0000 Subject: ctypes and unsigned char* Message-ID: <1187545486.797017.308720@a39g2000hsc.googlegroups.com> Hi, can anybody with ctypes experience tell me, how to handle a C function that returns an unsigned char*? Obviously it is not a restype of c_char_p. Best regards, Oliver From cjankowski at hbr-inc.com Mon Aug 6 15:20:09 2007 From: cjankowski at hbr-inc.com (cjankowski at hbr-inc.com) Date: Mon, 06 Aug 2007 12:20:09 -0700 Subject: Any Good Book To Start ? In-Reply-To: <1186427734.352753.183520@z24g2000prh.googlegroups.com> References: <1186426924.388898.224310@l70g2000hse.googlegroups.com> <1186427734.352753.183520@z24g2000prh.googlegroups.com> Message-ID: <1186428009.574472.160460@e9g2000prf.googlegroups.com> On Aug 6, 3:15 pm, kyoso... at gmail.com wrote: > On Aug 6, 2:02 pm, Katie Tam wrote: > > > Please let me know any good book to start ? Thank You > > > Katie Tam > > CCNP, CCDP > > LinkWaves Corporation > > **Leading Provider of Cisco Equipment**http://www.linkwaves.com > > To start learning Python or what? > > "Python Programming 3rd Ed." by Lutz is good for learning deeper > concepts in Python, but is probably better suited for experienced > programmers. I still recommend it though, as it has lots of case > studies and cool examples. > > "Python for Dummies" gives a good overview of Python for a complete > n00b. There are many other beginner Python books, most of which are > pretty nice, but not equal in quality. > > Mike I like "Learning Python" by Lutz & Ascher (O'Reilly), very good for beginners. Chris From http Fri Aug 3 21:36:40 2007 From: http (Paul Rubin) Date: 03 Aug 2007 18:36:40 -0700 Subject: How to pass a reference to the current module References: Message-ID: <7x4pjgjd1z.fsf@ruckus.brouhaha.com> James Stroud writes: > > please describe less abstractly what you're trying to do. > You sound like my former thesis adviser. I couldn't understand what you were trying to do either. > OK. From an external source, such as configuration file, the user will > specify the *name* of a function somehow with the assumption that the > function will be coded somewhere (in the present or other modules) by > that name. Is something wrong with import some_module func = getattr(some_module, func_name) ? From ca.allen at gmail.com Wed Aug 29 15:47:15 2007 From: ca.allen at gmail.com (Chris Allen) Date: Wed, 29 Aug 2007 12:47:15 -0700 Subject: sys.argv is munging my command line options In-Reply-To: <1188415680.744407.21190@r34g2000hsd.googlegroups.com> References: <1188414714.645724.63330@i38g2000prf.googlegroups.com> <1188415680.744407.21190@r34g2000hsd.googlegroups.com> Message-ID: <1188416835.325173.14310@q4g2000prc.googlegroups.com> Thanks for the reply. Oops... I forget that I was calling the program from a shell script, the shell script was responsible for goofing up my command line options. Solved. Thanks again. On Aug 29, 12:28 pm, Ant wrote: > On Aug 29, 8:11 pm, Chris Allen wrote: > ... > > > But I'm running into a problem with this which is that sys.argv splits > > my key=value options. I need to know the option associations, and > > there's no way to know this by inspecting sys.argv. Can I get access > > to the command line string as python saw it before it split it into > > sys.argv or is there another way? Thanks. > > Could you show us some example code that demonstrates this? The > following works as expected for me on win32: > > # test.py > import sys > > for arg in sys.argv[1:]: > print arg > > >From the command prompt: > > C:\0>test.py action key=value key=value > action > key=value > key=value > > -- > Ant. From http Thu Aug 30 21:41:55 2007 From: http (Paul Rubin) Date: 30 Aug 2007 18:41:55 -0700 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> Message-ID: <7xlkbsmqe4.fsf@ruckus.brouhaha.com> Bruno Desthuilliers writes: > FWIW, the "Eiffel and SPARK Ada folks" also "brilliantly explained" > why one can not hope to "write reliable programs" without strict > static declarative type-checking. I don't know about Eiffel but at least an important subset of SPARK Ada's DBC stuff is done using static analysis tools (not actually built into the compiler as it happens) to verify statically (i.e. without actually running the code) that the code fulfills the DBC conditions. I don't see any way to do that with Python decorators. From bj_666 at gmx.net Wed Aug 29 18:16:38 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 29 Aug 2007 22:16:38 GMT Subject: re compiled object result caching? References: <1188417101.936530.182480@50g2000hsm.googlegroups.com> Message-ID: <5jm9i5F6oarU2@mid.uni-berlin.de> On Wed, 29 Aug 2007 21:54:50 +0000, Dan Stromberg - Datallegro wrote: > I've long felt that publicly accessible attributes probably should be > syntactic sugared to look like accessor methods, a bit like how __add__ > ends up being + - so that if your attribute ever needs to become methods > (say, it started out life as a unidimensional thing, but later needs to > be a flattening of 3 dimensions or something), you won't necessarily need > to change depenent code. Maybe you should read about the `property()` function. Ciao, Marc 'BlackJack' Rintsch From carsten at uniqsys.com Fri Aug 3 21:04:18 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 03 Aug 2007 21:04:18 -0400 Subject: How to pass a reference to the current module In-Reply-To: References: Message-ID: <1186189458.3263.6.camel@localhost.localdomain> On Fri, 2007-08-03 at 17:22 -0700, James Stroud wrote: > Hello All, > > Say I have this code: > > > import AModule > import ModuleUser > > ModuleUser.do_something_with(AModule, 'some_function_name') > > > But say the functions are defined in the same module that contains the > above code. I can imagine this hack: > > > import AModule > import ModuleUser > > ModuleUser.do_something_with(AModule.__name__, 'some_name') > > > Where AModule.__name__ could be substituted for __name__ under the > proper circumstances. Then, I would have this code in ModuleUser: > > > import sys > def do_something_with(modname, funcname): > afunction = sys.modules[modname].funcname > [etc.] > > > Which is terribly ugly to me and makes for a pretty miserable API in my > opinion, requiring the programmer to type underscores. > > > Basically, what I am trying to acomplish is to be able to do this in any > arbitrary module or __main__: > > > funcname = determined_externally() > ModuleUser.do_something_with(AModule, funcname) > > > Ideally, it would be nice to leave out AModule if the functions were > designed in the same namespace in which do_something_with is called. > > Thanks in advance for any suggestions. I can't be too sure because you may have abstracted away too much of what you're actually trying to accomplish, but it seems to me that instead of passing a reference to the current module and a function name, you should just pass a reference to the function that you want do_something_with to call. If I missed the point of your question, please describe less abstractly what you're trying to do. -- Carsten Haese http://informixdb.sourceforge.net From mcl.office at googlemail.com Sat Aug 18 18:14:56 2007 From: mcl.office at googlemail.com (mosscliffe) Date: Sat, 18 Aug 2007 15:14:56 -0700 Subject: Symbolic Link Message-ID: <1187475296.173269.263080@k79g2000hse.googlegroups.com> I am trying to create a link to a file, which I can then use in an HTML page. The system is Linux on a hosted web service, running python 2.3. Other than that I have no knowledge of the system. The link is created OK, but when I try to use it as filename for the IMG TAG, it does not get displayed. The page source of the created page is pointing to the link as temp/test1.jpg Any ideas ? srcFile = "temp/test2.jpg" linkFile = "temp/test1.jpg" if os.path.islink(linkFile): print "Link Exists", nl pass else: print "Making Link", nl os.symlink(srcFile, linkFile) print '
the image

' % linkFile print 'the image' % srcFile From CarpeSkium at gmail.com Fri Aug 17 14:02:17 2007 From: CarpeSkium at gmail.com (CarpeSkium at gmail.com) Date: Fri, 17 Aug 2007 18:02:17 -0000 Subject: question Message-ID: <1187373737.410546.70930@w3g2000hsg.googlegroups.com> "I've parsed a webpage into a text file. In doing so, I've kept all the text I'm interested in, and removed all the text I don't want. My result is a text file that is comma-separated. However, the text file is one, very long, single string. I need to substitute every eighth (8th) comma with a new line ("\n"). I've tried regular expressions, but don't know how to make this happen on only every eighth comma. I'd post my code, but none of it works. Thanks for the help." From martin.marcher at gmail.com Thu Aug 30 11:19:04 2007 From: martin.marcher at gmail.com (Martin Marcher) Date: Thu, 30 Aug 2007 17:19:04 +0200 Subject: We need PIGs :) In-Reply-To: <5jn92hFdmbcU2@mid.uni-berlin.de> References: <5jn92hFdmbcU2@mid.uni-berlin.de> Message-ID: Hello, On 30 Aug 2007 07:14:25 GMT, Marc 'BlackJack' Rintsch wrote: > On Thu, 30 Aug 2007 07:10:47 +0200, Martin Marcher wrote: > > > Does that sound like a good idea or would that be over formalization? > > Sounds like over engineering/formalization to me. > You are aware of the Python Enhancement Proposals (PEPs)? Yes I am thought I mentioned the wsgi pep in the mail... > Is something like the `Python Database API Specification v2.0`_ or `API > for Block Encryption Algorithms v1.0`_ what you are looking for? http://en.wikipedia.org/wiki/Java_Authentication_and_Authorization_Service http://en.wikipedia.org/wiki/Content_repository_API_for_Java http://jcp.org/en/jsr/all But since python is much more open in these terms these hints should guide developers thru solutions so that they know they can use other modules/classes without any effort if such a specificaton exists. In Java it is more like not implementing any of these things is > > .. _API for Block Encryption Algorithms v1.0: > http://www.python.org/dev/peps/pep-0272/ > .. _Python Database API Specification v2.0: > http://www.python.org/dev/peps/pep-0249/ Indeed i wasn't aware of these (I know the wsgi spec) but I was more thinking about guidelines where you can be quite sure that because of not being able to provide an implementation that is so general that it could be incorporated in the standard library. Think of * object relational mappers (probably a bad example - but would be still nice) * service registries * service repositories * .... that use the same interface so that you can swap them effordlessly. I'm thinking big here so that generalization has to be applied to the problems but also that you can keep to well known interface to implement so that it will work out for the majority of situations in these fields. I do know the WSGI spec but I do think that (otherwise I wouldn't have had the idea) that PEPs are the wrong place for that. To me PEPs are (better should be) about the plain stock standard library and how to work with it (coding guidelines, docstring, iterators, generators - specification of the language) PIGs (given the name is arguable - I just like it it removes a bit of the necessary formal taste it has) should define: * problem * solution * expected behaviour * interface (probably even prepare unit tests if the interface is stabilized) but should by itself not implement anything as for example the DBAPI does. and given the nature of the field (spezialized for a task but still applies to a lot of people) an general purpose implementation wouldn't be useful hope that explains it well enough. I've been in a couple of projects where problems where common to all those projects but the specification made up by individual (project) managers made it impossible to reuse parts of other apps (and I guess with some "official" backup one could point back on proven recipies - that's probably the term that describes it best) greetings (always wondered is that a formal or informal closing part in english letters?) martin From zyzhu2000 at gmail.com Wed Aug 1 12:24:03 2007 From: zyzhu2000 at gmail.com (beginner) Date: Wed, 01 Aug 2007 16:24:03 -0000 Subject: Assertion in list comprehension In-Reply-To: <1185984540.245193.270110@i13g2000prf.googlegroups.com> References: <1185982643.001546.138180@e16g2000pri.googlegroups.com> <1185984540.245193.270110@i13g2000prf.googlegroups.com> Message-ID: <1185985443.357632.6410@d30g2000prg.googlegroups.com> On Aug 1, 11:09 am, "danmcle... at yahoo.com" wrote: > On Aug 1, 9:37 am, beginner wrote: > > > > > > > Hi, > > > Does anyone know how to put an assertion in list comprehension? I have > > the following list comprehension, but I want to use an assertion to > > check the contents of rec_stdl. I ended up using another loop which > > essentially duplicates the functions of list comprehension. It just > > look like a waste of coding and computer time to me. > > > I just wish I could put the assertions into list comprehensions. > > > x=[(rec_stdl[0].st/10000.0, > > rec_stdl[0].cl, > > rec_stdl[0].bb, > > rec_stdl[0].bo, > > rec_stdl[1].bb, > > rec_stdl[1].bo, > > rec_stdl[0].ex > > ) > > for rec_stdl in rec_by_ex if len(rec_stdl)==2 > > ] > > > #duplicated loop > > if __debug__: > > for rec_stdl in rec_by_ex: > > l=len(rec_stdl) > > assert(l<=2 and l>0) > > if l==2: > > assert(rec_stdl[0].c=="C" and rec_stdl[1].c=="P") > > assert(rec_stdl[0].ex==rec_stdl[1].ex) > > assert(rec_stdl[0].st==rec_stdl[1].st) > > assert(rec_stdl[0].cp==rec_stdl[1].cp) > > > Thanks, > > Geoffrey > > Can't you just call a function from within your list comprehension and > do whatever you want for each item? Something like this (not tested): > > def checker(item): > assert(len(item) <= 2 and len(item) > 0) > if len(item) == 2: > assert(item[0].c == "C" and item[1].c == "P" > > return len(item) == 2 > > x = [whatever for item in all_items if checker(item = item)]- Hide quoted text - > > - Show quoted text - Good idea! Thank you! From goldtech at worldpost.com Sat Aug 11 18:48:26 2007 From: goldtech at worldpost.com (goldtech) Date: Sat, 11 Aug 2007 22:48:26 -0000 Subject: C++ Runtime Library error message - Pythonwin? Message-ID: <1186872506.132154.61610@x35g2000prf.googlegroups.com> Hi, Doing GIS [Geographic Information Systems] scripts. I was running a batch clip script that worked OK for 126 iterations then I got the following message: "Microsoft Visual C++ Runtime Library program: C:\python21\pythonwin\pythonwin.exe This application has requested the runtime to terminate in an unusual way. Please contact the applications support team for more information." What does this mean? Using XP. Is there a log on my system that gives more info? Thanks From jstroud at mbi.ucla.edu Thu Aug 16 19:53:30 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 16 Aug 2007 16:53:30 -0700 Subject: Cancelling events on a COM Object In-Reply-To: References: Message-ID: Oliver, wait a while before you panic about your post not getting through! James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From aleax at mac.com Mon Aug 20 11:43:50 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 20 Aug 2007 08:43:50 -0700 Subject: yet another indentation proposal References: <1187591109.948771.144690@g4g2000hsf.googlegroups.com> Message-ID: <1i34y7s.l9m7j5jogddN%aleax@mac.com> Jakub Stolarski wrote: > Why not just use comments and some filter. Just write # _{ at the > beginning and # _} at the end. Then filter just before runing > indenting with those control sequences? Then there's no need to change > interpreter. As I pointed out in another post to this thread, that's essentially what Tools/scripts/pindent.py (part of the Python source distribution) does (no need to comment the beginning of a block since it's always a colon followed by newline; block-end comments in pindent.py are more informative). Just use and/or adapt that... Alex From bdesth.quelquechose at free.quelquepart.fr Mon Aug 20 13:51:00 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 20 Aug 2007 19:51:00 +0200 Subject: desperately in need of a tool In-Reply-To: <1187560418.339131.283470@i38g2000prf.googlegroups.com> References: <1187560418.339131.283470@i38g2000prf.googlegroups.com> Message-ID: <46cca95c$0$431$426a34cc@news.free.fr> yagyala a ?crit : > Hi. > > I recently started working for a company that has just implemented its > first set of software standards. So far, so good. Here's the problem: > one of those standards is that the comments for each routine must > indicate every other routine that it calls. May I suggest that this is a totally *stupid* (and FWIW, totally impossible to apply) "standard" ? Consider the following code, which is totally dumb but quite close to real-life code in it's design (use of polymorphic dispatch, HOFs and anonymous functions...) : def some_func(obj, callback): return callback(obj.method()) class One(object): def method(self): return 42 class Two(object): def __init__(self, val): self.val = val def method(self): return self.val / 3 def cb_one(val): return val + 2 def cb_two(val): return val * 3 + 42 arg_pairs = [(One(), cb_one), (One(), cb_two), (Two(33), cb_one), (Two(99), cb_two) (One(), lambda x: x ** 2] for obj, cb in arg_pairs: print some_func(obj, cb) How are you going to list the functions called by some_func ??? (snip) > I'm sure some will wonder about the reasoning of this standard. Indeed !-) > The > company primarily has experience writing scientific alogorythms which > can get rather long. It makes a bit more sense to document all > routines called for a very long routine, but for short routines that > primarily call other routines, as most mine do, well.... Show the above code to your PHB and ask him to explain how you're going to apply the "standard"... From a.schmolck at gmail.com Mon Aug 13 13:46:19 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Mon, 13 Aug 2007 18:46:19 +0100 Subject: decorators - more than just syntactic sugar References: <46be005e$0$13866$ba620e4c@news.skynet.be> <1186985383.303334.110230@19g2000hsx.googlegroups.com> Message-ID: Michele Simionato writes: > On Aug 11, 8:30 pm, Helmut Jarausch wrote: >> Hi, >> >> are decorators more than just syntactic sugar in python 2.x and what >> about python 3k ? > > Well, I argued may times that syntactic sugar is important (all Turing > complete languages differs by syntactic sugar only) Although I agree that "mere" syntactic sugar matters, I think you're overstating the point. I would argue that most people would understand syntactic sugar as equivalent to a (very) localized program transformation. Things like first class continuations clearly aren't syntactic sugar in that sense. 'as From kay.schluehr at gmx.net Mon Aug 13 02:27:14 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 12 Aug 2007 23:27:14 -0700 Subject: decorators - more than just syntactic sugar In-Reply-To: <46be005e$0$13866$ba620e4c@news.skynet.be> References: <46be005e$0$13866$ba620e4c@news.skynet.be> Message-ID: <1186986434.625285.143920@19g2000hsx.googlegroups.com> On Aug 11, 8:30 pm, Helmut Jarausch wrote: > How can I find out the predefined decorators? I dare to say that's not easy. Since decorators are just(?) syntactical sugar they don't obtain a particular semantics expressed by distinctive declarative elements. Unlike generators which can be identified looking for a yield expression a decorator can be identified syntactically just when it is used. However this might be sufficient, depending on your intention? From Graham.Dumpleton at gmail.com Sat Aug 18 03:31:20 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sat, 18 Aug 2007 07:31:20 -0000 Subject: Overriding Thread.join in derived class. Message-ID: <1187422280.018913.184990@q3g2000prf.googlegroups.com> If one creates a thread using threading.Thread and makes it a daemon by calling setDaemon(), then when Python is exiting it will not attempt to call join() on that thread and wait for it to complete first. The problem with this is that the daemonised thread will continue to run while atexit register callbacks are being called and while Python is being subsequently destroyed The result is that the daemonised thread may access application components that have been cleaned up and in the worst case as Python progresses with destroying interpreters it could try accessing things like sys.modules which may no longer exist. End result is that it could result in a Python exception at some point, evidenced by messages starting with: Exception in thread Thread-1 (most likely raised during interpreter shutdown) or: Unhandled exception in thread started by > In order to avoid this, do people think that as an alternative to creating daemonised thread that it would be reasonable to create a derived Thread class for the particular task which overrides Thread.join() method to set some flag or otherwise take some action that the thread would notice to tell it to stop, and then call base class Thread.join(). This way you can flag the thread to shutdown automatically when Python is going around calling join() on non daemonised threads. Or am I missing the obvious as far as ways of flagging threads to tell them to stop? Note that this is where Python is being used embedded in a C program. There is no Python main function where code can be put to signal threads to otherwise stop. Graham From Robert.R.Emmel at gmail.com Thu Aug 30 12:53:01 2007 From: Robert.R.Emmel at gmail.com (Robert.R.Emmel at gmail.com) Date: Thu, 30 Aug 2007 09:53:01 -0700 Subject: Python threading Message-ID: <1188492781.894079.153260@r23g2000prd.googlegroups.com> Hello, I am using the threading module and the Queue module in python to to send out shipment tracking URL requests. Is there a way to timeout a thread within a Queue? I think the way I have it now the thread will wait until something is returned and will basically wait forever for that something. Between the waiting for something to be returned and the timeouts on the database connections, the program appears to just hang like it has stopped working. Any suggestions? Here is a sample of code I am using (left out some of the code for brevity): import urllib from HTMLParser import HTMLParser import threading import Queue NTHREADS = 100 ... def Web_Retrieve(inpque, outqueue): N = 1 try: connection = MySQLdb.connect(host="hostname", port=3306, user="username", passwd="password", db="Mydatabase") print "t" + str(N)+ " - Database Connection Established !!" cursor = connection.cursor() except MySQLdb.OperationalError, message: errorMessage = "t" + str(N)+ " -Error %d:\n%s" % (message[0], message[1]) else: DBRow = inpque.get() while not (DBRow[0] == ''): PNum = DBRow[1] PNum = RemoveHyphens(RemoveSpaces(PNum)) print "t" + str(N)+ " -PNum : " + PNum ... # Setup URL to retrieve status web page depending on Carrier SCAC if SCAC == "RDWY": pURL = "http://www.quiktrak.roadway.com/cgi- bin/quiktrak?" bURL = "&pro0=" + PNum if DEBUG > 90 or (DEBUG > 30 and DEBUG < 40): print "t" + str(N)+ " -URL: ", pURL + bURL WURL = pURL + bURL # Retrieve status web page, assign it to a variable and close connection try: f = urllib.urlopen(pURL+bURL) s = f.read() f.close() except IOError, e: print 't' + str(N)+ ' -I/O Error: ',e.strerror ## continue ... outqueue.put((PR, s, WURL, s12)) DBRow = inpque.get() N = N+ 1 outqueue.put(None) cursor.close() connection.commit() connection.close() print "t" + str(N)+ " -Database Closed" ## Main processing file. def WebProcess(Mode): ## Get file listing from the proper directory depending on mode if Mode == 'B': IFilenames = os.listdir(os.curdir+os.sep+'Input') NTHREADS = 100 ... # Open connection to MySql try: connection = MySQLdb.connect(host="hostname", port=3306, user="username", passwd="password", db="mydatabase") print "Database Connection Established !!" cursor = connection.cursor() except MySQLdb.OperationalError, message: errorMessage = "Error %d:\n%s" % (message[0], message[1]) else: inputs = Queue.Queue(0) results = Queue.Queue(0) thread_pool = [] for ii in range(NTHREADS): thread = threading.Thread(target=Web_Retrieve, args=(inputs, results)) thread.start() thread_pool.append(thread) ## Retrieve BOL's from Database for web retrieval print "Current Mode is : ", Mode print "Length of Mode string is : ", len(Mode) Mode_results = cursor.execute( "Select * from bol_table where Mode = %s and (Expired IS NULL or Expired IS False);", (Mode.strip())) print "Mode Query Results: ", Mode_results if Mode_results > 0: print " Do Web Page lookups !!! " DBRows = cursor.fetchall() for DBRow in DBRows: inputs.put(DBRow) for ii in range(len(DBRows)): PR, s, WURL, s12 = results.get() ## print "PR is : "+PR+" S's first 100 char's are "+s[0:100]+" WURL is : "+WURL print "+-------------------------------------------------------------+" print "PR is : " + PR print "s is (First 100) : " + s[0:100] print "WURL is : " + WURL print "s12 is : " + s12 print "+-------------------------------------------------------------+" .... ## Clear out thread pool for thread in thread_pool: inputs.put(('','')) .... For the times I have run into the "" on web pages I take the f.read() string s and pass it to this function: ## fix webpages that have the 'scr' + 'ipt' split on them. def fixscript(x): SQ = 0 EQ = 0 ## if DEBUG > 90: ## print "fixscript length of x: ", len(x) while True: SQ = x.find('scr" + "ipt', SQ + 12) ## if DEBUG > 90: ## print "SQ : ", SQ if SQ <= 0: break x = x[0:SQ + 3] + x[SQ + 8:] return x Just passing this along to those who have run into this problem when parsing a web page. From jstroud at mbi.ucla.edu Sun Aug 19 04:27:46 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 19 Aug 2007 08:27:46 GMT Subject: Understanding closures In-Reply-To: <1187499818.125192.12930@m37g2000prh.googlegroups.com> References: <1187499818.125192.12930@m37g2000prh.googlegroups.com> Message-ID: <6aTxi.9264$3x.2221@newssvr25.news.prodigy.net> Ramashish Baranwal wrote: > Hi, > > I want to use variables passed to a function in an inner defined > function. Something like- > > def fun1(method=None): > def fun2(): > if not method: method = 'GET' > print '%s: this is fun2' % method > return > fun2() > > fun1() > > However I get this error- > UnboundLocalError: local variable 'method' referenced before > assignment > > This however works fine. > > def fun1(method=None): > if not method: method = 'GET' > def fun2(): > print '%s: this is fun2' % method > return > fun2() > > fun1() > > Is there a simple way I can pass on the variables passed to the outer > function to the inner one without having to use or refer them in the > outer function? Why do you have this latter requirement? Will /method/ change in the outer scope before it is called in the inner scope? E.g.: def fun1(method=None): def fun2(): if not method: method = 'GET' print '%s: this is fun2' % method return method = 'POST' # Now its going to be 'POST' in fun2 fun2() To avoid this problem, you want something like this: def fun1(method=None): def fun2(method=method): if not method: method = 'GET' print '%s: this is fun2' % method return method = 'POST' # Now the preceding line has no effect on fun2 fun2() # Now method is explicitly 'POST' in fun2 fun2('POST') But a deeper question is: Why do you need to define fun2 with fun1 to begin with? def fun2(method=None): if not method: method = 'GET' print '%s: this is fun2' % method return def fun1(method=None): method = 'POST' # will be 'GET' fun2() # will be 'POST' fun2(method) Also, empty "return" statements are unnecessary if they are the last statement in a function. James From bj_666 at gmx.net Thu Aug 30 03:14:25 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Aug 2007 07:14:25 GMT Subject: We need PIGs :) References: Message-ID: <5jn92hFdmbcU2@mid.uni-berlin.de> On Thu, 30 Aug 2007 07:10:47 +0200, Martin Marcher wrote: > Does that sound like a good idea or would that be over formalization? Sounds like over engineering/formalization to me. You are aware of the Python Enhancement Proposals (PEPs)? Is something like the `Python Database API Specification v2.0`_ or `API for Block Encryption Algorithms v1.0`_ what you are looking for? .. _API for Block Encryption Algorithms v1.0: http://www.python.org/dev/peps/pep-0272/ .. _Python Database API Specification v2.0: http://www.python.org/dev/peps/pep-0249/ Ciao, Marc 'BlackJack' Rintsch From http Fri Aug 31 06:47:51 2007 From: http (Paul Rubin) Date: 31 Aug 2007 03:47:51 -0700 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> <1188537516.622167.115080@z24g2000prh.googlegroups.com> Message-ID: <7xir6wc754.fsf@ruckus.brouhaha.com> Ricardo Ar?oz writes: > In that case why don't we just 'certify to a higher level' the programs > and get done with this formal proofs? We should remember that the level > of security of a 'System' is the same as the level of security of it's > weakest component, so either we formally prove all those other very > important components (OS gets MUCH more use than the program (the > program uses it for almost every other action)) or get done with the > whole fuss. This url has some info on the topic of certification etc.: http://www.dwheeler.com/essays/high-assurance-floss.html From jeff.fw at gmail.com Wed Aug 29 00:07:40 2007 From: jeff.fw at gmail.com (Jeff) Date: Wed, 29 Aug 2007 04:07:40 -0000 Subject: Creating a multi-tier client/server application Message-ID: <1188360460.838635.186930@w3g2000hsg.googlegroups.com> Hello everyone. I've searched through the archives here, and it seems that questions similar to this one have come up in the past, but I was hoping that I could pick your Pythonic brains a bit. Here's a broad overview of what I need to do: cross-platform, client- side GUI apps that interact with a server backed by a database. I'd also like the possibility of having a web interface for small portions of the app. It will be a fairly complex system for managing personnel (and training, performance reviews, etc.) and payroll, and I will probably have about a year or more to write it. None of this is written yet--actually, it's not even to the point of specs yet, I'm just trying to learn the best way to do this *before* I get to the specs. I want to plan this application out as thoroughly as possible before writing any code, and I want to do it The Right Way(TM), hence I have (hopefully) convinced my manager (and clients) that Python is the way to go. I have a couple years of experience in Python, but it's mostly been web apps (which I am thoroughly sick of making, thanks to PHP) and simple CLI programs. Not sure if any of that information helps, but I'm tired, so please bear with me. The application definitely needs at least three tiers: client, server, and DB. I want as little logic in the client as possible (if not none), as there will be sensitive data in the DB. I also can't have the clients connect to the DB directly, as it will need to only accept connections on the local host. The client will probably be installed on 50-100 machines, and will be used by several hundred people (yes, they're sharing machines--the users will be computer lab consultants/ server operators/helpdesk employees, etc. and their supervisors), so authentication (using LDAP) and authorization (using groups I will define) will be very important. Also important will be automatic updates of the client, which I figure I'll do by comparing version numbers, then downloading an archive (egg, maybe?) of the latest (compiled? byte-?) code. I will probably make the GUI in wxPython, as that seems to be most flexible and nicely cross-platform choice--but I am open to suggestions. Not too worried about that one, though. For the database, I'll use Postgres, because I love Postgres. Probably not going to budge on that one unless anyone has any good reasons to. I'd also like to use SQLAlchemy (because it is so nice), but this is not a requirement (I can write SQL, but... SQLAlchemy is so nice.) I'd like to use an ORM mainly because it would facilitate code reuse for the (very simple) web interface, and other offshoot tools down the line. So, my real question (sorry for the all the exposition) is this: how to do the networking? I'd really like to have the client send a simple request to the server along the lines of "fetch this (or these) object(s)", or "update this value in this object", then let the server decide if the user actually is allowed to do so, and then make the change in the database. My first thought was XML-RPC, because I've used it before, and it is so nice and clean--but then I can't send objects, which is really rather crucial. Then I looked at Pyro, which seems awesome, but I'm confused as to how (if possible) I would use it with a DB. Would I have to figure out on the client what SQL query to send to get the right objects? That would kind of kill the separation of logic. And would it work at all with SQLAlchemy (or any ORM for that matter)? I looked at SOAP. It made me feel unclean. I looked at some CORBA, at which point my eyes glazed over (possibly not CORBA's fault, I will look at it again later). I checked out Twisted, but there are so vastly many parts to it, that I'm not sure where to even start. I'm not ruling out writing my own simple protocol, but it seems like I'd be reinventing a wheel that's already been reinvented countless times. So, all that said--any advice on how to do the networking? And on the auto-update? For that matter, any advice on anything I've mentioned (or haven't?) Please feel free to ask me to clarify anything, or tell me if I'm being an idiot about anything. Thanks, Jeff From deets at nospam.web.de Thu Aug 23 03:02:38 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 23 Aug 2007 09:02:38 +0200 Subject: porting vc++ project to python? In-Reply-To: <46cc611f$0$25500$ba620dc5@text.nova.planet.nl> References: <46cc611f$0$25500$ba620dc5@text.nova.planet.nl> Message-ID: <5j4potF3p8ngaU1@mid.uni-berlin.de> marco Starglider schrieb: > hi, > > i have a very large project in visual studio2005->visual c++ in windowsxp. > i'd like to port it, or my next project, over to python. > is this possible without rewriting all my code? > are there multiple options to do this? > my project is so large, that entirely rewriting it > is actually no option. > > regards, > > m > > ps i guess, it's an option to transform my current code into one or more > python extensions/modules, and then calling them from a python core > module? It is. I personally prefer SIP, which is a C++ wrapper generator used to wrap the Qt toolkit. But there are other options as well, e.g. SWIG and Boost::Python. Diez From gherzig at fmed.uba.ar Thu Aug 30 15:28:22 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Thu, 30 Aug 2007 16:28:22 -0300 Subject: pure python for sms Message-ID: <46D71A56.30602@fmed.uba.ar> Hi dudes. Im looking for a python implementation for sending sms to a cell phone. I was try using some free pages, but i want to use a python. Do i need a cellphone conected to my machine? Or can i send sms to some cell via some python library? Waiting for advice. Thanks! Gerardo From QJing.Li at gmail.com Fri Aug 17 13:07:51 2007 From: QJing.Li at gmail.com (math2life) Date: Fri, 17 Aug 2007 17:07:51 -0000 Subject: help to make program better In-Reply-To: <1187368051.235289.76520@w3g2000hsg.googlegroups.com> References: <1187368051.235289.76520@w3g2000hsg.googlegroups.com> Message-ID: <1187370471.220778.23380@i13g2000prf.googlegroups.com> On Aug 17, 9:27 am, yadin wrote: > hi! > Can any one tell me why is it that i can't see my second frame and why > is the value of freq not Appended in the First frame ...thanks > I know it is wx python but it has to do with passing variables.thanks > > import wx > > def create(parent): > return Frame1(parent) > > [wxID_FRAME1, wxID_FRAME1FREQ, wxID_FRAME1FREQDISP, > wxID_FRAME1STATICTEXT1, > ] = [wx.NewId() for _init_ctrls in range(4)] > > class Frame1(wx.Frame): > def _init_ctrls(self, prnt): > # generated method, don't edit > wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt, > pos=wx.Point(380, 179), size=wx.Size(241, 133), > style=wx.DEFAULT_FRAME_STYLE, title='Frame1') > self.SetClientSize(wx.Size(233, 99)) > > self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1, > label='frequency disp', name='staticText1', parent=self, > pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) > > self.freqdisp = wx.TextCtrl(id=wxID_FRAME1FREQDISP, > name='freqdisp', > parent=self, pos=wx.Point(104, 24), size=wx.Size(100, > 21), > style=0, value='') > > self.freq = wx.Button(id=wxID_FRAME1FREQ, label='get freq', > name='freq', > parent=self, pos=wx.Point(24, 56), size=wx.Size(184, > 23), > style=0) > self.freq.Bind(wx.EVT_BUTTON, self.OnButton1Button, > id=wxID_FRAME1FREQ) > > def __init__(self, parent): > self._init_ctrls(parent) > > def OnButton1Button(self, event): > > def create(parent): > return Frame2(parent) > [wxID_FRAME2, wxID_FRAME2FREQ, wxID_FRAME2FREQDISP, > wxID_FRAME2STATICTEXT1,] = [wx.NewId() for _init_ctrls in range(4)] > > class Frame2: ~~~~~~~~~~~~~~~should be class Frame2(wx.Frame): > def __init__(self): > # > wx.Frame.__init__(self, id=wxID_FRAME2, name='', > parent=prt, > pos=wx.Point(400, 179), size=wx.Size(300, 133), > style=wx.DEFAULT_FRAME_STYLE, title='Frame2') > self.SetClientSize(wx.Size(233, 99)) > > self.staticText1 = > wx.StaticText(id=wxID_FRAME2STATICTEXT1, > label='frequency goes here first', > name='staticText2', parent=self, > pos=wx.Point(24, 32), size=wx.Size(71, 13), > style=0) > > self.freqdisp2 = wx.TextCtrl(id=wxID_FRAME2FREQDISP, > name='freqdisp2', > parent=self, pos=wx.Point(104, 24), > size=wx.Size(100, 21), > style=0, value=' ') > > self.freq = wx.Button(id=wxID_FRAME2FREQ, label='get > freq', name='freq', > parent=self, pos=wx.Point(24, 56), > size=wx.Size(184, 23), > style=0) > self.freq.Bind(wx.EVT_BUTTON, self.OnButton2Button, > id=wxID_FRAME2FREQ) > > def __init__(self, parent): > self._init_ctrls(parent) > def OnButton2Button(self, event): > freqdisp.Append('this is it 24HZ!') > Show() ~~~~~~~~~~~~~~~~~~~~should be create(self).Show() > > if __name__ == '__main__': > app = wx.PySimpleApp() > frame = create(None) > frame.Show() > > app.MainLoop() Hi, I found two errors in your program. one is that class Frame2 must be inherited from wx.Frame, the other is Show() must belong a object. From lycka at carmen.se Wed Aug 1 05:26:19 2007 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 01 Aug 2007 11:26:19 +0200 Subject: Where do they tech Python officialy ? In-Reply-To: <1185274675.038893.71200@d55g2000hsg.googlegroups.com> References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> <1185265091.276958.239910@r34g2000hsd.googlegroups.com> <7x8x96fa3q.fsf@ruckus.brouhaha.com> <1185274675.038893.71200@d55g2000hsg.googlegroups.com> Message-ID: On July 23, NicolasG wrote: > I want to be a professional python programmer... > unfortunately sometimes to work as a programmer is really hard in this > world, every employee requires professional experience and you can't > really start as a beginner.. On July 24, NicolasG wrote: > Python is what I like, I would love to be more creative with this > language and be able to produce things that I can't right now.. > Why not try to find a work that you would like ? I don't want to work > as a programmer to became one because I'm already a programmer, I just > want to work as a programmer .. I'm not sure I understand what you mean by "I'm already a programmer" if you can't get jobs because you're a beginner. That sounds a bit like "I'm a surgeon, except that I haven't done any surgery just yet." I also don't understand the concept on choosing a university depending on whether they use a particular language in their courses. I think it's a good idea with a good academic education, but whether Python is part of that is really a minor issue. The most important part of education for people who are going to work as programmers is advanced mathematics! That's what will teach you logic and systematic problem solving. Learning Python is a very small and easy part in learning to develop software in a professional way. There are no silver bullets. You won't find a language or a university course that will "fix" things for you. The world (and your job) is full of problems waiting to be solved. Solve them with Python, use your spare time if you're ambitious and don't get the opportunity to use working hours. Use the internet to find ideas and libraries etc. Doing this will make work more fun, if you are talented enough it will make you much more productive, you should be appreciated for the improvements you achieve, and you will build up a portfolio of software and solutions that you can show a prospective employer. If I'm hiring a consultant for a few weeks, prior Python experience might be an issue, but if I employ someone, I don't care whether they already know Python. I expect them to know a few languages well. I assert that they are capable of applying a programming language to solve problems swiftly and intelligently, and I'm pretty sure they pick up Python quickly. From horpner at yahoo.com Wed Aug 1 12:46:53 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 01 Aug 2007 16:46:53 GMT Subject: Awkward format string References: <1185984697.605529.157110@g12g2000prg.googlegroups.com> <1185986578.527619.314310@e9g2000prf.googlegroups.com> Message-ID: <1O2si.37265$G23.12306@newsreading01.news.tds.net> On 2007-08-01, beginner wrote: > print >>f, "%s\t%s\t%d\t%f\t%f\t%f\t%d" % > (x.field1..strftime("%Y-%m- %d"), > x.field2..strftime("%Y-%m-%d"), x.field3, x.field4, x.field5, > x.field.6, x.field7) > > This is also tedious and error-prone. Providing a suitable .str or .__repr__ method for your class may make that problem disappear. -- Neil Cerutti From ptmcg at austin.rr.com Thu Aug 30 09:54:47 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 30 Aug 2007 06:54:47 -0700 Subject: Important Research Project In-Reply-To: <13ddcvm1bsu3s94@corp.supernews.com> References: <13ddcvm1bsu3s94@corp.supernews.com> Message-ID: <1188482087.098419.56490@k79g2000hse.googlegroups.com> On Aug 30, 8:12 am, "E.D.G." wrote: > Important Research Project (Related to computer programming) > > Posted by E.D.G. on August 30, 2007 edgrs... at ix.netcom.com > > This report is being posted to a number of Internet Newsgroups Always the hallmark of a considerate poster. > to see if > there are any experienced computer programmers who would like to provide > some assistance with an effort to develop a Perl language computer program. > > Interested parties can try contacting me by e-mail or by posting a > response note to the comp.lang.perl.misc newsgroup. They would need to > download a recent (free) MSI copy of Perl from the ActiveState Web site and > get it running on a Windows XP or Vista system. > > http://www.activestate.com > This is a little backwards, one usually presents their research topic *first* and their contact info *last*. The reason? SO PEOPLE KNOW WHAT THE @#$(&#!@ YOU ARE WORKING ON! Ok, I'll bite, keep reading... > I am presently using Perl 5.8.8 Whoop-de-doo for you. > but plan to upgrade to the latest > version as soon as possible. People can use Windows 98 if that is the only > operating system available. Perl also runs on other operating systems. But > at this time I specifically need help with the Windows version. > I suspect Perl is largely the same Perl on all those platforms. Win 98? Is this a zombie spam from the turn of the century? > The goal is to have a single Perl program (or modules) perform functions > that have been done by a sizeable collection of other language programs in > the past. > Doing what!? Grrr..., keep reading, there's gotta be a punch line... > Help is presently needed with learning how to get Perl to generate > charts and also produce standalone .exe copies of itself. The plan is to > then make those .exe copies available to other scientific researchers around > the world for free use along with free use updates when they become > available. If other researchers wish to get Perl running on their own > computers then they will probably also be given the source code for the > original program for free use so that they can do their own development > work. > Ohmigod, is Google broken? Or has Perl gone this long and this far without support for creating charts and graphs? Sounds like about 10 minutes of research. > Perl was originally chosen because it is quite versatile, is a free > download, and is supported both by ActiveState and quite a few independent > programmers. So other researchers could get their own versions running > without having to worry about viruses or cost. > (Why is this posted on all these non-Perl newsgroups, then? I've *seen* Perl already, and never want to again!) > So far the work is fairly advanced. The effort has been underway for at > least a decade. ... and we are just getting around to plotting some data. > The core data generation program was formally copyrighted > several years ago. Red flag #37 - "formally copyrighted", wooo-ooooh > My present version of Perl will send data to Windows as > if it were being manually typed into the keyboard (important for controlling > other programs). And it can directed to respond to most keystrokes even > when another program is the active one. Unfortunately, Windows also > presently responds to those keystrokes. And that complicates things a bit. > ... and has for the past decade, and I still haven't figured it out. > Not being a professional computer programmer I have been finding it > difficult to get new features such as a chart generating ability merged with > and running with Perl. And the entire research project is now being slowed > as a result. One of my colleagues has done an extensive amount of work with > Basic. And I even offered to pay him to help with the Perl development > effort. But after he downloaded a copy of Perl and examined it he decided > that this would involve too much effort. I have to agree with him. > Maybe that up-front language choice could stand a review... > Once it is possible to create charts and .exe versions the plan is for > researchers around the world to develop Perl modules for generating a > variety of data related to sun, moon, planet, ocean tide crest and trough, > and Solid Earth Tide locations. Most of those data can already be generated > with other programs. Some of the data are not yet available anywhere as far > as I am aware. If the effort is unusually successful the Perl program (or > modules) might eventually be converted to CGI programs that will run at one > or more Internet Web sites. AHHH! The "research", I almost forgot! Why is it left to the end of the message? And do we still know what the @#(*&$ this "variety of data" is for? I'm going to take a wild guess here - earthquake prediction? perpetual motion? picking guaranteed-to-win lottery numbers? After a pitch like that, who could not be tempted at the prospect of "generating a variety of data related to sun, moon, etc. etc."? Sign me up - NOT! GTFA, -- Paul From wolf_tracks at invalid.com Sat Aug 18 11:42:52 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sat, 18 Aug 2007 15:42:52 GMT Subject: Python and Tkinter Programming--Expensive! In-Reply-To: References: Message-ID: <0sExi.33897$2v1.19719@newssvr14.news.prodigy.net> Thanks. I'll test the waters on Amazon. Nick Craig-Wood wrote: > W. Watson wrote: >> Why is the book in Subject (author is Grayson) so expensive? $100 on Amazon >> and $195 on ABE. Aren't there alternatives? > > There is an excellent section (266 pages) on TKinter in "Programming > Python" by Mark Lutz. I've got the 2nd edition. > > Lutz concentrates on TK programming using classes, making re-usable > components which I found really helpful compared to the ad-hoc way I'd > seen TK presented previously. > -- Wayne Watson (Nevada City, CA) Web Page: From arnau at ehas.org Wed Aug 29 15:59:30 2007 From: arnau at ehas.org (Arnau Sanchez) Date: Wed, 29 Aug 2007 21:59:30 +0200 Subject: sys.argv is munging my command line options In-Reply-To: <1188414714.645724.63330@i38g2000prf.googlegroups.com> References: <1188414714.645724.63330@i38g2000prf.googlegroups.com> Message-ID: <46D5D022.5010606@ehas.org> Chris Allen escribi?: > action key=value key=value... > > Where action is a required string (ie. 'backup', 'init', 'restore', > etc) and the program can accept one or more key value pairs. I know > this syntax isn't standard, but I think it works great for my program > as each key can override an identically named field in a configuration > file, that way the user doesn't have to have two different syntaxes to > do the same thing. I could do this with --key value It's ok for a personal script, but if you expect other people to use it, you should consider the "Rule of Least Surprise" and follow the standard. Anyway, using getopt or optparse, it would be "--key=value", or perhaps "-o key=value / --option=key=value" > But I'm running into a problem with this which is that sys.argv splits > my key=value options. I need to know the option associations, and > there's no way to know this by inspecting sys.argv. Can I get access > to the command line string as python saw it before it split it into > sys.argv or is there another way? I can't see the problem, sys.argv[1:] gives you the list of ordered key/value pairs... give an example of what you want and what you get. From mcl.office at googlemail.com Thu Aug 30 07:13:51 2007 From: mcl.office at googlemail.com (mcl) Date: Thu, 30 Aug 2007 04:13:51 -0700 Subject: Unzip: Memory Error In-Reply-To: References: <1188413939.834662.193180@y42g2000hsy.googlegroups.com> Message-ID: <1188472431.290871.103720@o80g2000hse.googlegroups.com> On 29 Aug, 21:18, David Bolen wrote: > mcl writes: > > I am trying to unzip an 18mb zip containing just a single 200mb file > > and I get a Memory Error. When I run the code on a smaller file 1mb > > zip, 11mb file, it works fine. > (...) > > def unzip_file_into_dir(file, dir): > > #os.mkdir(dir, 0777) > > zfobj = zipfile.ZipFile(file) > > for name in zfobj.namelist(): > > if name.endswith('/'): > > os.mkdir(os.path.join(dir, name)) > > else: > > outfile = open(os.path.join(dir, name), 'wb') > > outfile.write(zfobj.read(name)) > > outfile.close() > > The "zfobj.read(name)" call is reading the entire file out of the zip > into a string in memory. It sounds like it's exceeding the resources > you have available (whether overall or because the Apache runtime > environment has stricter limits). > > You may want to peek at a recent message from me in the "Unable to > read large files from zip" thread, as the suggestion there may also be > suitable for your purposes. > > http://groups.google.com/group/comp.lang.python/msg/de04105c170fc805?... > -- David David, Thank you. I read your post and I basically understood the concept, butI could not get my head around the code, I need to write for my solution. (Newbie and a bit long in the tooth) To solve my problem, I think my best approach would be to read my zipped file / files from the zip archive when I need them. Max three users, occasional use. So no big overloading of host's server. pseudo code zfhdl = zopen(zip,filename) # Open File in Zip Archive for Reading while True: ln = zfhdl.readline() # Get nextline of file if not ln: # if EOF file break dealwithline(ln) # do whatever is necessary with file zfhdl.close That is probably over simplified, and probably wrong but you may get the idea of what I am trying to achieve. Richard From __peter__ at web.de Wed Aug 22 12:19:27 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Aug 2007 18:19:27 +0200 Subject: instance method questions References: Message-ID: Danny wrote: > I have created an instance method for an object using new.instancemethod. > It works great. Now the questions are: > > 1) how do I dynamically inspect an object to determine if it has an > instance method? (there is a class method with the same name) Why would you want to do that? Here is a way that relies on an implementation detail of current CPython: >>> class Foo(object): ... def foo(self): pass ... def __init__(self): ... import new ... def bar(self): pass ... self.foo = new.instancemethod(bar, self) ... >>> x = Foo() >>> x.foo is x.foo True >>> del x.foo >>> x.foo is x.foo False This alternative is a little less subtle: >>> y = Foo() >>> "foo" in y.__dict__ True >>> del y.foo >>> "foo" in y.__dict__ False Peter From attn.steven.kuo at gmail.com Thu Aug 16 15:58:49 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 16 Aug 2007 19:58:49 -0000 Subject: sub-classing the types in the builtin module datetime In-Reply-To: References: Message-ID: <1187294329.082872.230800@l22g2000prc.googlegroups.com> On Aug 15, 5:54 pm, "Colin J. Williams" wrote: > I posted this about 5 hours ago, but it seems to have gone astray. (snipped) > > > >> I wish to sub-class (if that's the right word) datetime and to use a > >> different signature for the constructor. > >> > >> The second part has gone smoothly, but it is difficult to access the > >> type's methods from the sub-class instance. > >> > >> I'm beginning to wonder whether it might might be simpler to write my > >> own Date class. > >> > >> Does anyone have any comments please? > >> > >> Colin W. (snipped) > Yes, I should have posted an example, but I thought that others might > have experienced the problem. > > It is illustrated at the bottom of this script: > > # subClassing.py > > import datetime > import new > import sys > import types > > class Date(datetime.datetime): > ''' Date(s) -> a date object.__class__ > where s is an 8 digit string''' > > def __new__(cls, YYmmdd): > ''' YYmmdd is a string, in the form yyyymmdd i.e. 8 digits. > or a 3-tuple of integers in the form (y, m, d) > or a 6-tuple of integers in the form (y, m, d, h, m, > s) ''' (snipped) > > a= datetime.datetime(2007, 7, 31) > d= Date('20070731') > tm= datetime.time(1, 2) > try: > print a.today() > # print d.today() # grief > print a.now() > # print d.now() # grief > print a.combine(a, tm) # OK, but why not a.combine(tm)? > # e= d.combine(d, tm) # grief > print a.utcnow() > # print d.utcnow() # grief > print a.ctime() > print d.ctime() > except: > print 'Grief' > print sys.exc_info() > > Colin W. This problem arises when you change the function signature of __new__. I'm a little unclear as to why but it seems for the classmethods (thosed marked with the METH_CLASS flag in the C source code), you need to arrange to bypass the normal method resolution (I used a metaclass to do this): import datetime class Date(datetime.datetime): pass class FixClassMethods(type): def __init__(cls, classname, bases, classdict): # add strptime if using Python 2.5 flagged_as_meth_class = ('today', 'now', 'fromtimestamp', 'fromordinal', 'now', 'utcnow', 'utcfromtimestamp', 'combine') for meth in flagged_as_meth_class: setattr(cls, meth, getattr(datetime.datetime, meth)) class DateChangesNewSignature(datetime.datetime): @staticmethod def str2ymd(strval): yyyy, mm, dd = (int(substr) for substr in (strval[:4], strval[4:6], strval[6:])) return yyyy, mm, dd def __new__(cls, strval): yyyy, mm, dd = DateChangesNewSignature.str2ymd(strval) return super(DateChangesNewSignature,cls).__new__(cls, yyyy, mm, dd) def __init__(self, strval): yyyy, mm, dd = DateChangesNewSignature.str2ymd(strval) super(DateChangesNewSignature, self).__init__(yyyy, mm, dd) class DLast(DateChangesNewSignature): __metaclass__ = FixClassMethods f = Date(2007,07,07) print f print f.today() f2 = DateChangesNewSignature("20070707") print f2 try: print f2.today() except TypeError, e: print str(e) print "Uh?" f3 = DLast("20070707") print f3 print f3.today() I get: 2007-07-07 00:00:00 2007-08-16 12:57:41.480679 2007-07-07 00:00:00 __new__() takes exactly 2 arguments (9 given) Uh? 2007-07-07 00:00:00 2007-08-16 12:57:41.483104 -- Hope this helps, Steven From jmtulloss at gmail.com Thu Aug 9 12:51:47 2007 From: jmtulloss at gmail.com (Justin T.) Date: Thu, 09 Aug 2007 16:51:47 -0000 Subject: Stackless Integration In-Reply-To: References: <1186650027.043779.276520@i38g2000prf.googlegroups.com> Message-ID: <1186678307.205621.221100@x40g2000prg.googlegroups.com> On Aug 9, 8:57 am, "Terry Reedy" wrote: > First, which 'stackless'? The original continuation-stackless (of about 7 > years ago)? Or the more current tasklet-stackless (which I think is much > younger than that)? > The current iteration. I can certianly understand Guido's distaste for continuations. > > overcome. It is just not part of the stdlib. And I wish it were! It wouldn't be such a pain to get to my developers then. > And as far as I know or > could find in the PEP index, C. Tismer has never submitted a PEP asking > that it be made so. Doing so would mean a loss of control, so there is a > downside as well as the obvious upside of distribution. That's true. Though, hopefully, the powers that be would allow him to maintain it while it's in the stdlib. Maybe we should file a PEP for him... :) Justin From anders.u.persson at gmail.com Fri Aug 24 12:53:38 2007 From: anders.u.persson at gmail.com (anders) Date: Fri, 24 Aug 2007 09:53:38 -0700 Subject: GUI and distrubution Message-ID: <1187974418.175783.50860@i38g2000prf.googlegroups.com> I have looked att Python on www.showmedo.com And after this i start testing writing som program i Python. But... So how is the preferably way to distribute software written i Python i am NOT into hiding stuff, more a easy way of giving eg friends a copy of the program without having them installtion a lott och other stuff. My next question is witch is the best GUI to use, also consider the delivery question above. // Anders From zentraders at gmail.com Fri Aug 3 14:02:06 2007 From: zentraders at gmail.com (Zentrader) Date: Fri, 03 Aug 2007 18:02:06 -0000 Subject: i am new to python-Please somebody help In-Reply-To: References: <1186047103.673871.150460@z24g2000prh.googlegroups.com> <46b249a4$0$31219$426a74cc@news.free.fr> Message-ID: <1186164126.342012.214020@i13g2000prf.googlegroups.com> BTW - on the subject of polite discussions, how about this one as an example of opinions politely expressed. Oh, and does anyone know how to use zip in Python. Yes+1. From sylviajam at gmail.com Sat Aug 4 15:21:22 2007 From: sylviajam at gmail.com (S Jam) Date: Sat, 04 Aug 2007 12:21:22 -0700 Subject: =?utf-8?B?4peZ4peZ4peZIFR1cm4gWW91ciBQQyBJbnRvIFNhdGVsbGl0ZSBUViAmIFdhdGNoIGl0IEZSRUUgb2YgQ29zdOKXhOKXmeKXmeKXmQ==?= Message-ID: <1186255282.905274.288320@x35g2000prf.googlegroups.com> Watch Satellite TV On Your Computer Without Paying Monthly Fees... FOR FREE? Watch all your favorite shows on your Computer from anywhere in the World! Save 1000's of $$$ over many years on cable and satellite bills. INSTANT DOWNLOAD Plus Free Unlimited Downloads Movies, MP3s Music, etc !!! More Details: http://tvonpc.freeweb7.com From hg at nospam.org Sun Aug 26 19:00:09 2007 From: hg at nospam.org (hg) Date: Sun, 26 Aug 2007 23:00:09 GMT Subject: ANN: SCF released to GPL Message-ID: Dear all, I am releasing much of my work including SCF (Cross platform Smart Card library & Tools written in Python) to the GPL license. If interested, go to http://www.SnakeCard.com/Source.html I am moving the doc to doxygen and cleaning up the code, so what you'll see there will change in the course of the next few weeks - basically can only get meaningful info on the classes hierarchy at this stage. I am looking for a free subversion server resource to put the code ... if you know of any. Some of the work there will be windows-only related (GINA, activeX components ... and not coded in Python) and the applets JavaCard and BasicCard ... I'm releasing these during the next few days. Regards, hg From roy at panix.com Fri Aug 31 01:15:04 2007 From: roy at panix.com (Roy Smith) Date: Fri, 31 Aug 2007 01:15:04 -0400 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> <1188534061.243009.89640@m37g2000prh.googlegroups.com> Message-ID: Carl Banks wrote: > Python really isn't suitable for in-flight controls for various > reasons, and mission critical concerns is a minor one (systems with > less underlying complexity tend to have fewer failure modes). But > mostly it's raw throughput: Python is just too slow. Flight control > computers have to be powerful enough make a ton of mathematical > calculations in a matter of milliseconds, and under strict weight and > power constraints. The cost of running 100 times slower than optimal > is just too high. I'm not convinced that's true for all avionics uses. Certainly, if you're doing the fly-by-wire stability control system for a dynamically unstable airframe, you need a lot of compute power and guaranteed real-time response (recovery from a VMC rollover is no time for garbage collection). But, not everything in an airplane is like that. Take something relatively complicated like a GPS. The basic receiver is pretty compute intensive, but that's likely to be a dedicated chip. Most of the functionality in the box, however, requires a lot less horsepower. You need to handle user input (i.e. keep up a scan on maybe 20 keys), and update a low-res display (320 x 240 x 8 bit color is typical) with text or cartoon graphics. There are certain real-time calculations which need to be done, such as time, distance, and bearing to the next waypoint, but these are typically updated a few times a second. Like most things that use Python (or TCL, or Ruby, or ...), I would expect that most of the low-level stuff would be done in something like C and Python would be used for the glue code and things where there's no time pressure. From carairconditionersmail at gmail.com Sun Aug 19 13:42:07 2007 From: carairconditionersmail at gmail.com (carairconditionersmail at gmail.com) Date: Sun, 19 Aug 2007 17:42:07 -0000 Subject: A/C Systems! In-Reply-To: <1187545194.099278.217330@w3g2000hsg.googlegroups.com> References: <1187545194.099278.217330@w3g2000hsg.googlegroups.com> Message-ID: <1187545327.963222.223220@w3g2000hsg.googlegroups.com> On Aug 19, 7:39 pm, Cartun... at gmail.com wrote: > Everything you need to know about car air conditioners... > > http://car-air-conditioning.blogspot.com/ Great website man, I found everything I need From theshadowx at gmail.com Thu Aug 23 13:44:45 2007 From: theshadowx at gmail.com (TheShadow) Date: Thu, 23 Aug 2007 17:44:45 -0000 Subject: Question about embedding python in C++ Message-ID: <1187891085.147246.19380@i38g2000prf.googlegroups.com> When extending python in c/c++ after you register a module is there a way in c/c++ to check if they were correctly registered? Cause I'm having the problem where when I execute the the python script it finds the module but none of the functions. From deets at nospam.web.de Fri Aug 3 07:09:03 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 03 Aug 2007 13:09:03 +0200 Subject: (no) fast boolean evaluation ? missing NOT In-Reply-To: References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> <1186096979.397596.36640@e16g2000pri.googlegroups.com> Message-ID: <5hggmmF3k8fdoU1@mid.uni-berlin.de> Stef Mientki schrieb: > John Machin wrote: >> On Aug 3, 8:55 am, Ian Clark wrote: >>> Stef Mientki wrote: >>>> hello, >>>> I discovered that boolean evaluation in Python is done "fast" >>>> (as soon as the condition is ok, the rest of the expression is >>>> ignored). >>>> Is this standard behavior or is there a compiler switch to turn it >>>> on/off ? >>>> thanks, >>>> Stef Mientki >>> It's called short circuit evaluation and as far as I know it's standard >>> in most all languages. This only occurs if a conditional evaluates to >>> True and the only other operators that still need to be evaluated are >>> 'or's or the condition evaluates to False and all the other operators >>> are 'and's. The reason is those other operators will never change the >>> outcome: True or'd with any number of False's will still be True and >>> False and'ed to any number of Trues will still be False. >>> >>> My question would be why would you *not* want this? >>> >>> >> >> Why? Perhaps under some compound condition like this: >> >> (you_are_confused and/or >> function_returns_bool_but_has__side_effects()) >> > > Thanks guys, > Yes this is exactly what's going wrong ... > > Sorry, my question missed the essential "NOT", > here is an example, that behaves different in Delphi, > (so I guess Delphi is not a real language ;-) > > > def Some_Function (const): > print 'Ive been here', const > return True > > A = True > > if A and Some_Function (4 ): > print 'I knew it was True' > else: > print 'I''ll never print this' > > > > Ive been here 4 > I knew it was True > > I was expected that the function would not be called, > because A is True. > > And I agree with Laurent that it should be better to write a clean code, > so it doesn't matter whether you write in Python or in Delphi. > > Gabriel: you pointed me to this page: > The exact behavior is defined in the Language Reference > > > > or_test ::= and_test | or_test "or" and_test > > Can you imagine, while I'm not a programmer, just a human, > that I don't understand one bit of this line. > > So now I'm left with just one question: > for bitwise operations I should use &, |, ^ > for boolean operations I should use and, or, xor > but after doing some test I find strange effects: > >>> A = 4 > >>> B = 5 > >>> A and B > 5 > >>> A & B > 4 > >>> A or B > 4 > >>> A | B > 5 > > So if I use the bitwise operation on integers, > "and" changes into (bitwise) "or" and vise versa. No!!! Don't think that! Choose different numbers, and you will see that. The semantics for the and/or operators are spelled out like this (extra-verbose): def and(a, b): if bool(a) == True: if bool(b) == True return b # because it holds True == bool(b) return a # because it holds Fals == bool(a) def or(a, b): if bool(a) == True: return a return b This could be considered unfortunate because it relies on the implicit boolean nature of certain values like "", 0, 1, {} and so forth - but it's the way it is. However, this has _nothing_ to do with the bitwise operations! The work on the bits of integers, and because 5 and 4 are bitwise 0b101 and 0x100, the 5 & 4 -> 4 == 0b100 and 5 | 4 -> 5 == 0x101 That's all! If you need non-circuiting and/or, write functions and and or: def and_(a, b): return a and b def or_(a, b): return a or b That will ensure argument evaluation. Diez From bj_666 at gmx.net Wed Aug 1 01:55:35 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Aug 2007 05:55:35 GMT Subject: How does xmlrpc work ? References: <1185946334.436503.326920@x40g2000prg.googlegroups.com> Message-ID: <5halimF3inuf2U1@mid.uni-berlin.de> On Wed, 01 Aug 2007 05:32:14 +0000, hide1713 at gmail.com wrote: > I am working on a system which used XMLRPC to communicate between > hundreds of computer. One administrative computer keeps hundreds of > xmlrpc instance of other computers. I want to know if evey instance > use a single connection and keep it alive forever OR create a new > connection when a method is called and end it after the call is > finished? Every XMLRPC call uses its own HTTP connection that is closed after the call is finished. Ciao, Marc 'BlackJack' Rintsch From michael at jedimindworks.com Thu Aug 9 08:05:31 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 9 Aug 2007 05:05:31 -0700 Subject: Stackless Integration In-Reply-To: <20070809114832.4947.1833247582.divmod.quotient.20482@ohm> References: <20070809114832.4947.1833247582.divmod.quotient.20482@ohm> Message-ID: <81C07501-369D-4209-9A5F-34B446EDB8D3@jedimindworks.com> On Aug 9, 2007, at 4:48 AM, Jean-Paul Calderone wrote: > On Thu, 09 Aug 2007 09:00:27 -0000, "Justin T." > wrote: >> Hi, >> >> I've been looking at stackless python a little bit, and it's awesome. >> My question is, why hasn't it been integrated into the upstream >> python >> tree? Does it cause problems with the current C-extensions? It seems >> like if something is fully compatible and better, then it would be >> adopted. However, it hasn't been in what appears to be 7 years of >> existence, so I assume there's a reason. > > It's not Pythonic. Can you be more specific? It's a good question that I had thought about asking... --- Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. --Brian W. Kernighan From stefan.behnel-n05pAM at web.de Fri Aug 3 11:50:41 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 03 Aug 2007 17:50:41 +0200 Subject: Replacing _xmlplus.dom.minidom with xml.dom.minidom In-Reply-To: References: <1186148352.647143.68890@l70g2000hse.googlegroups.com> Message-ID: <46B34ED1.60402@web.de> Robert Rawlins - Think Blue wrote: > Just as a heads up, minidom is pretty inefficient and difficult to work with > too. > > On someone else's advice I switched over to ElementTree and have been really > pleased with the results, its much simpler to work with and more efficient > too. /and/ lxml.etree is compatible to ElementTree, so once you have written your code for ElementTree, you can switch to lxml.etree if ever you need things like XPath, XSLT or validation. However, as I understand the OP, the question deals with old code, so porting it to ET (i.e. reimplementing it) might not be that easy... Stefan From http Sat Aug 11 01:06:10 2007 From: http (Paul Rubin) Date: 10 Aug 2007 22:06:10 -0700 Subject: The Future of Python Threading References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <1i2njyp.1o6yslqe7ff47N%luc@honk-honk.com> <1186782710.600889.245930@j4g2000prf.googlegroups.com> <1186802188.653072.236260@x40g2000prg.googlegroups.com> <1186807396.988368.201400@b79g2000hse.googlegroups.com> Message-ID: <7xk5s2wth9.fsf@ruckus.brouhaha.com> Seun Osewa writes: > What is it about Python that makes a thread-safe CPython version much > slower?... > I'm thinking it might be the reference counting approach to memory > management... Yes. In the implementation that was benchmarked, if I understand correctly, every refcount had its own lock, that was acquired and released every time the refcount was modified. From twisted0n3 at gmail.com Sun Aug 19 23:08:35 2007 From: twisted0n3 at gmail.com (Twisted) Date: Mon, 20 Aug 2007 03:08:35 -0000 Subject: A/C Systems! In-Reply-To: <1187554376.345506.82660@i38g2000prf.googlegroups.com> References: <1187545194.099278.217330@w3g2000hsg.googlegroups.com> <1187545327.963222.223220@w3g2000hsg.googlegroups.com> <1187554376.345506.82660@i38g2000prf.googlegroups.com> Message-ID: <1187579315.469495.175990@m37g2000prh.googlegroups.com> On Aug 19, 4:12 pm, Daniel Pitts wrote: > Don't you know that targeted advertising has far better return? Only when each impression is fairly expensive to cause. Unfortunately, spam (whether usenet, guestbook, blog comment, email, or whatever) is very cheap per impression, so the best strategy is indeed to just jizz enormous amounts of it indiscriminately into any socket that will accept the insertion of your network packets. It's the same problem as causes the battle of the sexes; expensive eggs vs. cheap sperm. :P From grante at visi.com Thu Aug 23 16:25:18 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 23 Aug 2007 20:25:18 -0000 Subject: Putting #'s and variables together in 1 variable References: Message-ID: <13crr9emd038k1a@corp.supernews.com> On 2007-08-23, Jay Loden wrote: > 2) Since all you're doing is adding a bunch of numeric values to each other > to build the string, why wouldn't you just create a random number between > 0 -> 99999 and use that? Since the OP calls randint 5 times, his answer is 5 times more random! -- Grant Edwards grante Yow! Everybody gets free at BORSCHT! visi.com From alexandre.badez at gmail.com Wed Aug 29 09:39:27 2007 From: alexandre.badez at gmail.com (Alex) Date: Wed, 29 Aug 2007 13:39:27 -0000 Subject: What's the difference ? Message-ID: <1188394767.333396.129020@r29g2000hsg.googlegroups.com> Hye, I was just wondering what is the difference between >> if my_key in mydict: >> ... and >> if mydict.has_keys(my_key): >> ... I've search a bit in the python documentation, and the only things I found was that they are "equivalent". But in this (quiet old) sample ( "http://aspn.activestate.com/ASPN/ Cookbook/Python/Recipe/59875" ), there is difference between the two notation. Thanks in advance From samfeltus at gmail.com Thu Aug 2 23:18:24 2007 From: samfeltus at gmail.com (SamFeltus) Date: Fri, 03 Aug 2007 03:18:24 -0000 Subject: ANN: SonomaSunshine for Django v0.01 Message-ID: <1186111104.690781.155910@b79g2000hse.googlegroups.com> Presented for your amusement, with source code for the first time!!! LOL The Redneck Riviera's Best Python Powered Folk Art Server... SonomaSunshine v0.01 for Django Django application for creating/editing Shiny/Happy Flash movies. http://samfeltus.com/django/hey_yall.html From nospam at invalid.com Sun Aug 19 00:37:33 2007 From: nospam at invalid.com (Jack) Date: Sat, 18 Aug 2007 21:37:33 -0700 Subject: Parser Generator? References: Message-ID: <_6mdnZxbdNKTVFrbnZ2dnUVZ_tqtnZ2d@comcast.com> Thanks for all the replies! SPARK looks promising. Its doc doesn't say if it handles unicode (CJK in particular) encoding though. Yapps also looks powerful: http://theory.stanford.edu/~amitp/yapps/ There's also PyGgy http://lava.net/~newsham/pyggy/ I may also give Antlr a try. If anyone has experiences using any of the parser generators with CJK languages, I'd be very interested in hearing that. Jack "Jack" wrote in message news:abKdnVoQMu2o7FrbnZ2dnUVZ_gqdnZ2d at comcast.com... > Hi all, I need to do syntax parsing of simple naturual languages, > for example, "weather of London" or "what is the time", simple > things like these, with Unicode support in the syntax. > > In Java, there are JavaCC, Antlr, etc. I wonder what people use > in Python? Antlr also has Python support but I'm not sure how good > it is. Comments/hints are welcome. > From irmen.NOSPAM at xs4all.nl Mon Aug 13 19:15:34 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 14 Aug 2007 01:15:34 +0200 Subject: ANN: Compyler 0.1 In-Reply-To: <1187020875.575423.58000@o61g2000hsh.googlegroups.com> References: <46bf2ea3$0$240$e4fe514c@news.xs4all.nl> <1187020875.575423.58000@o61g2000hsh.googlegroups.com> Message-ID: <46c0e61f$0$241$e4fe514c@news.xs4all.nl> Thanks Grant for the very informative response. -irmen From dwahler at gmail.com Tue Aug 7 21:35:54 2007 From: dwahler at gmail.com (David Wahler) Date: Tue, 7 Aug 2007 20:35:54 -0500 Subject: Something in the function tutorial confused me. In-Reply-To: <46B8626A.2070303@bigfoot.com> References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <1186424693.529497.217040@w3g2000hsg.googlegroups.com> <46B8626A.2070303@bigfoot.com> Message-ID: On 8/7/07, Ricardo Ar?oz wrote: > Lee Fleming wrote: > > Thanks for all the help, everyone. I guess I was confused with default > > arguments that were mutable and immutable. I will continue to look > > over these posts until I understand what is happening. > > > > I cannot believe the number of helpful responses I got! > > > > Apparently he didn't understand. > Neither did I. > > Either (i)y's initial value (None or []) is saved somewhere to be > retrieved every time the function is called without 2nd argument, or > (ii) y keeps the value it has when last exiting the function (if there > is a third option, please mention it). > It's option (i). > (i) (a) whenever the function is called without 2nd argument the value > None is retrieved and assigned to y, thus causing [] to be assigned to y > by the 'if' statement. Yep. > (i) (b) But then if it is "def f(x, y = [])" the list [] should be ALSO > saved somewhere and when the function is called without 2nd argument it > should be retrieved and assigned to y, thus y would always be [] when > you enter the function without 2nd arg. No, when the def statement is executed, the expression [] is evaluated, and the result of this evaluation is an empty list. It's a reference to this list that is saved, not the expression itself. All invocations of the function that use the default argument refer to the same list, so if it gets modified the modifications persist. -- David From damondolby at googlemail.com Tue Aug 14 12:04:12 2007 From: damondolby at googlemail.com (towers) Date: Tue, 14 Aug 2007 09:04:12 -0700 Subject: module: zipfile.writestr - line endings issue Message-ID: <1187107452.905165.45700@l70g2000hse.googlegroups.com> Hi I'm probably doing something stupid but I've run into a problem whereby I'm trying to add a csv file to a zip archive - see example code below. The csv just has several rows with carriage return line feeds (CRLF). However after adding it to an archive and then decompressing the line endings have been converted to just line feeds (LF). Does anyone know if this is a bug or am I just doing something wrong? Many Thanks, Damon **************************************************************************** import zipfile zipFile = zipfile.ZipFile('LocalZipFile.zip', 'a', zipfile.ZIP_DEFLATED) dfile = open('LocalCSVFile.csv', 'r') zipFile.writestr('test.csv',dfile.read()) dfile.close() zipFile.close() **************************************************************************** From arunmail at gmail.com Thu Aug 2 15:54:52 2007 From: arunmail at gmail.com (lazy) Date: Thu, 02 Aug 2007 19:54:52 -0000 Subject: Berkely Db. How to iterate over large number of keys "quickly" In-Reply-To: <1186083838.318952.254370@q3g2000prf.googlegroups.com> References: <1186083838.318952.254370@q3g2000prf.googlegroups.com> Message-ID: <1186084492.982045.278500@x40g2000prg.googlegroups.com> Sorry, Just a small correction, > a way I can tell Python to not load allkeys, but try to access it as > the loop progresses(like in a linked list). I could find any accessor > methonds on bsddb to this with my initial search. I meant, "I couldn't find any accessor methonds on bsddb to do this(i.e accesing like in a linked list) with my initial search" > I am guessing BTree might be a good choice here, but since while the > Dbs were written it was opened using hashopen, Im not able to use > btopen when I want to iterate over the db. From david at asdf.asdf Fri Aug 24 05:07:48 2007 From: david at asdf.asdf (bambam) Date: Fri, 24 Aug 2007 19:07:48 +1000 Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com><1187898049.734696.9500@l22g2000prc.googlegroups.com><13csi2tn49esmc3@corp.supernews.com> <13csqk47j0c56b0@corp.supernews.com> Message-ID: <13ct7v3qn2v5206@corp.supernews.com> > This isn't a "cast" in the sense of some less-strongly-typed languages; > it's just a conversion. The `list` function/type iterates over its > argument and turns it into a list. Sets are iterable, so that's all > that's really going on here. oh :~). Learning experience happening here... Thank you. > The reason that lists don't have set-like methods is because > lists aren't sets -- lists can contain duplicate elements Interesting point -- if that's all there is in it, then lists should have difference and intersection methods. Not because they are the same as sets -- because they are slightly different than sets. In this case it doesn't matter - my lists don't contain duplicate elements this time - but I have worked with lists in money market and in inventory, and finding the intersection and difference for matching off and netting out are standard operations. Still, any built in feature would probably be too simple to use in any but the simplest cases. Steve. "Erik Max Francis" wrote in message news:CqSdnRl2x8928FPbnZ2dnUVZ_jSdnZ2d at speakeasy.net... > bambam wrote: > >> Excellent. By symmetry, I see that "list" casts the set back into a list. >> >> I wonder why list has not been extended with the same (difference, >> interesection) methods? Casting to set looks a little kludgy: >> >> c = list(set(a)-set(b)) >> I wonder if that is clearer than the explicit loop? > > This isn't a "cast" in the sense of some less-strongly-typed languages; > it's just a conversion. The `list` function/type iterates over its > argument and turns it into a list. Sets are iterable, so that's all > that's really going on here. > > The reason that lists don't have set-like methods is because lists aren't > sets -- lists can contain duplicate elements, whereas sets cannot. You > should use the proper type for your needs; if you want to take two lists, > remove duplicate elements, and then end up with a list, then the > sets-difference-and-then-make-a-list mechanism is appropriate. > > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis > It [freedom] must be demanded by the oppressed. > -- Dr. Martin Luther King, Jr. From attn.steven.kuo at gmail.com Fri Aug 24 01:04:31 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 23 Aug 2007 22:04:31 -0700 Subject: List Comprehension Question: One to Many Mapping? In-Reply-To: <1187929443.636690.287450@i13g2000prf.googlegroups.com> References: <1187929443.636690.287450@i13g2000prf.googlegroups.com> Message-ID: <1187931871.350842.261120@r23g2000prd.googlegroups.com> On Aug 23, 9:24 pm, beginner wrote: > Hi All, > > How do I map a list to two lists with list comprehension? > > For example, if I have x=[ [1,2], [3,4] ] > > What I want is a new list of list that has four sub-lists: > > [[1,2], [f(1), f(2)], [3,4], [f(3), f(4)]] > > [1,2] is mapped to [1,2] and [f(1), f(2)] and [3,4] is mapped to > [3,4], [f(3), f(4)]. > > I just can't find any way to do that with list comprension. I ended up > using a loop (untested code based on real code): > > l=[] > for y in x: > l.append(y) > l.append([f(z) for z in y]) > Suppose f is: >>> def f(n): return str(n) >>> import itertools Using a list comprehension: >>> [i for i in itertools.chain(*[(eachx, [f(y) for y in eachx]) for eachx in x])] [[1, 2], ['1', '2'], [3, 4], ['3', '4']] Using a list: >>> list(itertools.chain(*[(eachx, [f(y) for y in eachx]) for eachx in x])) [[1, 2], ['1', '2'], [3, 4], ['3', '4']] Not so pretty in either case. -- Hope this helps, Steven From dorjetarap at googlemail.com Sat Aug 18 14:39:18 2007 From: dorjetarap at googlemail.com (dorje tarap) Date: Sat, 18 Aug 2007 19:39:18 +0100 Subject: regular expression dictionary search Message-ID: Hi I have a dictionary with a list of patterns: Code: ( text ) 1. >>> words = {'sho.':6, '.ilk':8,'.an.':78 } Where the "." character means any pattern - this can easily be changed to the "*" symbol if need be. When the user submits a word, I want to be able to look for a corresponding pattern (if it exists). For example if the user said "show" or "shoe", then the value 6 would be returned. If it was "band", "land", "sand", "pant" etc then 78 would be returned - but not "pants" as it is longer than the pattern. I know the normal way is to provide the reg exp and search the dictionary with it, but this is the other way round :( Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From laurent.pointal at wanadoo.fr Sat Aug 11 14:09:03 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Sat, 11 Aug 2007 20:09:03 +0200 Subject: python 2.5 bug References: <1186825286.493878.80380@l70g2000hse.googlegroups.com> <5i5fktF3ml00gU1@mid.uni-berlin.de> <1186826980.346619.287670@r34g2000hsd.googlegroups.com> Message-ID: <46bdfb3f$0$5102$ba4acef3@news.orange.fr> vedrandekovic at v-programs.com wrote: > On 11 kol, 11:59, Marc 'BlackJack' Rintsch wrote: >> On Sat, 11 Aug 2007 02:41:26 -0700, vedrandekovic wrote: >> > I was install Python 2.5 and uninstall Python 2.4 now I cannot run my >> > scripts, only from idle >> >> > What should I do? >> >> Install 2.4 again. Both can be installed in parallel. >> >> Ciao, >> Marc 'BlackJack' Rintsch > > I need python 2.5 for work becose python 2.4 module tokenizer has no > attribute "untokenize" IMHO Python 2.4 was registered for .py files, Python 2.5 take precedence when installed, but when Python 2.4 has been removed, it remove .py files association too (so break Python 2.5 association). * manually associate .py/.pyc/.pyo files to python.exe, .pyw files to pythonw.exe. * or reinstall Python 2.5 so that it re-setup ad-hoc associations. From soundplay at gmail.com Sat Aug 18 08:24:35 2007 From: soundplay at gmail.com (SHY) Date: Sat, 18 Aug 2007 14:24:35 +0200 Subject: passing arguments with ampersands In-Reply-To: <20070818112913.GA3632@gmail.com> References: <20070818112913.GA3632@gmail.com> Message-ID: theres no special portion of code, just the one that handles filenames with spaces. the problem is that when i associate a file extension to my application and i open it, the filename is not quoted before passed as an arguement. i dont know if its the problem of windows or something, or it was just my fault when i incorrectly associated the extension. anyway, this is the code that outputs the second quote i posted in the original message: args = None > if len(sys.argv) > 1: > args = sys.argv[1:] > print args > and this is the code that handles the filenames with spaces (as space generally delimits cmdline params). its not very ellegant, needs a bit of tuning, but it works (i dont use any kind of -d --something params yet). [code] newargs = [] if args: first = None for arg in args: if not first: first = arg continue if os.path.isfile(first): newargs.append(first) first = None continue if arg.find(":") == -1: first = " ".join([first, arg]) if first: newargs.append(first) [/code] how can i make the params get quoted before send as arguments? thanks in advance. > > 2007/8/18, O.R.Senthil Kumaran : > Quote:D:\ftp\Music\Mixes & Compilations\Above & Beyond - Essential > > Mix\001_Essential_Mix_2004-06-06_-_Above_and_Beyond.txt > > > when i put 'print sys.argv[1:]' at the very beginning of the script, all > i > > get is this: > > > > Quote:['D:\\ftp\\Music\\Mixes'] > > > Can you share the portion of the code? > Are you quoting the argument that you are passing? > for e.g: > > #cat 1.py > import sys > print sys.argv[1] > > #python 1.py "I am able to print the spaces and & characters" > I am able to print the spaces and & characters > > -- > O.R.Senthil Kumaran > http://uthcode.sarovar.org > -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Wed Aug 8 10:52:39 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Aug 2007 14:52:39 GMT Subject: This bit of code hangs Python Indefinitely References: Message-ID: brad wrote: > Chris Mellon wrote: > >> ... the producer is designed to block if >> the queue is full. You can use the put_nowait method to have it raise >> an exception instead of blocking. > > I assumed that the behavior would have been the other way around. I > should not have made that assumption. > You could possibly make a case that before Queue.put blocks it should check whether the program has more than just the one thread and if not it should raise an RTFMException. From arkanes at gmail.com Thu Aug 30 14:52:50 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 30 Aug 2007 13:52:50 -0500 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188430887.481586.106760@l22g2000prc.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> <1188430887.481586.106760@l22g2000prc.googlegroups.com> Message-ID: <4866bea60708301152g202fb267lf409effb215f538@mail.gmail.com> On 8/29/07, Russ wrote: > > > But it's always a good idea to make your software "correct and as > > reliable as possible", isn't it? The problem is the external constraints > > on the project. As the old saying goes: "Cheap, fast, reliable: choose > > any two". > > If you are suggesting that "programming by contract" is not > appropriate for every application, you will get no argument from me. > All I am suggesting is that having the option to use it when you need > it is very desirable, and it can possibly enhance the versatility of > Python by making Python more suitable for *some* mission-critical > applications. > PEP 316 introduces new syntax for a limited use feature. That's pretty much a no-starter, in my opinion, and past experience tends to bear that out. Furthermore, it predates decorators and context managers, which give all the syntax support you need and let you move the actual DBC features into a library. I can't remember if I mentioned this before but I believe that Philip Ebys PEAK toolkit has some stuff you could use for DBC. > I once read a book on something called SPARK Ada, which also supports > programming by contract. I was pleasantly surprised to discover > yesterday that support for the such methods is also available for > Python. However, the support would obviously be a bit stronger if it > were in the core Python distribution. > If a well written contract library were to exist, and people were to use it, and the author were interested, it would make a decent candidate for inclusion in the standard library, and I wouldn't oppose such a thing (for all my opinion is worth, ie essentially nothing). The PEP 316 special syntax is another matter entirely. The best way for this to happen is for you to find or write such a library, and use it to write good code. From istvan.albert at gmail.com Wed Aug 8 09:48:01 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Wed, 08 Aug 2007 13:48:01 -0000 Subject: This bit of code hangs Python Indefinitely In-Reply-To: References: Message-ID: <1186580881.048597.134350@22g2000hsm.googlegroups.com> On Aug 8, 9:38 am, brad wrote: > The problem is that I have 512 things to add to the queue, but my limit > is half that... whoops. Shouldn't the interpreter tell me that I'm an > idiot for trying to do this instead of just hanging? A message such as > this would be more appropriate: See the docs, especially the block and timeout parameter for the put method: http://docs.python.org/lib/QueueObjects.html Istvan From horpner at yahoo.com Thu Aug 30 14:14:21 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 30 Aug 2007 18:14:21 GMT Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188495863.242815.236900@o80g2000hse.googlegroups.com> Message-ID: On 2007-08-30, zzbbaadd at aol.com wrote: >> How could it not be an exception, in the plain English sense >> of the word? Most certainly you're asking for the index >> because you want to do something with the index. If the item >> is not found, you have no index, so that's a special case that >> must be handled separately. There is no logical difference >> between handling that special case in an except clause versus >> handling it with an if-branch. > > In my case of have done os.listdir() on two directories. I want > to see what files are in directory A that are not in directory > B. In that case list.find would not be much of a win, but sets might be. not_in_both = list(set(os.listdir("A")) - set(os.listdir("B"))) > I have used exceptions in other languages and only do so on > logic that should never happen. In this case it is known that > some of the files will not be in both lists. I just want to > know which ones. "Exceptions" has become somewhat a misnomer. iterators are implemented using exceptions, and there's hardly anything more common in modern Python code. The hair shirts and thumb-screws necessary for using exceptions correctly in C++, aren't needed in Python. -- Neil Cerutti From jstroud at mbi.ucla.edu Fri Aug 3 21:31:39 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 03 Aug 2007 18:31:39 -0700 Subject: How to pass a reference to the current module In-Reply-To: References: Message-ID: Carsten Haese wrote: > please describe less abstractly what you're trying to do. You sound like my former thesis adviser. OK. From an external source, such as configuration file, the user will specify the *name* of a function somehow with the assumption that the function will be coded somewhere (in the present or other modules) by that name. This behavior is to be implemented in a very primitive pythoncard-like application wherein the user can specify hooks via a configuration file. The configuration file will describe the GUI. To go one more step deeper into the rationale, the idea would be to replace optparse type behavior with a gui wherein one can type input parameters into fields rather than specify them at the command line with optional flags. Please take a look at my previous response to myself for one possible solution I devised. I don't particularly like it much, however, because it seems unnatural. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From tjreedy at udel.edu Fri Aug 3 14:49:49 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 3 Aug 2007 14:49:49 -0400 Subject: __call__ considered harmful or indispensable? References: <46b24200$0$19638$426a74cc@news.free.fr> <46b2e0c2$0$14572$426a74cc@news.free.fr> Message-ID: Skip Montanaro a ?crit : >>> In this case there was a bug. Depending on inputs, sometimes obj >>> initialized to a class, sometimes an instance of that class. (I fixed >>> that too while I was at it.) The problem was that the use of __call__ >>> obscured the underlying bug by making the instance as well as the class >>> callable. > >> I don't quite get the point here. A concrete example would be welcome. > > The bug went something like this: > > obj = some.default_class > ... > if some_other_rare_condition_met: > ... several lines ... > obj = some.other_class() Should that have been some.other_class (without the ()s?). It is in the nature of Python's dynamic typing that mis-typing errors sometimes show up later than one would wish. Hence the need for unit testing. Consider i = condition and 1 or '2' # whoops, should have been 2, without the 's ... k = j * i # j an int; whoops, bad i value passes silently ... use of k as string raises exception I do not think __call__ should be specifically blamed for this general downside of Python's design. Terry Jan Reedy From steve at holdenweb.com Fri Aug 17 07:04:49 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 17 Aug 2007 07:04:49 -0400 Subject: to property or function in class object In-Reply-To: <1187317787.848991.242720@i38g2000prf.googlegroups.com> References: <1187317787.848991.242720@i38g2000prf.googlegroups.com> Message-ID: james_027 wrote: > hi, > > i am very new to python, not knowing much about good design. I have an > object here for example a Customer object, where I need to retrieve a > info which has a number of lines of code to get it. > > my question is weather what approach should I use? to use the property > which is from the python new class style as I understand or simple use > function that will return the the info I needed. > > class Customer(object): > > current_balance = property(fget=_get_current_balance) > This will need to go down below the definition of _get_current_balance() if you want to avoid an error in compilation. > def _get_current_balance(self): > # coding here > > or > > def get_current_balance(self): > # coding here > > While both approach would get the job done, I don't know much about > the performance, benefits, design philosophy between the two approach. > Any lecture will be very appreciated. > It's pretty much a matter of choice when the method to retrieve the value doesn't take any arguments. If it *does* take arguments then you can't use a property. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From robert.vergnes at yahoo.fr Mon Aug 27 10:18:26 2007 From: robert.vergnes at yahoo.fr (rfv-370) Date: Mon, 27 Aug 2007 07:18:26 -0700 Subject: How to free memory ( ie garbage collect) at run time with Python 2.5.1(windows) Message-ID: <1188224306.863247.127890@50g2000hsm.googlegroups.com> have made the following small test: Before starting my test my UsedPhysicalMemory(PF): 555Mb >>>tf=range(0,10000000) PF: 710Mb ( so 155Mb for my List) >>> tf=[0,1,2,3,4,5] PF: 672Mb (Why? Why the remaining 117Mb is not freed?) >>> del tf PF: 672Mb (unused memory not freed) So changing the list contents and/or deleting the list changes nothing...from a memory point of view. This is a problem as I have several applications/threads competing for memory share. (ie wxpython app). So how can I force Python to clean the memory and free the memory that is not used? PS: gc.collect() does nothing - To return memory I need to kill my process (ie the interpreter). Any ideas is welcome. Thanx Robert From steve at holdenweb.com Tue Aug 21 07:31:53 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 21 Aug 2007 07:31:53 -0400 Subject: Newbee Question In-Reply-To: <1187650036.450645.185500@a39g2000hsc.googlegroups.com> References: <1187621470.484615.7010@i13g2000prf.googlegroups.com> <1187622390.854759.162320@q3g2000prf.googlegroups.com> <1187650036.450645.185500@a39g2000hsc.googlegroups.com> Message-ID: <46CACD29.8080200@holdenweb.com> hd1956 at yahoo.com wrote: [...] > > Thanks for the help. By the way I am trying to learn the python after > work and on weekends. If it was a dumb question, to this group, I will > not bother you all again. > Without help it will take me longer to learn. Thanks > Don't worry about it. There is also a list specifically for learners, which you can find out about at http://mail.python.org/mailman/listinfo/tutor Welcome to the Python community! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From jgardner.jonathangardner.net at gmail.com Tue Aug 21 14:10:41 2007 From: jgardner.jonathangardner.net at gmail.com (Jonathan Gardner) Date: Tue, 21 Aug 2007 18:10:41 -0000 Subject: confused about why i get a type error when i call an object's method In-Reply-To: <1187719631.092657.158410@d55g2000hsg.googlegroups.com> References: <1187719631.092657.158410@d55g2000hsg.googlegroups.com> Message-ID: <1187719841.367010.293930@e9g2000prf.googlegroups.com> On Aug 21, 11:07 am, pep... at rumbalski.com wrote: > I'm confused about why i get a type error when i call an object's > method. Here's the example code:>>> class Foo: > > def __init__(self): > self.foo = [] > def foo(self): > print "in foo!" > > >>> f = Foo() > >>> dir(f) > > ['__doc__', '__init__', '__module__', 'foo'] > > >>> f.foo() > > Traceback (most recent call last): > File "", line 1, in > f.foo() > TypeError: 'list' object is not callable > > You've redefined what "f.foo" means in __init__. It's no longer a class method, but an attribute of the instance--the list. You can't call a list. Do this to show what I mean: >>> f.foo [] From samfeltus at gmail.com Thu Aug 23 23:03:22 2007 From: samfeltus at gmail.com (SamFeltus) Date: Fri, 24 Aug 2007 03:03:22 -0000 Subject: Summer Comic Relief in Python Message-ID: <1187924602.321976.223990@q4g2000prc.googlegroups.com> SonomaSunshine runs well on Django now... http://samfeltus.com/django/DjangoSummer.html (Use flowers to navigate to 10 scenes, no preloader, ~6mb) SonomaSunshine, the Redneck Riviera's Best Python Powered Folk Art Server, makes it easy to generate Cartoonish backdrops for Flash movies in Django... There will be a debugged alpha version out this week... Sam the Gardener :) From fabioztessitore at libero.it Sun Aug 12 13:31:42 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 12 Aug 2007 17:31:42 GMT Subject: Regular Expression Grouping References: <1186939262.144073.182450@z24g2000prh.googlegroups.com> Message-ID: <46bf43fe$0$10626$4fafbaef@reader2.news.tin.it> Il Sun, 12 Aug 2007 17:21:02 +0000, linnewbie ha scritto: > Fairly new to this regex thing, so this might be very juvenile but > important. > > I cannot understand and why 'c' constitutes a group here without being > surrounded by "(" ,")" ? > >>>>import re >>>> m = re.match("([abc])+", "abc") >>>> m.groups() > ('c',) > > Grateful for any clarity. thera are () outer [], maybe you don't know what do [] mean? or you want to know why 'c' and not 'a' or 'b' bye From mail at timgolden.me.uk Wed Aug 22 06:52:38 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 22 Aug 2007 11:52:38 +0100 Subject: Dispatching default application for file, cross platform. In-Reply-To: References: <01e101c7e48d$e0e9f860$03000080@hendrik> Message-ID: <46CC1576.7060309@timgolden.me.uk> Peter Otten wrote: > Tim Golden wrote: > >> Hendrik van Rooyen wrote: >>> How do I do the equivalent of clicking (in SuSe) or double clicking (in >>> Windows) on a file? >>> >>> In effect I want to tell the OS - take this file and feed it to the >>> application that is registered for it. > >> os.startfile > > Unfortunately this is Windows-only. Good point. I think that Paul Boddie's desktop module is designed to handle cross-platform issues for this kind of thing: (Never used it myself) http://pypi.python.org/pypi/desktop/0.2.3 TJG From coxy1 at netspace.net.au Sat Aug 11 16:21:36 2007 From: coxy1 at netspace.net.au (Tony) Date: Sun, 12 Aug 2007 06:21:36 +1000 Subject: SUCK my HUSBAND'S CUM from my CUNT Message-ID: <20070811202138.CCBE91345D4@mail.netspace.net.au> -------------- next part -------------- An HTML attachment was scrubbed... URL: From iddw at hotmail.com Fri Aug 3 18:36:05 2007 From: iddw at hotmail.com (Dave Hansen) Date: Fri, 03 Aug 2007 15:36:05 -0700 Subject: regexp problem in Python In-Reply-To: <1186177312.117581.129910@d55g2000hsg.googlegroups.com> References: <1186177312.117581.129910@d55g2000hsg.googlegroups.com> Message-ID: <1186180565.489968.310340@j4g2000prf.googlegroups.com> On Aug 3, 4:41 pm, Ehsan wrote: > I want to find "http://www.2shared.com/download/1716611/e2000f22/ [...] > I use this pattern : > "http.*?\.(wmv|3gp).*"" > > but it returns only 'wmv' and '3gp' instead of "http://www.2shared.com/ > download/1716611/e2000f22/Jadeed_Mlak14.wmv? > tsid=20070803-164051-9d637d11" > > what can I do? what's wrong whit this pattern? thanx for your comments Just a guess, based on too little information: Try "(http.*?\.(wmv| 3gp).*)" Regards, -=Dave From billiejoex at gmail.com Tue Aug 21 20:57:32 2007 From: billiejoex at gmail.com (codesite-noreply) Date: Tue, 21 Aug 2007 17:57:32 -0700 Subject: Extracting the traceback In-Reply-To: References: <1187740411.848743.151960@x35g2000prf.googlegroups.com> Message-ID: <1187744252.157335.91630@x40g2000prg.googlegroups.com> On 22 Ago, 02:09, "Evan Klitzke" wrote: > On 8/21/07, billiejoex wrote: > > > > > Hi there, > > I'm facing a case where I need to get the traceback outptut when > > occurring an exception. > > I solved such problem by using traceback module in conjunction with > > StringIO: > > > import StringIO, traceback > > try: > > raise Exception > > except: > > f = StringIO.StringIO() > > traceback.print_exc(file=f) > > print f.getvalue() > > > ... but this seems a little poor to me since I first put output into > > the StringIO.StringIO(), then I get it back by using getvalue() on > > it. > > Is there a way to avoid the use of StringIO and get such output > > without using such (useless) additional step? > > If you just want to print the output (as in your example), you can use > file=sys.stdout or file=sys.stderr in the call to print_exc. If you > want to store the traceback into a string for some other purpose (e.g. > logging, email notifications) I believe that you must use a StringIO > object. > > -- > Evan Klitzke Unfortunately I have to pass the output to a function which prints the passed string both on screen and into a log file. Anyway, not too much important. I'll use StringIO if there's no other solution. Thanks From ldo at geek-central.gen.new_zealand Fri Aug 31 01:31:18 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 31 Aug 2007 17:31:18 +1200 Subject: Symbolic Link References: <1187475296.173269.263080@k79g2000hse.googlegroups.com> <1187555373.202634.163160@57g2000hsv.googlegroups.com> <1187646982.760523.195750@i38g2000prf.googlegroups.com> Message-ID: In message , Ian Clark wrote: > My question would be why a symbolic link? Why not a hard link? Because of the potential for confusion. For instance, modifying the file without realizing that some other place expects to see the unmodified version. From iclark at mail.ewu.edu Thu Aug 2 13:42:59 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Thu, 02 Aug 2007 10:42:59 -0700 Subject: problems playing with dates from any month. In-Reply-To: References: Message-ID: krishnakant Mane wrote: > hello, > I have a very strange problem and I can't find any solution for that. > I am working on an accounting package which I wish to develop in python. > the simple problem is that I want to knoe how I can know if the given > date is the nth day of a month. > for example if a customer is supposed to pay his installment on every > 5th of all months, > I want to know if today is the fifth day (jan the fifth, feb the fifth > etc) for any given month. > I have not found any such function. > if I have looked (or over looked ) in the wrong places I am really sorry. > secondly I also want to know the way in which I can convert a given > string to a date object. > for example if I have a string "29/09/2005", I know it is a valid date > although it is in a string form. > now I want to convert the above string into a real date object. > how can I cast it this way? > regards, > Krishnakant. http://docs.python.org/lib/node85.html Then it's just: if date_obj.day == 5: print 'It's the fifth day of the month' Ian From tjreedy at udel.edu Thu Aug 2 17:12:27 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 2 Aug 2007 17:12:27 -0400 Subject: __call__ considered harmful or indispensable? References: <18098.8872.263489.36952@montanaro.dyndns.org> Message-ID: wrote in message news:18098.8872.263489.36952 at montanaro.dyndns.org... | I'm wondering, are there some general cases where __call__ methods of | a user-defined class are simply indispensable? One classical example (untested, based on memory of posted code): class memoize(): def __init__(self, func): self.func = func self.memo = {} def __call__(self, *args): try: return self.memo[args] except KeyError: res = self.func(*args) self.memo[args] = res return res Before Py2.2 closures, I might have called this indispensible. Since no attributes are rebound, this can now be written def memoize(func): memo = {} def _(*args) try: return memo[args] except KeyError: res = func(*args) memo[args] = res return res return _ This is a bit simpler, but one gives up both direct external access to the memo dict and any other methods, such as a customized def __repr__(self): return "memoize wrapper for %s" % self.func or possibly a method to empty (or partially empty) the memo dict. If I were writing about memoization for programmers in general, just using Python, I would give both forms since many languages (including Py2.1-) do not have both forms, even if they have one. Terry Jan Reedy From pyth0nc0d3r at gmail.com Tue Aug 28 11:13:32 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Tue, 28 Aug 2007 09:13:32 -0600 Subject: Python Classes In-Reply-To: <8AC0DE08-89C7-4647-93FE-CC9ED6102C98@myemma.com> References: <8AC0DE08-89C7-4647-93FE-CC9ED6102C98@myemma.com> Message-ID: Ok thanks I'll try remembering it. On 8/28/07, Erik Jones wrote: > > On Aug 28, 2007, at 12:04 AM, Lamonte Harris wrote: > > > How come you have to set the initialized created variables to equal > > the parameters, shouldn't that be default? > > > > class testing: > > def __init__(self,testing): > > self.testing = testing > > x = testing("testing") > > print x.testing > > > > > > How come self.testing = testing > > > > Can someone explain that in more detail, just confused on why you > > have to set it up like that. > > -- > > Simple Answer: > > Because language should never set variable values "by default". > That's what programmers are for. There may be application domains > where *some* defaulting behavior makes sense, but that's what > frameworks and DSLs are for. > > Erik Jones > > Software Developer | Emma(r) > erik at myemma.com > 800.595.4401 or 615.292.5888 > 615.292.0777 (fax) > > Emma helps organizations everywhere communicate & market in style. > Visit us online at http://www.myemma.com > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fabiofz at gmail.com Mon Aug 13 12:09:45 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 13 Aug 2007 13:09:45 -0300 Subject: Eclipse/PyDev question In-Reply-To: <1187011251.632213.249450@g4g2000hsf.googlegroups.com> References: <1186998539.030727.279330@g4g2000hsf.googlegroups.com> <1187005485.137101.43130@l70g2000hse.googlegroups.com> <1187006912.494455.86830@w3g2000hsg.googlegroups.com> <1187011251.632213.249450@g4g2000hsf.googlegroups.com> Message-ID: On 8/13/07, king kikapu wrote: > > Ah, i forgot another one: > > as any project evolves, you need to organize it in directories. So, i > have a project named "Dev" and Eclipse has provided me (in Navigator) > with "Dev" and "Src". Inside Src i put my .py files. Let's say that i > want to create a directory there (will i make it in "Src" or in "Dev") > to put other .py files. I tried adding a "Folder", i also tried to add > a "Pydev Source Folder", either way i cannot refer to these files from > a .py located in Src directory with the usual "from folderA > import"...It does not understand the folder structure and i am pretty > sure i am missing something obvious here... > You have to set as source folders the exact same folders you'd usually put into your pythonpath (that's one level before the module you're going to import). Details on how to do that can be found at: http://fabioz.com/pydev/manual_101_root.html Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Mon Aug 27 09:39:56 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 27 Aug 2007 06:39:56 -0700 Subject: Best open source Python online *CHAT* apps? In-Reply-To: <1188202360.562850.24860@e9g2000prf.googlegroups.com> References: <1188202360.562850.24860@e9g2000prf.googlegroups.com> Message-ID: <1188221996.849125.109130@y42g2000hsy.googlegroups.com> On Aug 27, 3:12 am, "seber... at spawar.navy.mil" wrote: > Best open source Python online chat apps? > > I believe there are a few PHP online chat apps to allow people to have > conversation > via a web server but a Python one would soothe the soul. > > Any available? > > Thanks, > > Chris Dunno, but I see Gozerbot just had another release. Check it out. I also found this link, but my business blocks it so I'm not sure how useful it is: http://www.bigwebmaster.com/Python/Scripts_and_Programs/Chat_Scripts/ Mike From conra2004 at yahoo.com Tue Aug 21 09:27:30 2007 From: conra2004 at yahoo.com (yadin) Date: Tue, 21 Aug 2007 06:27:30 -0700 Subject: 3D plot of 50 lines kwing end points using VTK Message-ID: <1187702850.063661.139910@r29g2000hsg.googlegroups.com> does anyone know how to plot multimple lines like lets say... 50 lines each liine is defined beetween two given points using VTK. a litlle example will be ok please on python and VTK thank you From horpner at yahoo.com Wed Aug 8 14:00:59 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 08 Aug 2007 18:00:59 GMT Subject: Something in the function tutorial confused me. References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <1186424693.529497.217040@w3g2000hsg.googlegroups.com> <46B8626A.2070303@bigfoot.com> <5hsoi3F3mlni2U1@mid.individual.net> <1186581124.3383.55.camel@dot.uniqsys.com> Message-ID: On 2007-08-08, Steve Holden wrote: > Carsten Haese wrote: >> On Wed, 2007-08-08 at 08:52 -0400, Steve Holden wrote: > [...] >> The problem is your ambiguous use of the word "assignment." In >> the sense of the Language Reference, "any assignment to y" is >> a simple assignment that always modifies a namespace and never >> modifies an object. In that sense, the mutability of None >> really isn't the issue. >> >> If you use the broader sense in which "assignment" includes >> augmented assignments, the mutability of None does become >> relevant. >> >> I agree that greg's delivery was unduly disrespectful, but I >> think he was making a valid point. >> >> Hope this helps clear up the confusion. >> >> Best regards, > > And this is why we should all be using the term "binding", > which is normal in Python. I'll try to be more careful in > future. The Python Language Reference seems a little confused about the terminology. 3.4.7 Emulating numeric types 6.3.1 Augmented assignment statements The former refers to "augmented arithmetic operations", which I think is a nice terminology, since assignment is not necessarily taking place. Then the latter muddies the waters. So Steve was both wrong and right, depending on the terminology. I tend to think the world would be a better place if he'd been right. -- Neil Cerutti The church will host an evening of fine dining, superb entertainment, and gracious hostility. --Church Bulletin Blooper From ndbecker2 at gmail.com Wed Aug 8 08:21:43 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Wed, 08 Aug 2007 08:21:43 -0400 Subject: mmm-mode, python-mode and doctest-mode? References: <46B8341E.2090805@gradient.cis.upenn.edu> Message-ID: Anyone testing on xemacs? I tried it, and C-c C-c sent xemacs into an infinite loop (apparantly). From horpner at yahoo.com Mon Aug 6 06:27:22 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 06 Aug 2007 10:27:22 GMT Subject: Misleading wikipedia article on Python 3? References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <7xzm15q8fy.fsf@ruckus.brouhaha.com> Message-ID: On 2007-08-06, Paul Rubin wrote: > Carsten Haese writes: >> For instance, if you never use print statements in your code, you won't >> notice that print is becoming a function. If you do, you'll have to make >> appropriate accommodations. > > Why on earth did they make this change? It just seems > gratuitous. Is the assert statement also being changed? Are > they going to update all the docs that say that the yield > statement works like the print statement? >From the footnotes of PEP 3100: http://mail.python.org/pipermail/python-dev/2005-September/056154.html http://www.python.org/dev/peps/pep-3105 -- Neil Cerutti From raims at dot.com Mon Aug 13 05:21:05 2007 From: raims at dot.com (Lawrence Oluyede) Date: Mon, 13 Aug 2007 11:21:05 +0200 Subject: verify whether "str" is still callable in Python 2.5.1 References: <1186994287.527549.119170@19g2000hsx.googlegroups.com> Message-ID: <1i2s7ep.1dmyyzvygpp6oN%raims@dot.com> Ge Chunyuan wrote: > Once use ActivePython latest version for Python 2.5.1. > I happened to find function "str" is not callable, but it is available > for Python 2.5. > Can anybody give some comments about it? I don't really understand what your asking. str is a callable, it has always been AFAIK, since it's a type constructor, like int() In [1]: callable(str) Out[1]: True In [2]: str() Out[2]: '' -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From rdm at rcblue.com Fri Aug 10 13:57:22 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 10 Aug 2007 10:57:22 -0700 Subject: Puzzled by "is" In-Reply-To: <87zm1042f0.fsf@benfinney.id.au> References: <20070809194105.39BD11E400A@bag.python.org> <87zm1042f0.fsf@benfinney.id.au> Message-ID: <20070810175735.B469C1E400A@bag.python.org> At 06:13 PM 8/9/2007, Ben Finney wrote: >Content-Transfer-Encoding: base64Grzegorz >S??odkowicz theorisation but I'd rather expect the interpreter > > simply not to create a second tuple while there already is an > > identical one. > >Others have already said that it's an implementation optimisation, >which seems to partly answer your question. > >It's important to also realise that the language is *deliberately* >non-committal on whether any given value will have this behaviour; >that is, it's entirely left to the language implementation which >optimisation trade-offs to make, and the language user (that's you and >I) should *not* expect any particular behaviour to hold between >different implementations. I'm not clear on the meaning of "implementations" here. Would 2.5 for Windows, Mac, Linux all be different implementations? Would Iron Python be another? ActivePython? Thanks, Dick From kyosohma at gmail.com Wed Aug 15 10:54:55 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 15 Aug 2007 07:54:55 -0700 Subject: ming on win32 anyone ? [help a noob] In-Reply-To: <1187189173.036327.65360@r29g2000hsg.googlegroups.com> References: <%QCwi.14541$rr5.1213@newsfe1-win.ntli.net> <1187189173.036327.65360@r29g2000hsg.googlegroups.com> Message-ID: <1187189695.581003.317920@q4g2000prc.googlegroups.com> On Aug 15, 9:46 am, "programmer... at gmail.com" wrote: > On Aug 15, 8:03 am, "daz.diamond" wrote: > > > hoping someone can help ... > > > how do I install ming (with python) on win32? have downloaded the tar.gz > > of ming-0.3.0 which doesn't have a handy self-installer, and I'm > > absolutely foxed as to what to do next ... the install instructions in > > the package seem to be linux oriented, which to me may as well be in greek > > > any clues much appreciated, thx > > > daz > > I don't know what you've downloaded, but it does not sound like the > right thing, err ming. The installer found here is 5.1.3.http://sourceforge.net/project/showfiles.php?group_id=2435 > > Maybe you should consider cygwin? > > jw I think the OP is referring to this: http://ming.sourceforge.net/ If so, it looks like it needs manual compilation using a C/C++ compiler of some sort. Mike From gmcalendar at gmail.com Thu Aug 23 16:49:24 2007 From: gmcalendar at gmail.com (gmcalendar at gmail.com) Date: Thu, 23 Aug 2007 20:49:24 -0000 Subject: simple spider in python In-Reply-To: <1187890751.871660.275320@z24g2000prh.googlegroups.com> References: <1187876014.845912.236690@e9g2000prf.googlegroups.com> <1187879398.007797.128510@i13g2000prf.googlegroups.com> <1187880988.813113.20350@l22g2000prc.googlegroups.com> <1187890751.871660.275320@z24g2000prh.googlegroups.com> Message-ID: <1187902164.596545.101050@q3g2000prf.googlegroups.com> > As to the Google API key issue, I was unaware of that. Very annoying > of them to stop that service. PyGoogle will basically be useless. well, i think that they deserve people moving toward yahoo's API... check this out: http://pysearch.sourceforge.net/ it's basically the same thing as pygoogle BUT working with google's competitor. it seems like internet has its own built-in antibodyes! ^__^ cheers! From martin at v.loewis.de Thu Aug 23 15:59:43 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 23 Aug 2007 21:59:43 +0200 Subject: MsiLib In-Reply-To: References: Message-ID: <46CDE72F.2090009@v.loewis.de> Charlie schrieb: > Thank you everybody for your help. It finally runs without errors and I > should be able to use this as I figure out more of it. I am curios if > there is any idea as to when GetString will be implemented? If I can find the time, it may be for Python 2.6. If not, Python 2.7, 3.1, or so. Faster if a patch is contributed. Regards, Martin From half.italian at gmail.com Mon Aug 27 15:24:31 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Mon, 27 Aug 2007 12:24:31 -0700 Subject: Socket - gaierror Message-ID: <1188242671.182072.130150@r23g2000prd.googlegroups.com> Hi all, I'm having trouble with the socket module resolving a hostname. It seems like this is a system level problem, but I'm not even sure where to start. I can ping the smtp server by name and IP, but when smtp.SMTP("theHost") tries to get the hostname, it keeps giving me the following error: File "bin/program.py", line 123, in notify smtp = smtplib.SMTP("theHost") File "/usr/lib/python2.4/smtplib.py", line 255, in __init__ addr = socket.gethostbyname(socket.gethostname()) gaierror: (-2, 'Name or service not known') I tried changing to a different smtp server, using an ip instead of a host name. I could ping both boxes by name oor IP. any ideas? ~Sean From ldo at geek-central.gen.new_zealand Sat Aug 18 00:34:22 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 18 Aug 2007 16:34:22 +1200 Subject: python socket usage References: Message-ID: In message , O?uz Yar?mtepe wrote: > Is it possible to send a data object like a tuple or a list in socket > programming? You'll have to define a bytestream encoding to send over the connection. I recently wrote up some Python code based on the old "chunk" idea from the Amiga days. Feel free to have a read and see if it makes sense to you. From bj_666 at gmx.net Tue Aug 28 01:00:05 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Aug 2007 05:00:05 GMT Subject: XML File -- dictionary edit/search References: <1188263724.306539.181980@y42g2000hsy.googlegroups.com> Message-ID: <5jhoekF3u17i9U1@mid.uni-berlin.de> On Mon, 27 Aug 2007 18:15:24 -0700, -b wrote: > I am trying to put together a python program that will be able to ask > for a word and its definition, then save that information into an xml > file for reference. I am not down right set on the file being in xml > format, but xml is the first thing that comes to mind, since I do not > want to use a MySQL database. I think xml will be easy to search and > return a word's definition--another reason why xml comes to mind first > after MySQL databases. Please, if you have any suggestions to what > python-xml libraries I might use to program this small app with, then > by all means voice your thoughts. Thank you very much for your time. `ElementTree` is a good XML library and from Python?2.5 on it is in the standard library. There are others, even in the standard library. Have you looked in the documentation? I don't think XML is a good storage format here. Looks to complicated to use a format suited for deeply nested structures for a simple flat database. Maybe CSV is enough here. Take a look at the `csv` module in the standard library. Or use SQLite. From Python?2.5 on there's even support for SQLite in the standard library. Ciao, Marc 'BlackJack' Rintsch From david at boddie.org.uk Sun Aug 5 09:35:53 2007 From: david at boddie.org.uk (David Boddie) Date: Sun, 05 Aug 2007 15:35:53 +0200 Subject: Best programs written completly in Python Message-ID: <200708051535.53978.david@boddie.org.uk> On Sun Aug 5 14:44:55 CEST 2007, Franz Steinh?usler wrote: > I'm only interested to have a list, or even help to > extend an existing one. If the main criterion is that the programs are written in Python then surely the PythonInfo Wiki is the place for such a list: http://wiki.python.org/moin/Applications May I suggest that you extend this one? David From use-revolution-bounces at lists.runrev.com Fri Aug 17 21:40:01 2007 From: use-revolution-bounces at lists.runrev.com (use-revolution-bounces at lists.runrev.com) Date: Fri, 17 Aug 2007 20:40:01 -0500 Subject: Your message to use-revolution awaits moderator approval Message-ID: Your mail to 'use-revolution' with the subject Returned mail: see transcript for details Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. If you would like to cancel this posting, please visit the following URL: http://lists.runrev.com/mailman/confirm/use-revolution/3f697cbe8e6e256a948b97c962c723f61075fc87 From tjreedy at udel.edu Thu Aug 2 16:36:08 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 2 Aug 2007 16:36:08 -0400 Subject: Determining if file is valid image file References: <1186064098.587590.91210@g4g2000hsf.googlegroups.com><1186064275.652416.250540@d55g2000hsg.googlegroups.com><1186065645.879720.27720@q75g2000hsh.googlegroups.com> Message-ID: "Jarek Zgoda" wrote in message news:f8tbd6$rnh$1 at nemesis.news.tpi.pl... Andr? napisa?(a): >>>> Other than installing PIL, is there a "simple" way using Python only >>>> to determine if a file is a valid image file? [...] > Be aware that broken images (i.e. partially downloaded) in many cases > pass the imghdr.what() test. To put it another way, the only way to determine whether a coded file is valid may be to decode it. And even then, it may be corrupted in the sense that the decoded version may have artifacts not in the original. I have seen the latter both in jpeg images and movie DVDs. tjr From enleverlesX.XmcX at XmclaveauX.com Wed Aug 29 09:19:27 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Wed, 29 Aug 2007 15:19:27 +0200 Subject: Pythonwin Install COM exceptions on Windows Vista Ultimate References: Message-ID: <46d578dc$0$25911$ba4acef3@news.orange.fr> Hi! Perso, on Vista, I : - deactive UAC - deactive firewall (I have a rooter) - run all like Administrator - install all in other DIR than "Program Files" Result : no problem. From mkent at acm.org Fri Aug 31 02:07:54 2007 From: mkent at acm.org (Mike Kent) Date: Fri, 31 Aug 2007 02:07:54 -0400 Subject: What's on at APL 2007, Montreal, October 21, (Tutorials) 22, 23 (Program) Message-ID: <5jpphrFof1qU1@mid.individual.net> ( Details and abstracts coming to the APL 2007 web page http://www.sigapl.org/apl2007.html shortly. In the meantime ... ) Tutorials and workshops Introduction to APL (Ray Polivka) OO for APLers, APL for OOers (Dan Baronet) ... others in the works Presentations No Experience Necessary: Hire for Aptitude - Train for Skills (Brooke Allen) Compiling APL with APEX (Robert Bernecky) APL, Bioinformatics, Cancer Research (Ken Fordyce) Generic Programming on Nesting Structure (Stephan Herhut, Sven-Bodo Scholz, Clemens Grelck) Interactive Array-Based Languages and Financial Research (Devon McCormick) Array vs Non-Array Approaches to Programming Problems (Devon McCormick) Design Issues in APL/OO Interfacing (Richard Nabavi) Arrays of Objects, or Arrays within Objects (Richard Nabavi) Competing, with J (John Randall) Plus representatives of vendors: Dyalog -- IBM -- MicroAPL From jon at turnthepage.org Wed Aug 8 09:57:50 2007 From: jon at turnthepage.org (Jon Rosebaugh) Date: Wed, 8 Aug 2007 08:57:50 -0500 Subject: Web based Reporting tool for Python References: <1186460956.945148.162610@k79g2000hse.googlegroups.com> <1186547726.383996.291360@d55g2000hsg.googlegroups.com> Message-ID: <2007080808575016807-jon@turnthepageorg> On 2007-08-07 23:35:26 -0500, Madhu Alagu said: > Thanking so much for all the informations and links.I would like to > use Mako Templates(www.makotemplates.org).I like to use simple and > python default module... Mako is an excellent template system, but you'll have a lot of work to do making it into a reporting system. From bayesianlogic at acm.org Fri Aug 10 14:08:20 2007 From: bayesianlogic at acm.org (ekzept) Date: Fri, 10 Aug 2007 11:08:20 -0700 Subject: pat-match.lisp or extend-match.lisp in Python? Message-ID: <1186769300.157903.90160@z24g2000prh.googlegroups.com> anyone have either pat-match.lisp or extend-match.lisp redone in Python? or how about knowing where there might be such a thing? sources: http://norvig.com/paip/patmatch.lisp http://www.cs.northwestern.edu/academics/courses/325/programs/extend-match.lisp From bj_666 at gmx.net Thu Aug 30 04:58:30 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Aug 2007 08:58:30 GMT Subject: Python doesn't see the directories I create References: Message-ID: <5jnf5lFdmbcU4@mid.uni-berlin.de> On Thu, 30 Aug 2007 04:30:50 -0400, mr_gadget wrote: > C:\>python -c "import os; print os.path.exists('C:\enhancement\rawfiles')" > > False > > C:\>python -c "import os; print os.path.exists('C:\\enhancement\\rawfiles')" > > True The backward slash has a special meaning in string literals. It is used to escape special character. One such sequence is '\r' which is *one* character, namely the return character. To insert *one* backslash it has to be protected by another backslash or the string literal may be prefixed by an 'r' to tell the compiler that backslashes have no special meaning in that raw string literal. In [23]: len('\r') Out[23]: 1 In [24]: len('\\') Out[24]: 1 In [25]: len(r'\r') Out[25]: 2 In [26]: len(r'\\') Out[26]: 2 Ciao, Marc 'BlackJack' Rintsch From silfheed at gmail.com Tue Aug 21 15:18:00 2007 From: silfheed at gmail.com (Silfheed) Date: Tue, 21 Aug 2007 19:18:00 -0000 Subject: Adjusting the names of custom exceptions (since raising strings is deprecated) In-Reply-To: <5qxyi.18719$eY.12647@newssvr13.news.prodigy.net> References: <1187672085.263963.157470@z24g2000prh.googlegroups.com> <5qxyi.18719$eY.12647@newssvr13.news.prodigy.net> Message-ID: <1187723880.146487.36250@l22g2000prc.googlegroups.com> On Aug 21, 1:32 am, James Stroud wrote: > Silfheed wrote: > > Heyas > > > So this probably highlights my lack of understanding of how naming > > works in python, but I'm currently using FailUnlessRaises in a unit > > test and raising exceptions with a string exception. It's working > > pretty well, except that I get the deprecation warning that raising a > > string exception is going to go away. So my question is, how do I > > mangle the name of my exception class enough that it doesnt stick the > > name of the module before the name of the exception? > > > Namely I'd like to get the following > > > *** > > Traceback (most recent call last): > > File "", line 1, in ? > > MyError: 'oops!' > > > instead of > > > *** > > Traceback (most recent call last): > > File "", line 1, in ? > > __main__.MyError: 'oops!' > > > (or even test_thingie.MyError as is usually the case). > > > Creating a class in a separate file and then doing > > > *** > > from module import MyError > > raise MyError > > > still gives > > > *** > > Traceback (most recent call last): > > File "", line 1, in > > module.MyError > > > Anyway, any help appreciated. > > Would it be cheating to use metaclasses? > > # myModule.py > class ExampleType(type): > def __repr__(cls): > return cls.__name__ > > class ExampleError(Exception): > __metaclass__ = ExampleType > __name__ = 'ExampleError' > def __repr__(self): > return 'ExampleError' > > py> import myModule > py> raise myMo > myModule myModule.py myModule.pyc myModule.py~ > py> raise myModule.Ex > myModule.ExampleError myModule.ExampleType > py> raise myModule.ExampleError > ------------------------------------------------------------ > Traceback (most recent call last): > File "", line 1, in > ExampleError > > James It doesnt appear to work for me. Same exact code as you have but I still get: >>> raise myModule.ExampleError Traceback (most recent call last): File "", line 1, in myModule.ExampleError From nospam at nowhere.com Fri Aug 17 20:55:47 2007 From: nospam at nowhere.com (DavidM) Date: 18 Aug 2007 12:55:47 +1200 Subject: python video editing libs Message-ID: <46c64393$1@news.orcon.net.nz> Hi, Does anyone know of any python or python-wrapped libs for video editing? My requirements: - open video files in any of the popular containers (avi, mov, ogg, flv etc) and all the popular codecs (mpeg3, theora, mpeg2 etc) and audio codecs (raw, wav, mp3 etc) - get an abstract video clip object on opening such a file - query the clip object to determine stuff like length, framerate, size etc - iterate through all the frames, and get a frame object with each frame - with a frame object, be able to access individual pixels, add graphic images (eg, via PIL), export frame to graphics file (eg jpeg) - with video clip object, be able to change framerate, insert/remove frames etc, and render out with desired a-v codecs and container - good well-documented API, preferably some usage examples Does anything like this exist? Cheers David From xmikedavis at gmail.com Fri Aug 24 17:06:21 2007 From: xmikedavis at gmail.com (garage) Date: Fri, 24 Aug 2007 21:06:21 -0000 Subject: Regular expression use In-Reply-To: References: Message-ID: <1187989581.752849.23840@m37g2000prh.googlegroups.com> I work in print (book) production and i regularly use regular expressions to parse .eps (encapsulated postscript) files for incorrect specifications (8-bit vs. ASCII, etc), bad fonts and the like. Just to ensure that what's been submitted to me will actually end up on the page. From steve at holdenweb.com Wed Aug 8 21:26:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 08 Aug 2007 21:26:51 -0400 Subject: Something in the function tutorial confused me. In-Reply-To: <5hv705F3mk67nU1@mid.individual.net> References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <1186424693.529497.217040@w3g2000hsg.googlegroups.com> <46B8626A.2070303@bigfoot.com> <5hsoi3F3mlni2U1@mid.individual.net> <5hv705F3mk67nU1@mid.individual.net> Message-ID: greg wrote: > Steve Holden wrote: > >> For some reason your reply got right up my nose, > > I'm sorry about that. Sometimes it's hard to judge the > level of experience with Python that a poster has. In > discussions about this particular topic, often it turns > out that the person is a newcomer to Python who is > using the wrong mental model of assignment, and your > comment about None being immutable suggested that this > is what was going on. If I was mistaken about that, > then I apologise. > No worries. I've been subjected to far worse. > While it may not have been what you meant, what you > *seemed* to be saying is that the result of a (plain) > assignment somehow depends on what was previously > bound to the name being assigned. I was just trying > to point out that this is not true. > I must have expressed myself badly, then. > The reason I suggested trying an example is that it > can be hard to talk about these things clearly when > you're not sure whether the words you're using, such > as "assignment", mean the same thing to the person > on the other end. The interpreter always interprets > things unambiguously. > Sure. Don't worry, I was pretty sure it was as much me as you. Otherwise I'd doubtless have been more obnoxious :-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From cjankowski at hbr-inc.com Tue Aug 7 10:09:07 2007 From: cjankowski at hbr-inc.com (cjankowski at hbr-inc.com) Date: Tue, 07 Aug 2007 07:09:07 -0700 Subject: RTF 2 Tiff In-Reply-To: References: <1186427712.284976.207560@d30g2000prg.googlegroups.com> Message-ID: <1186495747.958628.198070@g12g2000prg.googlegroups.com> On Aug 6, 4:04 pm, Larry Bates wrote: > cjankow... at hbr-inc.com wrote: > > Hi all, > > I am trying to convert an RTF file to a Tiff image using Python. This > > process will convert several hundred images daily. Currently I am > > able to get the RTF file into a text format using Rtf2Txt.py, but I > > loose the images contained in the RTF file. I have the same problem > > when I convert to .HTML using Rtf2Html.py. I do not have a sample > > that I can share because of HIPPA regulations. Can anyone please help > > me? > > > Thanks, > > > Chris J. > > Google turns up lots of solutions, but you didn't tell us what operating system > you are running on. Most likely you will want to automate one of the off-the > shelf solutions rather than trying to roll your own. > > -Larry We are running Windows Operating Systems. I was not able to find anything that actually would convert the images via command line or interface. I tried a couple of boxed solutions and they only convert the text portions. I would perfer to not reinvent the wheel. I did find someone has created RTF's using Python and images, but I need to reverse the process. Thanks again, Chris J. From horpner at yahoo.com Wed Aug 22 08:29:24 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 22 Aug 2007 12:29:24 GMT Subject: for statement on empty iterable References: <1187760507.951994.50310@q4g2000prc.googlegroups.com> <7xabsk3zgm.fsf@ruckus.brouhaha.com> <1187761270.713307.224570@i38g2000prf.googlegroups.com> <7xejhw15r9.fsf@ruckus.brouhaha.com> <1187761957.636211.107060@x40g2000prg.googlegroups.com> <7xd4xgnldp.fsf@ruckus.brouhaha.com> <1187765372.361411.249990@z24g2000prh.googlegroups.com> <5j2679F3s7lbpU1@mid.uni-berlin.de> Message-ID: On 2007-08-22, Diez B. Roggisch wrote: > While it is desireable to not only write working, but also > aesthetically pleasing code, as a beginner you shouldn't worry > too much. The sense of aesthetics develops with time. Important > is to try and grasp the idioms of the language, around here > ofter referred to as "beeing pythonic." It's hard to keep up with the new buzzwords that keep popping up in this group. -- Neil Cerutti A billion here, a billion there, sooner or later it adds up to real money. --Everett Dirksen From grahn+nntp at snipabacken.dyndns.org Sun Aug 12 16:18:54 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 12 Aug 2007 20:18:54 GMT Subject: Querying Graphics Card Name References: <1186686984.160312.175270@i13g2000prf.googlegroups.com> <5i1f4cF3mbqqdU1@mid.individual.net> <1186696734.059152.131080@d30g2000prg.googlegroups.com> Message-ID: On Thu, 09 Aug 2007 21:58:54 -0000, Benjamin Goldenberg wrote: > On Aug 9, 3:26 pm, Bjoern Schliessmann mail-0306.20.chr0n... at spamgourmet.com> wrote: >> Benjamin Goldenberg wrote: >> > I would like to find out the name of the graphics card of the >> > machine my program is running on. I have looked into the pyopengl >> > module, and using them to query the card, but it seems like there >> > ought to be a simpler way to find this out without setting up a >> > glcontext. Does anyone have any ideas? >> >> You could execute glxinfo and look for the renderer string. If >> that's sharp enough for your purpose. Another option is lspci. > > I should have clarified. I would like a cross platform implementation, > Windows and *nix. It doesn't seem as if glxinfo is available under > Windows, at least not without installing X11 under cygwin. If > necessary, I can write the *nix and Windows queries separately. Yeah, but ... - what if there isn't one? - what if there are several? - what if there *is* one, but your user is sitting by a remote machine, not using the card at all? Your method will, no matter how you choose, fail sooner or later, so you'd better plan for that. What is your reason to do this, by the way? Remember what Homer Simpson said: if something appears to be hard, it is simply not worth doing. And I mean that semi-seriously. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From Shawn at Milochik.com Tue Aug 14 13:46:48 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Tue, 14 Aug 2007 13:46:48 -0400 Subject: Opinions about this new Python book? In-Reply-To: <8a6b8e350708141020q495b22der4c362ee3df618d82@mail.gmail.com> References: <1187096231.194685.86030@m37g2000prh.googlegroups.com> <20070814154913.D8C3C1E400A@bag.python.org> <8a6b8e350708141020q495b22der4c362ee3df618d82@mail.gmail.com> Message-ID: <2dc0c81b0708141046p5006c2d1l35e50c0baf91069d@mail.gmail.com> Yes, please post back to the list. I saw this book on Amazon, but there's no table of contents listed, nor is there one on the publisher's site. Thanks, Shawn On 8/14/07, James Matthews wrote: > i got to say that the best python book i bought was Core Python Programming > (2nd) by Wesly Chun! Aside for all the spelling mistakes and syntax errors > that there are i feel that the book really explained the language well for > someone coming from another programming language! > > > On 8/14/07, Dick Moores wrote: > > At 05:57 AM 8/14/2007, kyosohma at gmail.com wrote: > > >On Aug 14, 7:05 am, Dick Moores wrote: > > > > I'd appreciate opinions about this new Python book. > > > > > > > > Title: Python Power!: The Comprehensive Guide > > > > Author: Matt Telles > > > > Publisher: Course Technology > > > > Pub. Date: Jul 27, 2007 > > > > Edition: 1st edition > > > > Binding: Paperback > > > > Pages: 508 > > > > ISBN: 1598631586 > > > > List Price: 34.99 USD > > > > > > > > The book on the publisher's website: < http://tinyurl.com/2dkhzg> > > > > > > > > And at BestBookDeal.com: > > > > > > > > > > > > Thanks, > > > > > > > > Dick Moores > > > > > >I just got this book over the weekend. I'll start reading/skimming > > >through it this week and hopefully remember to get back to you. > > > > Thanks! > > > > > By the > > >way, why do you want to know? > > > > If the experts like it, I'll buy it. > > > > Dick > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > http://www.goldwatches.com/ > http://www.jewelerslounge.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- Please read: http://milocast.com/2007/07/31/this-i-believe/ From aleax at mac.com Thu Aug 30 22:20:24 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 30 Aug 2007 19:20:24 -0700 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> Message-ID: <1i3o9kr.2gmni61g62moaN%aleax@mac.com> Russ wrote: ... > programs." Any idea how much Python is used for flight control systems > in commercial > transport aircraft or jet fighters? Are there differences in reliability requirements between the parts of such control systems that run on aircraft themselves, and those that run in airports' control towers? Because Python *IS* used in the latter case, cfr ... if on-plane control SW requires hard-real-time response, that might be a more credible reason why Python would be inappropriate (any garbage collected language is NOT a candidate for hard-real-time SW!) than your implied aspersions against Python's reliability. According to , Google's current uptime is around 99.99%, with many months at 100% and a few at 99.98% -- and that's on *cheap*, not-that-reliable commodity HW, and in real-world conditions where power can go away, network cables can accidentally get cut, etc. I'm Uber Tech Lead for Production Systems at Google -- i.e., the groups I uber-lead are responsible for some software which (partly by automating things as much as possible) empowers our wondrous Site Reliability Engineers and network specialists to achieve that uptime in face of all the Bad Stuff the world can and does throw at us. Guess what programming language I'm a well-known expert of...? > The important question is this: why do I waste my time with bozos like > you? Yeah, good question indeed, and I'm asking myself that -- somebody who posts to this group in order to attack the reliability of the language the group is about (and appears to be supremely ignorant about its use in air-traffic control and for high-reliability mission-critical applications such as Google's "Production Systems" software) might well be considered not worth responding to. OTOH, you _did_ irritate me enough that I feel happier for venting in response;-) Oh, FYI -- among the many tasks I undertook in my quarter-century long career was leading and coordinating pilot projects in Eiffel for one employer, many years ago. The result of the pilot was that Eiffel and its DbC features didn't really let us save any of the extensive testing we performed for C++-coded components, and the overall reliability of such extensively tested components was not different in a statistically significant way whether they were coded in C++ or Eiffel; Eiffel did let us catch a few bugs marginally earlier (but then, I'm now convinced that, at that distant time, we used by far too few unit-tests for early bug catching and relied too much on regression and acceptance tests), but that definitely was _not_ enough to pay for itself. DbC and allegedly rigorous compile-time typechecking (regularly too weak due to Eiffel's covariant vs countervariant approach, btw...), based on those empirical results, appear to be way overhyped. A small decorator library supporting DbC would probably be a nice addition to Python, but it should first prove itself in the field by being released and supported as an add-on and gaining wide acceptance: "arguments" such as yours are definitely NOT going to change that. Alex From kyosohma at gmail.com Thu Aug 2 10:24:45 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 02 Aug 2007 14:24:45 -0000 Subject: backup/restore postgresql database In-Reply-To: <1186037711.895840.240250@g4g2000hsf.googlegroups.com> References: <1186037711.895840.240250@g4g2000hsf.googlegroups.com> Message-ID: <1186064685.670910.160470@x40g2000prg.googlegroups.com> On Aug 2, 1:55 am, Acm wrote: > I am working with Python 2.5 and Postgresql 8.2.4. > > I would like to know how to perform the backup and restore operations > on postgresql through a python API (e.g. psycopg2). > > Thank you. I don't know much about postgres, but here's what my google-fu turned up: http://www.koders.com/python/fidF98B0B88C167C4B9862D8EF6C0CC9BAAC33718DB.aspx?s=cdef%3Aparser http://python.projects.postgresql.org/ http://pypgsql.sourceforge.net/ http://www.pygresql.org/ You can probably use the subprocess module to connect to it and use the pg_dump command as well that is documented here: http://www.postgresql.org/docs/8.1/static/backup.html Mike From jstroud at mbi.ucla.edu Wed Aug 15 17:36:01 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 15 Aug 2007 14:36:01 -0700 Subject: encrypting files + filestreams? In-Reply-To: <1187186797.579680.206820@19g2000hsx.googlegroups.com> References: <1187186797.579680.206820@19g2000hsx.googlegroups.com> Message-ID: per9000 wrote: > Also I wonder if this can be solved with filestreams (Are there > streams in python? The only python file streams I found in the evil > search engine was stuff in other forums.) Check the source to: http://passerby.sf.net In it you will find the jenncrypt module that makes a file-like wrapper around streams for encrypting and handles padding, etc. It is designed for a block cipher. This is not a trivial task, actually, but all the code is in there. It is not intensely well documented. It is somewhat well organized but this was my first full size attempt at a python application. Please read the notes to the "SecureRandom" module inside if you decide to use that module as the "name is misleading" under certain circumstances. It is used for the padding, although the randomness of the padding in a block cipher is in principle not a practical security issue in most cases. Other than the pad generation, the encryption algorithm is drop-in and I use the pycrypto implementation of AES. Read at least Schneier if you want to get started with such things as there are many caveats to using cryptographic systems. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From kw at codebykevin.com Sun Aug 19 08:47:34 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Sun, 19 Aug 2007 08:47:34 -0400 Subject: Hot subject: a good python editor and/or IDE? In-Reply-To: References: Message-ID: <93cf5$46c83bee$4275d90a$26606@FUSE.NET> S?bastien wrote: > Hi folks, > > I am currently using Eclipse+PyDev when developping Python projects but > I lack a fast, simple editor for tiny bit of scripts. So here is my > question: what is, for you, the current best ( but still kind of light! > ) Python editor/IDE ? A tiny precision, I am on Ubuntu so I am looking > for a linux compatible editor. > > Cheers, > > S?bastien IDLE -- Kevin Walzer Code by Kevin http://www.codebykevin.com From grflanagan at yahoo.co.uk Tue Aug 21 06:49:09 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: Tue, 21 Aug 2007 03:49:09 -0700 Subject: C# and Python In-Reply-To: <1187690505.903506.79690@d55g2000hsg.googlegroups.com> References: <1187690505.903506.79690@d55g2000hsg.googlegroups.com> Message-ID: <1187693349.890687.203900@50g2000hsm.googlegroups.com> On Aug 21, 12:01 pm, subeen wrote: > Hi, > I am a newcomer in Python. I am going to write a small Python > application that will run in windows xp. This application needs to > have GUI. Is it possible to make a C# application using visual studio > 2005 that will call the python scripts? Let me explain more here: > My program will generate a text file of 100 - 100000 random integers, > and sort those using various sorting methods. Now I have written > separate sorting scripts in Python (quick sort, insertion sort etc.). > But I want to write the GUI and number generation program in C#.net. > When the user clicks Quick Sort button, the quicksort.py will be > called and it will sort the numbers. > If you just want to capture the stdout of a script then you can use the System.Process and System.ProcessInfo classes. An example is here: http://gflanagan.net/site/dotnet/vsto/run_python_script_from_word.html HTH Gerard From dickinsm at gmail.com Thu Aug 30 16:36:20 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 30 Aug 2007 20:36:20 -0000 Subject: Biased random? In-Reply-To: References: Message-ID: <1188506180.227794.20030@q5g2000prf.googlegroups.com> On Aug 30, 3:55 pm, Ivan Voras wrote: > I've noticed something interesting in my test: the value 0 appears less > often than other values (which behave as they should). That's because the call to abs() usually collapses two values to one (e.g. -2 and 2 both end up being 2), but there's only one integer n for which abs(n) == 0. One possible fix: do x = randint(0, 10) - randint(0, 10) x = abs(x) - (x<0) This collapses -1 and 0 to 0, -2 and 1 to 1, etc. Mark From atkedzierski at gmail.com Fri Aug 17 10:33:16 2007 From: atkedzierski at gmail.com (AndrewTK) Date: Fri, 17 Aug 2007 14:33:16 -0000 Subject: Getting the result of a process after exec*() Message-ID: <1187361196.184025.234020@k79g2000hse.googlegroups.com> Hi, I am trying to write a Python script that takes a ZIP file from a web form (using CGI) and uses either of the UN*X unzip, gunzip, tar, bunzip2 utilities to expand it. I can use Python to save the script to disk; but processing it is another matter. If for example I have received a *.tar.gz file, I need to first pass it through gunzip; then through the tar utility. I also want to process the resulting directory. The problem for me is this: once an external process is called via exec*() the script has effectively fulfilled its task. Is there any way one can process a file with an external process and continue further processing in Python; /once the external processing is completed/? Many thanks, Andrew From tdelaney at avaya.com Mon Aug 6 23:50:46 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 7 Aug 2007 11:50:46 +0800 Subject: All leading tabs or all leading spaces - why isn't that enforced? In-Reply-To: Message-ID: John Nagle wrote: > One can argue over tab vs. space indentation, but mixing the two > is just wrong. Why not have CPython report an error if a file has > both leading tabs and leading spaces? I know that was proposed at > some point, but I don't think it ever went in. That would catch a > common error introduced during maintenance. To warn about mixed tabs and spaces: python -t > > http://www.2shared.com/download/1716611/e2000f22/ > Jadeed_Mlak14.3gp?tsid=20070803-164051-9d637d11"sfgsfgsfgv > > I use this pattern : > "http.*?\.(wmv|3gp).*"" > > but it returns only 'wmv' and '3gp' instead of "http://www.2shared.com/ > download/1716611/e2000f22/Jadeed_Mlak14.wmv? > tsid=20070803-164051-9d637d11" > > what can I do? what's wrong whit this pattern? thanx for your comments You could use r'window.location = "(.*?\.(wmv|3gp)";' as your regex string, I guess.. From http Fri Aug 3 22:01:04 2007 From: http (Paul Rubin) Date: 03 Aug 2007 19:01:04 -0700 Subject: How to pass a reference to the current module References: Message-ID: <7xtzrg3vof.fsf@ruckus.brouhaha.com> James Stroud writes: > Module Behavior > ============== ==================================================== > UserDefined1 Imports FunctionUser > ThirdParty Contains User Functions (May be ==UserDefined1) > FunctionUser do_something_with() and/or get_function_from_name() > > So the name-to-function mapping is done in FunctionUser but the > function is actually defined in UserDefined1 (or ThirdParty if > ThirdParty is different than UserDefined1). I'm still completely confused. Does FunctionUser know what module the user functions are supposed to come from? Could you give an example of what you want the actual contents of those 3 modules to look like? E.g.: UserDefined1.py: import FunctionUser def foo(x): print x+3 FunctionUser.py: def do_something_with (module, funcname, *args, **kw): func = getattr(module, funcname) func (*args, **kw) main.py: import UserDefined1, FunctionUser # the following should print 10 FunctionUser.do_something_with(UserDefined1, 'foo', 7) I don't think the above is quite what you want, but is it somewhere close? From jzgoda at o2.usun.pl Thu Aug 2 10:34:35 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 02 Aug 2007 16:34:35 +0200 Subject: Determining if file is valid image file In-Reply-To: <1186064275.652416.250540@d55g2000hsg.googlegroups.com> References: <1186064098.587590.91210@g4g2000hsf.googlegroups.com> <1186064275.652416.250540@d55g2000hsg.googlegroups.com> Message-ID: Andr? napisa?(a): >> Other than installing PIL, is there a "simple" way using Python only >> to determine if a file is a valid image file? >> >> I'd be happy if I could at least identify valid images files for gif, >> jpeg and png. Pointers to existing modules or examples would be >> appreciated. >> >> The reason why I'd prefer not using PIL is that I'd like to bundle >> such a function/module in my app. >> >> Andr? > > I should have added: I'm interesting in validating the file *content* > - not the filename :-) Is the module imghdr enough for your needs? -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From fabioztessitore at libero.it Sun Aug 12 14:18:32 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 12 Aug 2007 18:18:32 GMT Subject: who is simpler? try/except/else or try/except References: <46bf4074$0$10626$4fafbaef@reader2.news.tin.it> Message-ID: <46bf4ef8$0$10626$4fafbaef@reader2.news.tin.it> Il Sun, 12 Aug 2007 20:06:23 +0200, Peter Otten ha scritto: [cut] > at the same time introducing the implicit > constraint that the latter does not fail with . > Therefore the original code gives the reader a much clearer notion of > the author's intention. This may not be a problem for the simple code > at hand but is definitely a bad habit to get into. > thanks Peter, that's the kind of opinion I'm interesting to. bye Fabio From f.guerrieri at gmail.com Thu Aug 23 09:41:04 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Thu, 23 Aug 2007 15:41:04 +0200 Subject: Joining elements in a list to 1 element In-Reply-To: <46CD8ABC.9080407@sdf.lonestar.org> References: <79b79e730708230343t5e2ec45dx9d334bbf48b75e55@mail.gmail.com> <46CD8ABC.9080407@sdf.lonestar.org> Message-ID: <79b79e730708230641l33a9afebi59e8bc5ab38907b8@mail.gmail.com> On 8/23/07, J. Cliff Dyer wrote: > > What do you want to have happen in this case? > > my_list = [ 'a', 4, 'c' ] > It depends on the requirements of the OP. A possible solution could be: my_second_list = [] try: my_second_list.append("".join(my_list)) except TypeError: my_second_list.append("".join(str(item) for item in my_list) ) But it depends on the the actual requirements, maybe it isn't meaningful for the original list to contain numbers (think for instance of nucleotide sequences...?) Francesco -------------- next part -------------- An HTML attachment was scrubbed... URL: From rajingwei at gmail.com Tue Aug 28 04:18:37 2007 From: rajingwei at gmail.com (baby's happy) Date: Tue, 28 Aug 2007 01:18:37 -0700 Subject: Biased random? In-Reply-To: References: <13d6i72s8b2a3ad@corp.supernews.com> <46D34ECF.8060106@sdf.lonestar.org> Message-ID: <1188289117.351952.39300@e9g2000prf.googlegroups.com> I saw your article is very good, I like it very much. I will continue to pay attention to your article, the following are the points I hope that I have similar concerns. http://www.game-win.com http://www.game-win.com/wow-powerleveling.html http://www.game-win.com/faq.html http://www.game-win.com/power-leveling.html http://www.game-win.com/World-of-Warcraft-power-leveling.html http://www.paper-cup-machine.com http://www.sinceremachine.com http://www.clickra.com http://www.clickra.com/NewsList_2.htm http://www.east163.com http://www.ruian2machine.cn http://www.rajayj.cn http://www.mycvcv.com http://www.dgajm.com http://www.icansee.cn http://www.icansee.cn/chanpin.htm http://www.pjwsdyb.com http://www.shdyf.com http://www.nonwoven-bags.cn http://www.plastic-thermoforming-machine.com http://www.gopowerlevel.com From kyosohma at gmail.com Fri Aug 17 10:14:09 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 17 Aug 2007 07:14:09 -0700 Subject: Question on SPE and pwintypes.dll In-Reply-To: <1187357898.740425.33170@r29g2000hsg.googlegroups.com> References: <1187357898.740425.33170@r29g2000hsg.googlegroups.com> Message-ID: <1187360049.391743.9980@l22g2000prc.googlegroups.com> On Aug 17, 8:38 am, Gerry wrote: > I'm running SPE 8.3.c under XP, on a new PC. > > The files for SPE and Python were copied to the new machine, but > the OS wasn't migrated, so the registry didn't know about either. > > I reinstalled Python 2.5.1, and Python seems fine. > > I made a shortcut to SPE.pyw. Clicking on the shortcut gives an > error pop-up, application failed to start cannot find pwintypes.dll. > When I click "OK", SPE seems to start normally. > > Any idea what's up? Googling for pwintypes.dll didn't give me any > hits. > > Gerry Probably just need to do a search in the registry of the old PC for SPE or that dll file and then make the appropriate changes on your new PC. Or just reinstall SPE. Mike From paddy3118 at googlemail.com Fri Aug 31 16:24:15 2007 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 31 Aug 2007 20:24:15 -0000 Subject: OT: pronounciation [was: list index()] In-Reply-To: References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188497498.3468.60.camel@dot.uniqsys.com> <0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net> <1188551958.728836.137370@x35g2000prf.googlegroups.com> <46D7E36D.4000301@timgolden.me.uk> Message-ID: <1188591855.327294.181280@r34g2000hsd.googlegroups.com> On Aug 31, 11:19 am, Tim Golden wrote: > Tim Golden wrote: > > Erik Max Francis wrote: > >> Paddy wrote: > > >>> I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll > >>> and role similarly. > > >>> My accent is probably from the East Midlands of the UK, but is not > >>> pronounced. > >> _Troll_ and _frolic_ aren't pronounced with the same "o" sound in any > >> accent I've ever heard of. Which you pronounce _boat_ and _bot_ the > >> same way, too? > > > [Amusingly contemplating a trolling war about the pronunciation of "troll"] > > > Well they sound the same in my more-or-less South London accent. > > I can't write those funny phonetic symbols (and I hate to > > imagine the Unicode encoding hoops I'd have to jump through > > to make them readable anyway) but both "o"s sound short to me. > > Like "bot" rather than "boat" using your example. > > Since we're talking... I'm still a little startled when I listen > to some of the excellent webcasts that are being produced these > days (showmedo.com and friends) and hear American voices pronounce > Python... well, the way they do, with the stress and something of a > drawl on the second syllable. I'm sure it's just as amusing the other > way round: we pronounce it with the stress on the first syllable and > the characteristic short vowel sound in the second. > (Something like: Pie'thun). > > TJG The only true way of pronouncing Python (the computing language), is the way it is done at the beginning of Monty Pythons Flying Circus of course :-) Your right, the American way does make me pause. - Paddy. From jstroud at mbi.ucla.edu Tue Aug 21 00:00:05 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 20 Aug 2007 21:00:05 -0700 Subject: Retrieving a variable's name. In-Reply-To: <1187658202.236626.93600@50g2000hsm.googlegroups.com> References: <1187658202.236626.93600@50g2000hsm.googlegroups.com> Message-ID: rodrigo wrote: > How would I go about retrieving a variable's name (not its value)? I > want to write a function that, given a list of variables, returns a > string with each variable's name and its value, like: > > a: 100 > b: 200 > > I get the feeling this is trivial, but I have been unable to find an > answer on my own. > > Thanks, > > Rodrigo > Use a dict as that is what you access when you use namespaces anyway: py> type(globals()) The essential problem with what you suggest is that python assigns names to references to objects, so the interpreter can not tell what name you want by a reference to the object, so it gives you whatever name it happens to find, which, since the names are keys to a dict, come in arbitrary order. For example, consider this situation: py> a = 4 py> b = a py> ns = globals() py> for avar in a,b: ... for k,v in ns.items(): ... if v is avar: ... print '%s is %s' % (k,v) ... break ... avar is 4 avar is 4 So getting at the names by reference to thee objects will never be dependable. Passing names makes more sense: py> for aname in ['a', 'b']: ... print '%s is %s' % (aname, globals()[aname]) ... a is 4 b is 4 But this is tantamount to using a dict: py> mydict = {'a':4, 'b':2} py> for aname in ['a', 'b']: ... print '%s is %s' % (aname, mydict[aname]) ... a is 4 b is 2 Which is preferred because it keeps your namespaces cleaner. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From no.email.here at zombo.com Wed Aug 29 16:49:59 2007 From: no.email.here at zombo.com (Moon) Date: Wed, 29 Aug 2007 20:49:59 GMT Subject: Short, crazy example: list-derived class, with __iadd__ Message-ID: class Vec(list): def __init__(self): list.__init__(self, [0.0, 0.0]) def __iadd__(self, other): assert isinstance(other, Vec) self[0] += other[0] self[1] += other[1] print "right now, v is: ", self, " as you'd expect" v = Vec() w = Vec() w[0] = 1.0 w[1] = 2.0 print "v starts:", v print "(w is:", w, " which is fine)" v += w print "(w still is:", w print "after iadd, v: ", v, " <-- becomes None! What the hey?" # - running it: py> python badvec.py v starts: [0.0, 0.0] (w is: [1.0, 2.0] which is fine) right now, v is: [1.0, 2.0] (w still is: [1.0, 2.0] later, v is: None <-- becomes None! What the hey? py> python -V Python 2.5.1 -- Any explanation from a guru? Thanks much... From see at signature.invalid Mon Aug 27 19:22:35 2007 From: see at signature.invalid (Douglas Wells) Date: Mon, 27 Aug 2007 19:22:35 -0400 (EDT) Subject: Socket - gaierror References: <1188242671.182072.130150@r23g2000prd.googlegroups.com> <1188244050.029920.314700@i13g2000prf.googlegroups.com> Message-ID: In article <1188244050.029920.314700 at i13g2000prf.googlegroups.com>, half.italian at gmail.com writes: > On Aug 27, 12:32 pm, Larry Bates wrote: > > Changing it to IP gives me the same exact error... > > File "bin/prgram.py", line 123, in notify > smtp = smtplib.SMTP("XXX.XXX.XXX.XXX") > > File "/usr/lib/python2.4/smtplib.py", line 255, in __init__ > addr = socket.gethostbyname(socket.gethostname()) > > gaierror: (-2, 'Name or service not known') > > Looks like the smtp port is closed on the client machine...doh Should > have gotten to that! > > ~Sean Note that the lookup is of your *local* system name (socket.gethostname()). I suspect that the name of your client system (the one running the python script) is not registered in DNS. Try ping'ing your own system and see if that resolves in DNS. In UNIX/Linux you can use the hostname command; in any system you can write a python script to print the result of socket.gethostname(). - dmw -- . Douglas Wells . Connection Technologies . . Internet: -sp9804- -at - contek.com- . From bjourne at gmail.com Wed Aug 22 09:00:15 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 22 Aug 2007 15:00:15 +0200 Subject: advice about `correct' use of decorator In-Reply-To: <46C5C9AE.5020508@fmed.uba.ar> References: <46C4B097.4080309@fmed.uba.ar> <740c3aec0708170529s6f7e7fe2l8c92771c2d0a51d4@mail.gmail.com> <46C5C9AE.5020508@fmed.uba.ar> Message-ID: <740c3aec0708220600u7c01ca85kdddedfede9dac415@mail.gmail.com> On 8/17/07, Gerardo Herzig wrote: > BJ?rn Lindqvist wrote: > >def is_logued_in(): > > if not user.is_logged_in(): > > raise NotLoggedInError > > > >It costs you one more line, but reduces complexity. And if you are > >worried about that extra line you can put it in a function. > > > As far as i know (by the way, AFAK is the shortcut?, and BTW means `by > the way'? ), decorators are not indispensable. I mean, all that you can > do with python, you can doit without decorators. And from my point of > view, this hides the complexity for the other developers of my group, hiding is not the same thing as reducing. By hiding the code behind a decorator, you are increasing the complexity by adding another layer that the programmer has to look through to see your control flow. > since all they have to do is add the @is_logged_in line at the top of > the cgi script, and not to worrie about exceptions, not even how the > decorator is implemented (i may log the error in some file). All they > have to know is that any abnormal situation will redirect to the `login' > screen. As I said, you can accomplish the exact same thing by calling a function from within the function that requires the user to be logged in. def change_pass(): check_user_logged_in() ... more stuff here... is less complex (and therefore preferable) than: @check_user_logged_in def change_pass(): ... more stuff here... An important principle in engineering is that you should always strive to make your design as simple as possible. If you have two equal designs, you should always choose the one that is simpler because simple things are easier to understand than complex things. -- mvh Bj?rn From deets at nospam.web.de Sun Aug 19 14:43:42 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 19 Aug 2007 20:43:42 +0200 Subject: Latest models of Gibson guitars In-Reply-To: <1187548916.909340.37420@k79g2000hse.googlegroups.com> References: <1187544898.289948.322160@22g2000hsm.googlegroups.com> <1187548916.909340.37420@k79g2000hse.googlegroups.com> Message-ID: <5irhb9F3qrs2kU1@mid.uni-berlin.de> > Hello, > > This is a newsgroup of programming language Python, stop with this! And by fully citing the message including the links, you increase the visibility of the spammers site. Don't do that. Diez From bj_666 at gmx.net Wed Aug 29 12:40:46 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 29 Aug 2007 16:40:46 GMT Subject: general function for sorting a matrix References: <1188402447.290663.307640@z24g2000prh.googlegroups.com> Message-ID: <5jllseF6oarU1@mid.uni-berlin.de> On Wed, 29 Aug 2007 08:47:27 -0700, Xah Lee wrote: > While reviewing this code, there's something interesting of note. > > Namely, in my perl solution, the approach is drastically different > than the python version. Instead of sorting by looping thru the > sorting directives, it parses the directives then generate the > complete sort code, then eval it in one shot. This is more of a pure > functional approach. I don't see why that is more functional. After all you iterate in both versions through the directives. In Perl to build the code, in Python to sort the list multiple times. Here's a Python function that sorts the list just once: def sort_matrix(matrix, directives): tmp = [(column - 1, str if as_string else float, 1 if ascending else -1) for (column, as_string, ascending) in directives] def cmp_func(row_a, row_b): for column, convert_func, factor in tmp: result = cmp(convert_func(row_a[column]), convert_func(row_b[column])) * factor if result: return result return 0 matrix.sort(cmp=cmp_func) There's no return value as your reference implementation sorts in place too. Ciao, Marc 'BlackJack' Rintsch From jstroud at mbi.ucla.edu Mon Aug 20 00:31:41 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 19 Aug 2007 21:31:41 -0700 Subject: popen4 not returning output In-Reply-To: <1187582318.054450.76960@z24g2000prh.googlegroups.com> References: <1187582318.054450.76960@z24g2000prh.googlegroups.com> Message-ID: hortitude at gmail.com wrote: > I am trying to run the following script: > > > #!/usr/bin/python > > import popen2 > > commandToRun = """scp scp_trial.py user at host:/targetDirectory""" > #commandToRun = "ls" > print commandToRun > p_out, p_in = popen2.popen4 (commandToRun) > > theOut = p_out.readlines () > print theOut > > > When I run this command with the "ls" command I see the output. > When I run this with the scp command I do not see the output of my > command -- however the file is successfully transfered. How can I see > the output? > > Thanks > I'm not up on my scp, but look at popen3 and read from err. James From jecarnell at saintfrancis.com Mon Aug 27 10:48:46 2007 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Mon, 27 Aug 2007 09:48:46 -0500 Subject: Image.open( "C:\test.jpg") is this wrong ? Message-ID: > I am trying to simply open an image with PIL... My problem is that I > don't know what my active directory is so I am putting an absolute > path name in quotes. It can't find the specified file or directory. > I'm horrible with docs. I also tried to save an image file (to find > where it saved it, but I didn't understand what mode is (I now know it > is RGB etc.). Does everyone usually do fairly well with the docs > except for me??? For instance, it says Image.open(file, ...something > else [I'm at work so I don't remember]). How am I supposed to know > even to put quotes around the filepath? I'm really starting to wonder > if there is something wrong with me. > > So How do I open an image? > > Image.open("C:\test.jpg") # this is what I have right now. And it > can't find the file or directory. The file is there (it is everywhere > on my computer now!!!) > I found some code where they apply the file path to a variable in single quotes. Is that how it is done. Also I thought single quotes were for characters not strings. > Sincerely, > > James Carnell > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From zentraders at gmail.com Wed Aug 22 14:20:18 2007 From: zentraders at gmail.com (Zentrader) Date: Wed, 22 Aug 2007 11:20:18 -0700 Subject: Free Air Conditioners!!!!!! In-Reply-To: References: <1187738115.972271.94080@r23g2000prd.googlegroups.com> Message-ID: <1187806818.490520.231690@e9g2000prf.googlegroups.com> On Aug 21, 10:13 pm, "Scott M." wrote: > Oh my God! How did you know?!! You were so smart to post that here! > > wrote in message > > news:1187738115.972271.94080 at r23g2000prd.googlegroups.com... > > >http://freeairconditioners.blogspot.com/ It's probably a handheld fan made out of a piece of paper From istvan.albert at gmail.com Wed Aug 8 10:07:46 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Wed, 08 Aug 2007 14:07:46 -0000 Subject: Misleading wikipedia article on Python 3? In-Reply-To: <41Dti.37401$G23.10727@newsreading01.news.tds.net> References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <7xzm15q8fy.fsf@ruckus.brouhaha.com> <41Dti.37401$G23.10727@newsreading01.news.tds.net> Message-ID: <1186582066.096793.14700@57g2000hsv.googlegroups.com> On Aug 6, 6:49 am, Neil Cerutti wrote: > Incidentally, from the second link I find it shocking that the > keyword parameter "file" shadows a builtin. It seems to endorse a > bad practice. I believe that the "file" builtin has been removed as well so it won't shadow anything. i. From info at egenix.com Wed Aug 22 08:59:03 2007 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Wed, 22 Aug 2007 14:59:03 +0200 Subject: ANN: eGenix mxODBC Distribution 3.0.1 (mxODBC Database Interface) Message-ID: <46CC3317.3070305@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com mxODBC Database Interface Version 3.0.1 Our commercially supported Python extension providing ODBC database connectivity to Python applications on Windows and Unix platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mxODBC-Distribution-3.0.1-GA.html ________________________________________________________________________ INTRODUCTION The mxODBC Database Interface allows users to easily connect Python applications to just about any database on the market today - on both Windows and Unix platforms in a highly portable and convenient way. This makes mxODBC the ideal basis for writing cross-platform database programs and utilities in Python. mxODBC is included in the eGenix.com mxODBC Distribution for Python, which is part of the eGenix.com mx Extension Series - a collection of professional quality software tools aimed at enhancing Python's usability in many important areas such as database connectivity, fast text processing, date/time processing and web site programming. The package has proven its stability and usefulness in many mission critical applications and various commercial settings all around the world. It's been used in production for almost 10 years now. * About Python: Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. * About eGenix: eGenix is a consulting and software product company focused on providing professional quality services and products to Python users and developers (http://www.egenix.com/). ________________________________________________________________________ NEWS mxODBC 3.0.1 is a patch-level release and includes the following updates: Enhanced SQL Server ODBC driver support: * work-around for using Unicode parameters together with cursor.executedirect() * bug-fix for cursor.stringformat setting when used with cursor.executedirect() * improved compatibility by using non-padding character binding codes Documentation: * added more documentation and an example of how to use the new connection and cursor error handlers. Error handlers were introduced in mxODBC 3.0.0 and allow for much greater control over how low-level errors in the interface are to be dealt with. For the full set of changes please check the mxODBC change log. ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/mxODBC/ IMPORTANT: In order to use the eGenix mxODBC package you will first need to install the eGenix mx Base package: http://www.egenix.com/products/python/mxBase/ ________________________________________________________________________ UPGRADING You are encouraged to upgrade to this latest mxODBC release, especially if you are using MS SQL Server as database server. Customers who have purchased mxODBC 3.0 licenses can download and install this patch-level release on top of their existing installations. The licenses will continue to work with version 3.0.1. Users of mxODBC 2.0 will have to purchase new licenses from our online shop in order to upgrade to mxODBC 3.0.1. You can request 30-day evaluation licenses by writing to sales at egenix.com, stating your name (or the name of the company) and the number of eval licenses that you need. We will then issue you licenses and send them to you by email. Please make sure that you can receive ZIP file attachments on the email you specify in the request, since the license files are send out as ZIP attachments. _______________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Aug 22 2007) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From duncan.booth at invalid.invalid Sun Aug 12 13:44:36 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Aug 2007 17:44:36 GMT Subject: Regular Expression Grouping References: <1186939262.144073.182450@z24g2000prh.googlegroups.com> Message-ID: linnewbie at gmail.com wrote: > Fairly new to this regex thing, so this might be very juvenile but > important. > > I cannot understand and why 'c' constitutes a group here without being > surrounded by "(" ,")" ? > >>>>import re >>>> m = re.match("([abc])+", "abc") >>>> m.groups() > ('c',) > > Grateful for any clarity. > The group matches a single letter a, b, or c. That group must match one or more times for the entire expression to match: in this case it matches 3 times once for the a, once for the b and once for the c. When a group matches more than once, only the last match is available, i.e. the 'c'. The matches against the a and b are discarded. Its a bit like having some code: x = 'a' x = 'b' x = 'c' print x and asking why x isn't 'a' and 'b' as well as 'c'. From gerdusvanzyl at gmail.com Sun Aug 26 12:47:02 2007 From: gerdusvanzyl at gmail.com (Gerdus van Zyl) Date: Sun, 26 Aug 2007 16:47:02 -0000 Subject: New UI Toolkit Message-ID: <1188146822.129605.160560@22g2000hsm.googlegroups.com> Hi I am halfway to a first release of a new GUI library for python. It will be cross platform and follows the Swing philosophy of user experience and interface fidelity above "but it doesn't look like windows!" (aside: neither does office 2007 or windowsmediaplayer). The library is built on top of CairoGraphics (cairographics.org) and currently has a rather stable backend for Win32 and experimental backends for GTK,Pyglet,pygame. I am also busy with an WYSIWYG designer ala visualstudio but have yet to decide on an serializable format leaning towards xul-alike without XBL. You can see a screenshot here: http://infireal.com/external/gradripper.png and a executable of a utility built using here: http://www.infireal.com/alpha (generates cairo/svg gradients from images) Please reply and let your thoughts be known. Is there a need for a new GUI library for python? From http Fri Aug 24 06:47:43 2007 From: http (Paul Rubin) Date: 24 Aug 2007 03:47:43 -0700 Subject: List Comprehension Question: One to Many Mapping? References: <1187929443.636690.287450@i13g2000prf.googlegroups.com> <7x8x81l9z3.fsf@ruckus.brouhaha.com> Message-ID: <7xlkc143ao.fsf@ruckus.brouhaha.com> Boris Borcic writes: > >> For example, if I have x=[ [1,2], [3,4] ] > >> > >> What I want is a new list of list that has four sub-lists: > >> > >> [[1,2], [f(1), f(2)], [3,4], [f(3), f(4)]] > > [[a, map(f,a)] for a in x] > > no, that one will be [[[1,2], [f(1), f(2)]], [[3,4], [f(3), f(4)]]] > eg two sublists instead of four. Oh ugh, I misread the original request and thought the extra brackets were there. I think the following works and is reasonably intuitive: from itertools import chain y = list(chain(*([a, map(f,a)] for a in x))) But the original request itself seems a bit weird. From seun.osewa at gmail.com Sat Aug 11 00:43:16 2007 From: seun.osewa at gmail.com (Seun Osewa) Date: Sat, 11 Aug 2007 04:43:16 -0000 Subject: The Future of Python Threading In-Reply-To: <1186802188.653072.236260@x40g2000prg.googlegroups.com> References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <1i2njyp.1o6yslqe7ff47N%luc@honk-honk.com> <1186782710.600889.245930@j4g2000prf.googlegroups.com> <1186802188.653072.236260@x40g2000prg.googlegroups.com> Message-ID: <1186807396.988368.201400@b79g2000hse.googlegroups.com> > I think I've heard Guido say the last attempt at removing the Global > Interpreter Lock (GIL) resulted in a Python that was much slower... What is it about Python that makes a thread-safe CPython version much slower? Why doesn'ttrue threading slow down other languages like Perl and Java? I'm thinking it might be the reference counting approach to memory management... but what do you guys think is the reason? From seb.buchoux at gmail.com Sun Aug 19 09:37:49 2007 From: seb.buchoux at gmail.com (=?ISO-8859-1?Q?Buchoux_S=E9bastien?=) Date: Sun, 19 Aug 2007 15:37:49 +0200 Subject: Hot subject: a good python editor and/or IDE? In-Reply-To: <5iqreuF3qanv6U1@mid.individual.net> References: <5iqreuF3qanv6U1@mid.individual.net> Message-ID: <46C847AD.50709@gmail.com> Bjoern Schliessmann wrote: > S?bastien wrote: > >> I am currently using Eclipse+PyDev when developping Python >> projects but I lack a fast, simple editor for tiny bit of scripts. >> So here is my question: what is, for you, the current best ( but >> still kind of light! ) Python editor/IDE ? >> > > vim > > BTW, this is an FAQ. Please look through the archives for many > threads with many, many IDEs. > > Regards, > > > Bj?rn > > Yeah, I know this is a FAQ, but, as you mention, there is a whole bunch of editors, every one of them being updated constantly (+ the new ones getting out). So I am quite sure that looking through the archives is THE solution since it will only reflect what people thought when question was asked. Just type "best Python editor" on Google and you will see that almost all hits are completely out of date. Fair enough though! ;) From horpner at yahoo.com Thu Aug 2 15:04:22 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 02 Aug 2007 19:04:22 GMT Subject: __call__ considered harmful or indispensable? References: Message-ID: On 2007-08-02, skip at pobox.com wrote: > I don't personally use __call__ methods in my classes, but I > have encountered it every now and then here at work in code > written by other people. The other day I replaced __call__ > with a more obvious method name, so now instead of executing > > obj(foo, bar, baz) > > the code in question is > > obj.execute(foo, bar, baz) > > In this case there was a bug. Depending on inputs, sometimes > obj initialized to a class, sometimes an instance of that > class. (I fixed that too while I was at it.) The problem was > that the use of __call__ obscured the underlying bug by making > the instance as well as the class callable. > > In this particular case it was clearly unnecessary and just > obfuscated the code. I'm wondering, are there some general > cases where __call__ methods of a user-defined class are simply > indispensable? In C++ they are called functors, and they are very useful as surrogate functions with state. I haven't seen them used in the same way in Python much, because Python has more immediate solutions to (most of) these problems. Here's a (somewhat goofy) example: class is_consecutive(object): def __init__(self, seed, compare=operator.lt): self.last_value = seed self.compare = compare def __call__(self, total, value): if total is False: return False lv = self.last_value self.last_value = value return self.compare(lv, value): a = range(15) >>> reduce(is_consecutive(0), a) True >>> reduce(is_consecutive(0), a + [1,2]) False It's been a while since I had to be in the STL mindset, so I couldn't think of a better example. -- Neil Cerutti This is not a book to be put down lightly. It should be thrown with great force. --Dorothy Parker From kyosohma at gmail.com Tue Aug 7 11:16:09 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 07 Aug 2007 08:16:09 -0700 Subject: Tkinter or wxpython? In-Reply-To: References: <7xlkcopu4r.fsf@ruckus.brouhaha.com> <7x7io8r6na.fsf@ruckus.brouhaha.com> Message-ID: <1186499769.560806.295660@x35g2000prf.googlegroups.com> On Aug 7, 9:00 am, cla... at lairds.us (Cameron Laird) wrote: > In article <7x7io8r6na.... at ruckus.brouhaha.com>, > Paul Rubin wrote: > . > . > . > > > > >I should also add: there is also the possibility of running a Python > >program with an embedded http server on the same desktop as the > >browser, using the browser purely as a gui, but with the Python > >program having complete access to the file system and so forth. This > >could be seen as combining the disadvantages of both the remote web > >server approach (i.e. gui elements constrained by the browser) and the > >all-desktop approach (deployment issues). However, a lot of the time > >it's still just plain easier to do. Whenever I've written a desktop > >gui app I've always just been shocked at how much time goes into > >making the gui look decent and do the right stuff, even though none of > >mine have been even slightly slick (they've all been for industrial > >applications). When I do a web gui, it's been just a matter of > >tossing some html into a file or into some print statements, viewing > >it in a browser, and tweaking it a little as needed. Maybe that's > >mostly a matter of the lousy state of gui toolkits, and we actually > >need a toolkit that's more like an embedded browser. But we don't > >have that at the moment. > > One key to Tkinter's longevity lurks there. While > many whine about the antiquity of the appearance of > Tkinter's widgets, they have the virtue of sensible > defaults; more than any other toolkit, Tkinter comes > up with minimal refinements in a sensible and > consistent state. While those with an artistic eye > assure me the simplest Tkinter programs look worse > that corresponding ones built with any other toolkit, > they behave the most coherently in regards to resizing > and so on. I am curious. What are these "sensible defaults" that you mention? If you set up a wxPython program's sizers appropriately, the program should resize logically. But I think Tkinter is a little bit easier in that respect. However, you can get pretty granular in how you want items to behave in wxPython that you may not be able to do in Tkinter. I just don't know. I've used both, so I'm interested in hearing your opinion. Mike From horpner at yahoo.com Tue Aug 14 08:03:55 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 14 Aug 2007 12:03:55 GMT Subject: Module imports during object instantiation References: <4c3vo4-u7k.ln1@learner.hq.netapp.com> <46c16ec9$0$405$426a34cc@news.free.fr> Message-ID: On 2007-08-14, Ritesh Raj Sarraf wrote: > Bruno Desthuilliers wrote: > >>>> What's leading you to conclude the import isn't being executed? You >>>> realise, I trust, that the module's code will only be executed on the >>>> first call to __init__()? >>>> >>> >>> Well. Putting it in a "try" inside __init__() doesn't do anything. >> >> This would be highly suprising. >> > > Yes, it is surprising. Unfortunately. :-( > Or maybe I'm doing something really dumb. > >>> The >>> import never happens. >> >> As soon as your running this code on a platform where os.name yields >> either 'nt' or 'dos', the import statement is executed. You can bet your >> ass on this. Now this import can fail for a lot of reasons (imported >> module not in sys.path, error in the imported module, etc), and since >> your catching *and dismissing* the ImportError, you don't know what >> effectively happens. It's like someone send you mails, you set your >> filter to trash mails from this person, and then complain this person >> never send you mails !-) >> >>> And thus if I make a call in any of the methods, it >>> fails with an error message. A NameError IIRC. >> >> "IIRC" ? Inspecting the traceback may help, you know. > > There's no traceback because the import never happens. > > Here's what I've captured for you exactly I see on my terminal > > > rrs at learner:/tmp$ cat rick.py > class Log: > def __init__(self, verbose, lock = None): > self.VERBOSE = bool(verbose) > self.lock = bool(lock) > > if self.lock: > self.dispLock = threading.Lock() > else: > self.dispLock = None > > if os.name == 'posix': > try: > import foobar > except ImportError, e: > print >> sys.stderr, e > > self.platform = 'posix' > self.color = get_colors() > > elif os.name in ['nt', 'dos']: > self.platform = 'microsoft' > try: > import SomeModule > except ImportError, e: > # comment out next line before going to prod... > print >> sys.stderr, e > > self.color = None > else: > self.color = SomeModule.get_colors_windows() > else: > self.platform = None > self.color = None > rrs at learner:/tmp$ python > Python 2.4.4 (#2, Jul 21 2007, 11:00:24) > [GCC 4.1.3 20070718 (prerelease) (Debian 4.1.2-14)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import os, sys >>>> os.path.abspath(os.curdir) > '/tmp' >>>> from rick import Log >>>> import rick >>>> os.name > 'posix' >>>> import foobar > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named foobar >>>> > > > > For the 'posix' OS, I'm doing an erratic import which should fail and print > the error message. > > See, it prints nothing. This _is_ what has made me conclude > that imports aren't executed in __init__(). But hey, they will > get executed if you put them in any of the methods (which is > again illogical because methods can/are called multiple times). If you want an import inside an __init__ to run, you must call the __init__ function that contains it. >>> log = rick.Log() You'll get another surprise when you do this, though. ;) -- Neil Cerutti From Brian.McCann at viziant.net Mon Aug 20 15:54:07 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Mon, 20 Aug 2007 15:54:07 -0400 Subject: reading a line in file References: <93066C069973ED448DC2BCEA9C44A7383BE2B2@efmailx><2dc0c81b0708201029k5909d919vcf0deebae74a79c7@mail.gmail.com><93066C069973ED448DC2BCEA9C44A7383BE2B4@efmailx> <2dc0c81b0708201207p7f83f2e0l6de15fd70be252a5@mail.gmail.com> Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE2B6@efmailx> Shawn, Tim ,Jay many thanks, It looks like there are many ways this problem can be approached either by using regex or a tokens Tim I'm not familiar with your solution, but will learn about that method also Jay, what do you mean by regex comes with a lot of overhead? --Brian ________________________________ From: python-list-bounces+brian.mccann=viziant.net at python.org on behalf of Shawn Milochik Sent: Mon 8/20/2007 3:07 PM To: python-list at python.org Subject: Re: reading a line in file Hopefully this will help (using your input file) #!/usr/bin/env python import re buildinfo = "input.txt" input = open(buildinfo, 'r') regex = re.compile(r"^\s*build.number=(\d+)\s*$") for line in input: if re.search(regex, line): print line buildNum = re.sub(r"^\s*build.number=(\d+)\s*$", "\\1", line) print line print buildNum -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From aafshar at gmail.com Tue Aug 14 06:00:20 2007 From: aafshar at gmail.com (Ali) Date: Tue, 14 Aug 2007 10:00:20 -0000 Subject: Assignments and Variable Substitution In-Reply-To: References: Message-ID: <1187085620.641516.269590@b79g2000hse.googlegroups.com> On Aug 14, 12:45 am, Steve Holden wrote: > Evan Klitzke wrote: > > On 8/13/07, brad wrote: > >> I'd like to do something like this: > > >> var = '123' > >> %s = [], %var > And why would you want a variable whose name is '123'? ... and thus continues the search for private variables in Python. From cai.haibin at gmail.com Wed Aug 22 03:13:40 2007 From: cai.haibin at gmail.com (james_027) Date: Wed, 22 Aug 2007 07:13:40 -0000 Subject: creating a dictionary from a dictionary with regex Message-ID: <1187766820.785959.170190@r23g2000prd.googlegroups.com> Hi, I am trying to create a dictionary from a dictionary which the help of regex to identify which keys to select. I have something like this but I feel its long and not the fastest solution ... could someone contribute? import re d= {'line2.qty':2, 'line3.qty':1, 'line5.qty':12, 'line2.item':'5c-BL Battery', 'line3.item':'N73', 'line5.item':'Screen Cover'} collected = [k[:5] for k in d if re.match('^line\d+\.qty',k)] for i in collected: d2 = {} for k in d: if re.match('^%s\.\D+' % i, k): d2[k] = d[k] print d2 Thanks james From google at mrabarnett.plus.com Fri Aug 31 12:49:31 2007 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 31 Aug 2007 09:49:31 -0700 Subject: list index() In-Reply-To: References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188497498.3468.60.camel@dot.uniqsys.com> <0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net> <1188551958.728836.137370@x35g2000prf.googlegroups.com> Message-ID: <1188578971.748594.206140@d55g2000hsg.googlegroups.com> On Aug 31, 11:05 am, Jon Ribbens wrote: > On 2007-08-31, Erik Max Francis wrote: > > >> I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll > >> and role similarly. > > >> My accent is probably from the East Midlands of the UK, but is not > >> pronounced. > > > _Troll_ and _frolic_ aren't pronounced with the same "o" sound in any > > accent I've ever heard of. > > Welcome to England! > > > Which you pronounce _boat_ and _bot_ the same way, too? > > No. HTH HAND. > For some, "troll" rhymes with "roll", for others, with "doll". Does it matter? As for the pronunciation of "Python", let's ask Guido! :-) From catherine.devlin at gmail.com Fri Aug 17 16:41:34 2007 From: catherine.devlin at gmail.com (Catherine) Date: Fri, 17 Aug 2007 20:41:34 -0000 Subject: round-trip from egg to code and back to egg Message-ID: <1187383294.003703.193230@x35g2000prf.googlegroups.com> I'd like to use Scriptaculous with TurboGears on Python 2.5. Unfortunately, Scriptaculous is currently in the Cheese Shop only as a Python 2.4 egg. If I had the setup.py that was used to generate the egg, I think it would be really easy to generate a new Python 2.5 egg from the existing 2.4 egg. In fact, it would be gruntwork we could easily offload from the package authors. The trouble is, an egg doesn't include setup.py. Is there any direct way to round-trip a Python package from egg to installed code and into a new egg? I might be able to mine enough information from the files in EGG-INFO to reconstruct setup.py - reverse-engineering - but that seems unnervingly like work. Three possibilities come to mind - 1. I'm missing something simple 2. setuptools could be modified to include the original setup.py with the egg 3. a script could mine EGG-INFO to regenerate setup.py - maybe such a script has already been written? Can somebody who understands eggs better comment? Thanks very much! - Catherine http://catherinedevlin.blogspot.com From zyzhu2000 at gmail.com Sat Aug 18 21:46:57 2007 From: zyzhu2000 at gmail.com (beginner) Date: Sun, 19 Aug 2007 01:46:57 -0000 Subject: How to make a module function visible only inside the module? In-Reply-To: <1i32pg7.b0y3h92vjygwN%raims@dot.com> References: <1187484334.091530.90420@m37g2000prh.googlegroups.com> <1i32pg7.b0y3h92vjygwN%raims@dot.com> Message-ID: <1187488017.198905.242610@j4g2000prf.googlegroups.com> On Aug 18, 8:27 pm, ra... at dot.com (Lawrence Oluyede) wrote: > beginner wrote: > > Is there any equivalent version of C's static function in Python. I > > know I can make a class function private by starting a function name > > with two underscores, but it does not work with module functions. > > The trick for the name mangling does not work at module level. Anyway, > if you read the PEP 8 [1] you can correctly write your code following a > well known coding standard. A function like this: > > def _f(): > pass > > is meant to be private, you can also state it in the function's > docstring to be more clear, if you want, but it's not necessary > > > For exmaple, __func1 is still visible outside the module. > > Yes, and _f() will also be. There's no such thing as enforcing > encapsulation in Python, even the "__method()" trick can be easily > bypassed if you have to. > > 1 - > > HTH > > -- > Lawrence, oluyede.org - neropercaso.it > "It is difficult to get a man to understand > something when his salary depends on not > understanding it" - Upton Sinclair Thanks a lot. I was using two underscores, __module_method() as my static method convention, and then I had some problems calling them from inside class methods. From zyzhu2000 at gmail.com Thu Aug 16 15:28:03 2007 From: zyzhu2000 at gmail.com (beginner) Date: Thu, 16 Aug 2007 19:28:03 -0000 Subject: Help me!! In-Reply-To: <1187292365.988491.249170@i38g2000prf.googlegroups.com> References: <1187291279.545324.205610@i38g2000prf.googlegroups.com> <1187292365.988491.249170@i38g2000prf.googlegroups.com> Message-ID: <1187292483.879788.130890@m37g2000prh.googlegroups.com> On Aug 16, 2:26 pm, beginner wrote: > > Some one help me so that > > If ab = [a,b,c,d] > > and cd = [a,c] > > my global list file should be [A,b,C,d] If there is a lot of entries in the list, I would consider using an indexed data structure such as dict. ab=['a','b','c','d'] cd=['a','c'] common=[x.upper() for x in ab if x in cd] ab_minus_cd=[x for x in ab if x not in cd] cd_minus_ab=[x for x in ab if x not in cd] requested_list = common+ab_minus_cd+cd_minus_ab- Hide quoted text - From http Mon Aug 27 00:11:03 2007 From: http (Paul Rubin) Date: 26 Aug 2007 21:11:03 -0700 Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com> <1187898049.734696.9500@l22g2000prc.googlegroups.com> <13csi2tn49esmc3@corp.supernews.com> <13csqk47j0c56b0@corp.supernews.com> <13ct7v3qn2v5206@corp.supernews.com> <13d49lk6ue2as6d@corp.supernews.com> <13d4hutad1dq699@corp.supernews.com> Message-ID: <7xk5rhvcq0.fsf@ruckus.brouhaha.com> "bambam" writes: > Is it safe to write > A = [x for x in A if x in U] > or is that undefined? I understand that the slice operation > can be used to make a temporary copy, so I could write > A=[x for x in A[:] if x in U] > but I've just copied that without any understanding. You get a temporary copy either way; note you're going to linearly search U on every pass. Maybe you want: SU = set(u) A = [a for x in A if x in SU] or possibly A = list(set(A) & set(U)) which will remove duplicate elements from A and not necessarily keep them in the same order, but is likely to be fastest of the bunch. From conra2004 at yahoo.com Thu Aug 16 03:48:20 2007 From: conra2004 at yahoo.com (yadin) Date: Thu, 16 Aug 2007 00:48:20 -0700 Subject: ploting issues in program Message-ID: <1187250500.571837.196940@19g2000hsx.googlegroups.com> hi every one! can you please help me to fix these polar plot in db's so that the center is at the minimun negative number in voltagedb about [-50] and the maximun is at zero and how can i see values on the axis like showing that the axes start at -50 -40 -30 .....and end at zero than you here is the program import wx import os from wx.lib.colourdb import * from pylab import* angteta = [ 4.36332313e-003, 3.18522588e-001, 6.32681854e-001, 9.46841119e-001, 1.26100038e+000, 1.57515965e+000, 1.88931892e+000, 2.20347818e+000, 2.51763745e+000, 2.83179671e+000, 3.14595598e+000, 3.46011524e+000, 3.77427451e+000, 4.08843377e+000, 4.40259304e+000, 4.71675230e+000, 5.03091157e+000, 5.34507083e+000, 5.65923010e+000, 5.97338936e+000,] voltage = [ 0.00363471, 0.26569155, 0.52562334, 0.76330428, 0.93673361, 1. , 0.93321713, 0.75733232, 0.5185449 , 0.25840091, 0.00363471, 0.26569155, 0.52562334, 0.76330428, 0.93673361, 1. , 0.93321713, 0.75733232, 0.5185449 , 0.25840091,] #voltagedb = 20*log10(voltage) voltagedb = [-48.7906044 ,-11.51244516, -5.58650713, -2.34604603, -0.56767793, 0. , -0.60034598, -2.41427014, -5.7042726 ,-11.75411924,-48.7906044 , -11.51244516, -5.58650713, -2.34604603, -0.56767793, 0. , -0.60034598, -2.41427014, -5.7042726 ,-11.75411924,] polar(angteta,voltagedb) show() From ricaraoz at gmail.com Mon Aug 13 15:21:44 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 13 Aug 2007 16:21:44 -0300 Subject: python 2.5 bug In-Reply-To: <1186884626.597028.246990@57g2000hsv.googlegroups.com> References: <1186825286.493878.80380@l70g2000hse.googlegroups.com> <1186884626.597028.246990@57g2000hsv.googlegroups.com> Message-ID: <46C0AF48.20307@bigfoot.com> Dustan wrote: > On Aug 11, 12:32 am, Thorsten Kampe wrote: >> 4. don't do something you don't fully understand (in this case >> installing Python 2.5 and uninstalling Python 2.4) > > If we were all limited by that rule, none of us would never have used > a computer in the first place. Operating a computer is a learning > experience, no matter what level you're at (although admittedly the > lessons learned can sometimes be hurtful). > Hi, I'm new to python. I'm male 48yo have a daughter, divorced. Live in BA. Read Introduct me python and am at page 56 of shafting python the right way. Have 220v alternate current (notice ! not 110v), my computer is dirty, used to be whitish, got an epson printer (stylus c65). My computer table is wood and some plastic. It's 16:05 and we are +4GMT here, temp is 17Centigrades and no wind. Ok. The question is....... shit, I forgot the question! Get to you later. ;c) From zyzhu2000 at gmail.com Mon Aug 20 14:03:58 2007 From: zyzhu2000 at gmail.com (beginner) Date: Mon, 20 Aug 2007 18:03:58 -0000 Subject: 'REPL' style IDE In-Reply-To: <1187632249.748945.158910@i13g2000prf.googlegroups.com> References: <1187632249.748945.158910@i13g2000prf.googlegroups.com> Message-ID: <1187633038.373751.244700@i38g2000prf.googlegroups.com> On Aug 20, 12:50 pm, beginner wrote: > Hi Everyone, > > I am using the Wing IDE. It works great when developing applications, > but the workflow is like Visual Studio -- after you execute it or > debug it, the python script ends. > > What I want is an interactive interpreting environment. I want the IDE > to execute a boot script to initialize my environment and create some > basic data objects. And then I want to be able to type in command on > the command line using these objects. The IDLE that comes with Python > does this, but compared with Wing, it does not have a lot of the > convenient features. > > I am wondering if there is anything more powerful than IDLE that can > do this. > > Thanks, > Geoffrey If Wing could load my init script into a python session ONCE and then run my code in another files MANY times, with or without the debugger, without starting a new python session, that would be great. From omari at smileystation.com Mon Aug 6 15:28:22 2007 From: omari at smileystation.com (Omari Norman) Date: Mon, 6 Aug 2007 15:28:22 -0400 Subject: encode() question In-Reply-To: <1185900791.595830.21290@d55g2000hsg.googlegroups.com> References: <1185900791.595830.21290@d55g2000hsg.googlegroups.com> Message-ID: <20070806192822.GA22360@cameron> On Tue, Jul 31, 2007 at 09:53:11AM -0700, 7stud wrote: > s1 = "hello" > s2 = s1.encode("utf-8") > > s1 = "an accented 'e': \xc3\xa9" > s2 = s1.encode("utf-8") > > The last line produces the error: > > --- > Traceback (most recent call last): > File "test1.py", line 6, in ? > s2 = s1.encode("utf-8") > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position > 17: ordinal not in range(128) > --- > > The error is a "decode" error, and as far as I can tell, decoding > happens when you convert a regular string to a unicode string. So, is > there an implicit conversion taking place from s1 to a unicode string > before encode() is called? By what mechanism? Yep. You are trying to encode a string. The problem is that strings are already encoded, so it generally makes no sense to call .encode() on them. .encode()ing a string can be handy if you want to convert its encoding. In such a case, though, Python will first convert the string to Unicode. To do that, it has to know how the string is encoded. Unless you tell it otherwise, Python assumes the string is encoded in ascii. You had a byte in there that was out of ascii's range...thus, the error. Python was trying to decode the string, assumed it was ascii, but that didn't work. This is all very confusing; I'd highly recommend reading this bit about Unicode. It started me down the difficult road of actually understanding what is going on here. http://www.joelonsoftware.com/articles/Unicode.html -- It's another Baseline Boulder Morning. From tjreedy at udel.edu Fri Aug 31 17:12:38 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 31 Aug 2007 17:12:38 -0400 Subject: [python 3.0] reload() gone? References: <61d0e2b40708311110l5a13819fh4e6b2aafe928b44d@mail.gmail.com> Message-ID: "Bernard Lebel" <3dbernard at gmail.com> wrote in message news:61d0e2b40708311110l5a13819fh4e6b2aafe928b44d at mail.gmail.com... |I read in the Python 3.0 documentation that reload() was removed, | without further explanations. | | http://docs.python.org/dev/3.0/whatsnew/3.0.html?highlight=reload The .a1 release docs are a bit skimpy in places. Reload() often does not do what people want or expect. | So what are we supposed to do to reload modules? He once said he was working on a replacement that he was first testing on himself. I guess it did not make .a1. tjr From tn.pablo at gmail.com Mon Aug 20 21:59:39 2007 From: tn.pablo at gmail.com (Pablo Torres) Date: Mon, 20 Aug 2007 18:59:39 -0700 Subject: Any advice on ways for sharing a small Python application with the world? In-Reply-To: <1187647187.137812.158130@22g2000hsm.googlegroups.com> References: <1187647187.137812.158130@22g2000hsm.googlegroups.com> Message-ID: <1187661579.868574.219860@50g2000hsm.googlegroups.com> On Aug 20, 4:59 pm, Bert Heymans wrote: > Hi, > > I made a Python cli application for resizing batches of images based > on the PIL. You can find it herehttp://heymans.org/pyresize.html > > It's just an straight forward command line interface application but I > guess many people would find a use for it, it can be used as a module > as well. There's lots of comments in the code and a chunk of > documentation. > > This post is a way to get the word out, I blogged about it (http:// > blog.heymans.org) and submitted it to the Vaults of Parnassus (http:// > py.vaults.ca/) does anyone know of other ways to share something that > might just be too small for a sourceforge project but too big to be a > snippet? > > Thanks! > > Cheers > > Bert Heymans www.uselesspython.com is not as useless as it sounds. I think it's popular enough. From rNOSPAMon at flownet.com Tue Aug 21 03:42:45 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Tue, 21 Aug 2007 00:42:45 -0700 Subject: Is there a way to change the default string encoding? References: Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: > If all else fails there's > > >>> sys.setdefaultencoding("latin1") > >>> "Andre\xe9 Ramel".decode() > u'Andre\xe9 Ramel' > > but that's an evil hack, you should rather talk to the maintainer of the > offending code to update it to accept unicode. Yes, but I need to hack around it until I can get it fixed. Thanks! rg From gregturn at mindspring.com Wed Aug 29 10:36:45 2007 From: gregturn at mindspring.com (Goldfish) Date: Wed, 29 Aug 2007 07:36:45 -0700 Subject: Creating a multi-tier client/server application In-Reply-To: <46d57888$0$295$426a74cc@news.free.fr> References: <1188360460.838635.186930@w3g2000hsg.googlegroups.com> <7xbqcqhqbw.fsf@ruckus.brouhaha.com> <46d54ed8$0$429$426a34cc@news.free.fr> <1188393925.007952.313110@r29g2000hsg.googlegroups.com> <46d57888$0$295$426a74cc@news.free.fr> Message-ID: <1188398205.836630.280570@19g2000hsx.googlegroups.com> Perhaps Spring Python can help you out (http://springpython.python- hosting.com). It reuses technologies like Pyro for remoting, offers database templates, has a plugable security component, an AOP solution should the need arise, an IoC container, and has a couple of web-app demos using CherryPy. Of course, you can use whatever web stack you want. I just picked CherryPy to demo things. Each component of Spring Python is optional, and you can use it through the IoC container, or programatically. This might help you leverage development of an enterprise app. BTW, I have plans to implement a wxPython front end sample app. I just haven't done it yet. Good luck! From deets at nospam.web.de Sun Aug 19 05:58:37 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 19 Aug 2007 11:58:37 +0200 Subject: Symbolic Link In-Reply-To: <1187505140.524645.314920@d55g2000hsg.googlegroups.com> References: <1187475296.173269.263080@k79g2000hse.googlegroups.com> <5ipbc3F3q94rmU1@mid.uni-berlin.de> <1187505140.524645.314920@d55g2000hsg.googlegroups.com> Message-ID: <5iqiinF3q07dgU1@mid.uni-berlin.de> mosscliffe schrieb: > On 18 Aug, 23:49, "Diez B. Roggisch" wrote: >> mosscliffe schrieb: >> >> >> >>> I am trying to create a link to a file, which I can then use in an >>> HTML page. >>> The system is Linux on a hosted web service, running python 2.3. >>> Other than that I have no knowledge of the system. >>> The link is created OK, but when I try to use it as filename for the >>> IMG TAG, it does not get displayed. The page source of the created >>> page is pointing to the link as temp/test1.jpg >>> Any ideas ? >>> srcFile = "temp/test2.jpg" >>> linkFile = "temp/test1.jpg" >>> if os.path.islink(linkFile): >>> print "Link Exists", nl >>> pass >>> else: >>> print "Making Link", nl >>> os.symlink(srcFile, linkFile) >>> print '
the image

' % linkFile >>> print 'the image' % srcFile >> In what environment is that script running? If it's apache, it might be >> that the apache settings disallow for following links. >> >> Diez > > It is Apache. > > Can I create some override in the current directory. I am afraid my > Apache skills are almost zero. As are mine. At least from the top of my head. You better ask in a more apache-centric forum. Diez From bscrivener42 at gmail.com Thu Aug 2 07:27:31 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Thu, 02 Aug 2007 04:27:31 -0700 Subject: i am new to python-Please somebody help In-Reply-To: <1186047103.673871.150460@z24g2000prh.googlegroups.com> References: <1186047103.673871.150460@z24g2000prh.googlegroups.com> Message-ID: <1186054051.011105.196620@i13g2000prf.googlegroups.com> On Aug 2, 4:31 am, cool.vimalsm... at gmail.com wrote: > > i want the packages file with > a ".gz" extension by implementing a python program http://docs.python.org/lib/module-gzip.html From skip at pobox.com Fri Aug 3 19:23:25 2007 From: skip at pobox.com (Skip Montanaro) Date: Fri, 3 Aug 2007 23:23:25 +0000 (UTC) Subject: =?utf-8?b?X19jYWxsX18=?= considered harmful or indispensable? References: <46b24200$0$19638$426a74cc@news.free.fr> <46b2e0c2$0$14572$426a74cc@news.free.fr> Message-ID: Terry Reedy udel.edu> writes: > > The bug went something like this: > > > > obj = some.default_class > > ... > > if some_other_rare_condition_met: > > ... several lines ... > > obj = some.other_class() > > Should that have been some.other_class (without the ()s?). Either that or default value should have been an instance of some.default_class. Didn't really matter in this case... Skip From kevin.t.ryan at gmail.com Tue Aug 28 22:46:17 2007 From: kevin.t.ryan at gmail.com (Kevin T. Ryan) Date: Wed, 29 Aug 2007 02:46:17 -0000 Subject: Compiling Source with alternate Openssl lib In-Reply-To: <1188324598.687927.169350@d55g2000hsg.googlegroups.com> References: <1188324598.687927.169350@d55g2000hsg.googlegroups.com> Message-ID: <1188355577.552009.101640@g4g2000hsf.googlegroups.com> On Aug 28, 2:09 pm, "Kevin T. Ryan" wrote: > Hi All - > > I'm trying to compile Python on a Centos machine (RHEL) 3.8 for a > hosting account that I just set up and I'm having 2 issues: > > 1. I ran into an issue with the "hashlib" module [I think] because it > bumps it up against an *OLD* openssl lib (like, Feb. 2003). So I > installed a newer openssl lib, but when I recompiled python it still > used the old library. So I tried ./configure again with the flag: "- > with-openssl-libs=/new/directory" but it still didn't work. Any idea > how I might be able to remedy this? I have a working solution right > now: I've commented out the last 2 lines of hashlib.py, but I'd rather > not do that if I didn't have to. > > 2. As part of this process, I installed "easy_install" and I was > trying to download psycopg2 but I got the error: "PyDateTimeAPI > defined but not used" when trying to compile. I've had this problem > before when trying to compile psycopg2 and it was because I didn't > have the postgres header libs installed (libpq-dev) ... but that's on > a debian box, and I can't figure out how to fix it on the RHEL one. > > I know the 2nd question might not belong in this group, but I thought > I'd ask just in case someone ran into this before or might have any > suggestions. > > Thanks in advance (as always!) for your help! > > Kevin In case this helps anyone, I figured it out ... unfortunately, my dumb a$$ didn't install Postgres before I tried to install the psycopg2 module! I then still had issues, but after adding the postgres 'lib' directory to the ld.so.config file (eg, cat "/dir/to/pgsql/lib" >> / etc/ld.so.config and running ldconfig all is well! Thanks, From bignose+hates-spam at benfinney.id.au Sat Aug 25 10:11:50 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 26 Aug 2007 00:11:50 +1000 Subject: curses library References: Message-ID: <873ay7itzt.fsf@benfinney.id.au> Ghirai writes: > Are there any wrappers around curses/ncurses? Python has its own 'curses' module in the standard library of course. That's if you want to work directly with the curses functionality, which is rather low-level. > Or any other similar libraries? The library that I always think of when I think "Python ncurses wrapper" is: Urwid is a console user interface library for Python. Available as a package (e.g. 'python-urwid') in most GNU/Linux distributions, or you can install it from the download link. -- \ "Pity the meek, for they shall inherit the earth." -- Donald | `\ Robert Perry Marquis | _o__) | Ben Finney From raims at dot.com Thu Aug 16 18:43:03 2007 From: raims at dot.com (Lawrence Oluyede) Date: Fri, 17 Aug 2007 00:43:03 +0200 Subject: How to say $a=$b->{"A"} ||={} in Python? References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> Message-ID: <1i2ysn4.7ue1uud53iygN%raims@dot.com> beginner wrote: > I'd like to do the following in more succint code: > > if k in b: > a=b[k] > else: > a={} > b[k]=a b.setdefault(k, a) -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From lists at liquidtrust.org Wed Aug 22 16:19:17 2007 From: lists at liquidtrust.org (Charlie) Date: Wed, 22 Aug 2007 14:19:17 -0600 Subject: MsiLib Message-ID: <20070822141917.kbgih09joc0ko0ws@74.220.202.27> Thanks for pointing that out. It solved the one problem and along came another. Now I get the following error when I try running it. Thanks for the help. Traceback (most recent call last): File "msi.py", line 7, in record = view.Fetch() _msi.MSIError: function failed From deets at nospam.web.de Thu Aug 2 13:20:33 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 02 Aug 2007 19:20:33 +0200 Subject: standalone process to interact with the web In-Reply-To: <46b20019$0$18576$426a74cc@news.free.fr> References: <1185899130.331170.151980@e16g2000pri.googlegroups.com> <1185904623.754078.198910@e9g2000prf.googlegroups.com> <1185909098.952860.217190@j4g2000prf.googlegroups.com> <46b05aac$0$31743$426a74cc@news.free.fr> <1186059016.461925.295520@e16g2000pri.googlegroups.com> <46b20019$0$18576$426a74cc@news.free.fr> Message-ID: <5hei3dF3kaamsU1@mid.uni-berlin.de> Bruno Desthuilliers schrieb: > beginner a ?crit : >> On Aug 1, 5:04 am, Bruno Desthuilliers > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >>> beginner a ?crit : >>> (snip) >>> >>>> Yes exactly. I just don't want to reinvent the wheel as I imagine >>>> there are already tons of libraries and frameworks that support RPC or >>>> the like functions. >>> Why go thru the pain of RPC, SOAP or such bloated horrors ? Why not just >>> use plain old HTTP with a RESTful API ? Then you just need to make your >>> app wsgi compliant. >> >> I am not familiar with RESTful API. I will look into it. >> > It's nothing else than the correct use of the HTTP protocol. And it's > much more simpler than all those XMLRPC, SOAP and whatnot monstruosities. While I'm with you regarding the monstrosity of SOAP, XMLRPC certainly isn't among the crappy IPC-protocols. Using it, you get type marshalling for some simple, yet important cases for free. Including such things as argument-order, and ordered values. Which for example make transmitting a dict a trivial operation of transmitting the two sequences of key/values. I don't see that with REST. Diez From titleistfour at gmail.com Thu Aug 9 12:08:08 2007 From: titleistfour at gmail.com (jay) Date: Thu, 09 Aug 2007 16:08:08 -0000 Subject: Extending logging module Message-ID: <1186675688.291944.299060@z24g2000prh.googlegroups.com> Hello, I've been using the python logging module a lot lately, and I've come across an instance where I need some new levels. Specifically, python does not include ALERT and NOTICE in the default set of logging levels. I am wondering how trivial it would be to extend the logging module to include these 2 levels that are standard with syslog? My first test was just to use the addLevelName method to add the two new levels, but syslog ignores them and logs at the next highest priority, no matter what I use. Looking further into the code and as a test, I changed the following to see if this would even work lib/python2.5/logging/__init__.py -> class Logger -> add new notice and alert root level functions -> new _levelNames for notice and alert -> new default level names for notice and alert lib/python2.5/logging/handlers.py -> class SysLogHandler priority_map was changed to include notice and alert It actually worked, but this is not the way I would like to handle the problem. I would prefer to extend the classes instead. However, I'm not too familiar with that, and I had to change things in so many places, I'm wondering if its even possible? I don't like changing the standard libraries, what happens if I have to upgrade python? My changes get overwritten. Can anyone offer some help or suggestions? Thanks Jay From carsten at uniqsys.com Fri Aug 3 15:10:45 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 03 Aug 2007 15:10:45 -0400 Subject: downloading files In-Reply-To: <1186166920.757662.269340@o61g2000hsh.googlegroups.com> References: <1186166920.757662.269340@o61g2000hsh.googlegroups.com> Message-ID: <1186168245.3382.52.camel@dot.uniqsys.com> On Fri, 2007-08-03 at 11:48 -0700, Ehsan wrote: > I foundd this code in ASPN Python Cookbook for downloading files in > python but when it finished downloading files the files became > corrupted and didn't open, the files in internet havn't any problem: > > > def download(url,fileName): > """Copy the contents of a file from a given URL > to a local file. > """ > import urllib > webFile = urllib.urlopen(url) > localFile = open(fileName, 'w') > [...] Try 'wb' instead of 'w'. -- Carsten Haese http://informixdb.sourceforge.net From kyosohma at gmail.com Tue Aug 7 11:21:31 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 07 Aug 2007 08:21:31 -0700 Subject: python system subprocess win32 In-Reply-To: References: Message-ID: <1186500091.063514.178640@e9g2000prf.googlegroups.com> On Aug 7, 9:48 am, "mclaugb" wrote: > Hello ALl, > I have a compiled program "conv.exe" that works as follows:>>conv.exe > > ----------------------------- > Please selection from the following options. press "h" for help, "p" for > print, "r" for readfile. > Enter your request now: > ... > -------------------- > Is there a way to script python using the subprocess method to start this > program "conv.exe" and then send a "r" to the command line to make it, say, > readfile. > > I have tried the following but the .communicate("r) is not doing anything > > import subprocess > import time > > a=subprocess.Popen("c:\\mcml\\conv.exe") > time.sleep(1) > (stdout, stderr) = a.communicate("r") > > Many thanks, > Bryan Use the sys.argv method. In the code that you have compiled, put the following lines in: import sys default = sys.argv[1] if default: # check which option it is and run it appropriately else: # print your menu here Then you should be able to do the subprocess Popen command: subprocess.Popen("c:\\mcml\\conv.exe r") You may need to turn the shell on... subprocess.Popen("c:\\mcml\\conv.exe r", shell=True) Hopefully that gives you some ideas anyway. Mike From michael at jedimindworks.com Sun Aug 12 22:04:10 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 12 Aug 2007 19:04:10 -0700 Subject: Binary, Hex, and Decimal string conversions In-Reply-To: <496954360708121620r4dd68ac9o430326ae8c8ae04d@mail.gmail.co m> References: <496954360708111559s1cef4212pabd14e95b27435ea@mail.gmail.com> <496954360708121620r4dd68ac9o430326ae8c8ae04d@mail.gmail.com> Message-ID: <649D1D6C-A44C-4D03-920D-489BBD108789@jedimindworks.com> On Aug 12, 2007, at 6:28 PM, Dick Moores wrote: > n = 12 > base = 36 > print to_base(n, base) > ========================================== > This seems to work fine for n >= base, but not for n < base. For > example, the code shown returns "c". Is my indentation wrong, or > the code? It seems to me that the code should work for the general > case, not just for n >= base. Isn't 'c' the correct answer? Regards, Michael --- Simplicity is the ultimate sophistication. -Leonardo da Vinci -------------- next part -------------- An HTML attachment was scrubbed... URL: From tenax.raccoon at gmail.com Thu Aug 9 11:01:00 2007 From: tenax.raccoon at gmail.com (Jason) Date: Thu, 09 Aug 2007 08:01:00 -0700 Subject: tests In-Reply-To: <46bb2511$0$10103$7b0f0fd3@mistral.news.newnet.co.uk> References: <1186666919.456036.120270@d30g2000prg.googlegroups.com> <1186670584.148181.180040@r34g2000hsd.googlegroups.com> <46bb2511$0$10103$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <1186671660.912133.225810@l70g2000hse.googlegroups.com> On Aug 9, 8:46 am, "special_dragonfly" wrote: > wrote in message > >http://docs.python.org/lib/module-filecmp.html > > My understanding of reading that is that it only looks at the file names > themselves and not their contents. So whether filename1=filename2 and in the > case of the function below it, whether one directory has files which are in > the other. > Correct me if I'm wrong. > Dom > > P.S. md5 or sha hash is what I'd go for, short of doing: > > MyFirstFile=file("file1.xls") > MySecondFile=file("file2.xls") > If MyFirstFile==MySecondFile: > print "True" > > although this won't tell you where they're different, just that they are... You're incorrect. If the shallow flag is not given or is true, the results of os.stat are used to compare the two files, so if they have the same size, change times, etc, they're considered the same. If the shallow flag is given and is false, their contents are compared. In either case, the results are cached for efficiency's sake. --Jason The documentation for filecmp.cmp is: cmp( f1, f2[, shallow]) Compare the files named f1 and f2, returning True if they seem equal, False otherwise. Unless shallow is given and is false, files with identical os.stat() signatures are taken to be equal. Files that were compared using this function will not be compared again unless their os.stat() signature changes. Note that no external programs are called from this function, giving it portability and efficiency. From irmen.NOSPAM at xs4all.nl Sat Aug 4 13:44:53 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sat, 04 Aug 2007 19:44:53 +0200 Subject: Auto run/Timer In-Reply-To: <1186216025.768369.240570@j4g2000prf.googlegroups.com> References: <1186216025.768369.240570@j4g2000prf.googlegroups.com> Message-ID: <46b4bb1a$0$237$e4fe514c@news.xs4all.nl> Rohan wrote: > Hello, > I would like my script to run once a week with out any external > interference. > More like a timer. Can it be done in python or should some other shell > scripting be used. > If anyone knows anything please let me know. > Have a look at my 'kronos' task scheduler, available from: http://www.razorvine.net/downloads.html Things like this do require a Python process to be running all the time, for obvious reasons. If you don't want that, you'll have to use a task scheduler tool that your operating system provides (cron, for instance). --irmen From gagsl-py2 at yahoo.com.ar Mon Aug 27 02:46:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 27 Aug 2007 03:46:16 -0300 Subject: Error with Simplemapi.py References: <1187938985.165186.300780@i38g2000prf.googlegroups.com> <1188194730.024877.120880@q5g2000prf.googlegroups.com> Message-ID: En Mon, 27 Aug 2007 03:05:30 -0300, Mick Duprez escribi?: > Thank you very much Gabriel, changing the NULL to None did the trick > (it also helps if I reload the changed module after editing!:( ). Glad to see it worked. > Yes > that is an old script and I will look into your suggestions. Basically > I'd just like to use the default mail client (windows or Unix/Linux) > to send simple mail with attachments, this way I can log the > attachments I send to a db for example for document transmittal/ > register reports etc. Hmmm... altough you may find some MAPI implementation for Linux, it's very uncommon; consider using sendmail instead, or ask for an outbound SMTP server and use the smtplib module. -- Gabriel Genellina From mensanator at aol.com Mon Aug 27 18:30:16 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 27 Aug 2007 15:30:16 -0700 Subject: Biased random? In-Reply-To: References: Message-ID: <1188253816.661391.22460@k79g2000hse.googlegroups.com> On Aug 27, 3:42 pm, Ivan Voras wrote: > Hi, > > I have a list of items, and need to choose several elements from it, > "almost random". The catch is that the elements from the beginning > should have more chance of being selected than those at the end (how > much more? I don't care how the "envelope" of probability looks like at > this point - can be linear). I see that there are several functions in > Python standard libraries for various distribution, but is there an easy > pythonic way to make them do what I need? > > signature.asc > 1KDownload If your list is small enough, you could do something like this: import random test = ['a','b','c','d','e','f','g','h','i','j'] temp = [] size = len(test)-1 for i,j in enumerate(test): temp.extend(j*(2**(size-i))) for i in xrange(400): if i % 30 == 0: print print random.choice(temp), ## a a b a a a i c a a a b c b b a a a a b a a a d a b a a g f ## a e a a a i a b a a b c b a a b a b b c b a b a c a a a a a ## b a a c a c e d b d a a a a a c a b b e a a b a a b a a c a ## a a a a a a b a b a c a a a c a d a c a a d b b b b d a a a ## a a d b a a a b a b b a b a c a a a b b a c b c a a c c c a ## a a b a a a b a b a a a a d c a a b c b b b d b b a a b c a ## a a a a a a b a d b c d b a b c a d b b b a b a b b b b b a ## b c a b a a b c a a a a a a a a b a a a b a a a a a d a b b ## a b b a c a b c a a a a a a a a c b a c c a a e a a a c b b ## a c e b b a a b c a b a b a a b a g a b e a a a c c a a c b ## b i a b a a a a c c c b a a a a a b b b a b b a a b b h a a ## d b a b a b b a a b c a b a a b a a a c a d a a b a b a a a ## a d a b b a b a a c a b c d b a a d a a b b a a a a a d a c ## a a a b a a b a c b Here, 'a' is twice as likely to occur as 'b', which is twice as likely to occur as 'c', which is twice as likely to occur as 'd', etc. From sjmachin at lexicon.net Mon Aug 20 09:15:46 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 20 Aug 2007 06:15:46 -0700 Subject: datetime in microseconds In-Reply-To: <1187610776.755796.170990@r29g2000hsg.googlegroups.com> References: <1187610776.755796.170990@r29g2000hsg.googlegroups.com> Message-ID: <1187615746.655162.295570@z24g2000prh.googlegroups.com> On Aug 20, 9:52 pm, mroelo... at gmail.com wrote: > Hi I have a time in microseconds, for example 0x8C905CBA7F84AF4. I > want this to a normal view in hh:mm:ss DD:MM:YYYY. I tried with > datetime, but it only takes a max of 1000000 microseconds is there > another solution? Your question can be interpreted in two possible ways: 1. You have an interval or duration (independent of a calendar point) and you want to express it in years, months, days, hours, etc. This is not possible, due to the variable number of days in a month. The best that you can do is express it as days, hours, etc. >>> microsecs = 0x8C905CBA7F84AF4 >>> secs = microsecs // 1000000 # or round to nearest if you prefer >>> mins, secs = divmod(secs, 60) >>> hrs, mins = divmod(mins, 60) >>> days, hrs = divmod(hrs, 24) >>> days, hrs, mins, secs (7326893L, 11L, 1L, 16L) >>> 2. You want to know the (Gregorian) calendar point that is 0x8C905CBA7F84AF4 microseconds after some epoch. In this case you need to specify what the epoch is. Then you can try something like: >>> datetime.datetime.fromordinal(1) + datetime.timedelta(microseconds=microsecs ) Traceback (most recent call last): File "", line 1, in OverflowError: date value out of range >>> # Whoops! >>> years_approx = days / 365.25 >>> years_approx 20059.939767282682 >>> Hmmm, one of us seems to be missing something ... From Shawn at Milochik.com Mon Aug 20 11:35:45 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Mon, 20 Aug 2007 11:35:45 -0400 Subject: regular expression dictionary search In-Reply-To: References: Message-ID: <2dc0c81b0708200835v4cd32bd4k9a443cc4feef879a@mail.gmail.com> #!/usr/bin/env python import re patterns = { 'sho.' : 6, '.ilk' : 8, '.an.' : 78 } def returnCode(aWord): for k in patterns: p = "^%s$" % k regex = re.compile(p) if re.match(regex, aWord): return patterns[k] if __name__ == "__main__": print "The return for 'fred' : %s" % returnCode('fred') print "The return for 'silk' : %s" % returnCode('silk') print "The return for 'silky' : %s" % returnCode('silky') print "The return for 'hand' : %s" % returnCode('hand') print "The return for 'strand' : %s" % returnCode('strand') print "The return for 'bank' : %s" % returnCode('bank') Note: If a word matches more than one pattern, only one will be returned. I'm not sure if I'm doing the patterns thing properly -- if anyone could instruct me on whether it would be proper to declare it in the function, or use a global declaration, please let me know. However, it runs properly as far as I tested it. Shawn From gtcopeland at gmail.com Tue Aug 21 09:24:00 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: 21 Aug 2007 06:24:00 -0700 Subject: IDE for Python In-Reply-To: References: Message-ID: <1187702024.675011.324020@q4g2000prc.googlegroups.com> On Aug 21, 5:00 am, Joel Andres Granados wrote: > Hello list: > > I have tried various times to use an IDE for python put have always been > disapointed. > I haven't revisited the idea in about a year and was wondering what the > python people > use. > I have also foundhttp://pida.co.uk/mainas a possible solution. Anyone > tried it yet? > > suggestions. > Regards > Joel Andres Granados > > joel.granados.vcf > 1KDownload Have you tried SPE? I don't know how it compares to PyDev but SPE is pretty slick. It has several other tools integrated into it, including a pretty nice debugger. It's fairly small and loads mucho faster than Eclipse ever will. Best of all SPE is written completely in Python. http://pythonide.blogspot.com/ http://sourceforge.net/projects/spe Personally I use XEmacs at the expense of some of the nicer IDE features. Greg From michele.simionato at gmail.com Wed Aug 29 22:39:14 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 30 Aug 2007 02:39:14 -0000 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> Message-ID: <1188441554.884249.50110@22g2000hsm.googlegroups.com> On Aug 30, 1:17 am, Dan Stromberg - Datallegro wrote: > IMO, putting Programming by Contract into python as part of the language > itself, or as a simple module, is a little bit like a company or > department coming up with a mission statement. It's easy to say that it's > meaningless, and some will ignore it, but it still kind of sets the tone > for how things "should be done". I disagree. IMO automatic testing is thousands of times better than design by contract and Python has already all the support you need (unittest, doctest, py.test, nose, ...) Michele Simionato From seanttierney at gmail.com Wed Aug 15 09:00:05 2007 From: seanttierney at gmail.com (Sean Tierney) Date: Wed, 15 Aug 2007 06:00:05 -0700 Subject: Combinatorial of elements in Python? In-Reply-To: References: <9e2f512b0708142203m782b0e10s817fb4d061ba0e46@mail.gmail.com> <46C2ED11.70904@freakmail.de> Message-ID: <54e1e4bc0708150600o40a6b979ta6b8497e20ddf0a7@mail.gmail.com> Hi Team, I'm trying to get Python hooked up to MySQL using MySQL-python-1.2.2 Details: Mac OS X 10.4.x Python2.5 MySQL 5.x.x MySQL-python-1.2.2 gcc Target: i686-apple-darwin8 Configured with: /private/var/tmp/gcc/gcc-5250.obj~12/src/configure --disable-checking -enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.0/ --with-gxx-include-dir=/include/c++/4.0.0 --build=powerpc-apple-darwin8 --with-arch=pentium-m --with-tune=prescott --program-prefix= --host=i686-apple-darwin8 --target=i686-apple-darwin8 Thread model: posix gcc version 4.0.1 (Apple Computer, Inc. build 5250) When I run $ python setup.py build, I get this message: ~/Desktop/MySQL-python-1.2.2 SeanThomas$ python setup.py build running build running build_py copying MySQLdb/release.py -> build/lib.macosx-10.3-fat-2.5/MySQLdb running build_ext building '_mysql' extension gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -Dversion_info=(1,2,2,'final',0) -D__version__=1.2.2 -I/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -c _mysql.c -o build/temp.macosx-10.3-fat-2.5/_mysql.o _mysql.c:35:23: error: my_config.h: No such file or directory _mysql.c:41: error: parse error before string constant _mysql.c:78: error: parse error before 'MYSQL' _mysql.c:78: warning: no semicolon at end of struct or union _mysql.c:81: error: parse error before '}' token _mysql.c:81: warning: data definition has no type or storage class _mysql.c:92: error: parse error before 'MYSQL_RES' _mysql.c:92: warning: no semicolon at end of struct or union _mysql.c:96: error: parse error before '}' token _mysql.c:96: warning: data definition has no type or storage class _mysql.c:108: error: parse error before '*' token _mysql.c: In function '_mysql_Exception': _mysql.c:122: error: 'c' undeclared (first use in this function) _mysql.c:122: error: (Each undeclared identifier is reported only once _mysql.c:122: error: for each function it appears in.) _mysql.c:125: error: 'CR_MAX_ERROR' undeclared (first use in this function) _mysql.c:133: error: 'CR_COMMANDS_OUT_OF_SYNC' undeclared (first use in this function) ....~100+ or more lines of error message then it ends with: lipo: can't figure out the architecture type of: /var/tmp//cc1VlbOG.out error: command 'gcc' failed with exit status 1 Can someone point me in the right direction? Thanks, and Happy Wednesday. From gheize at gmail.com Mon Aug 27 11:13:46 2007 From: gheize at gmail.com (Guillermo Heizenreder) Date: Mon, 27 Aug 2007 12:13:46 -0300 Subject: getLabel() CD-ROM Message-ID: <1188227626.15011.17.camel@leinad-desktop> Hi list, I'm new whit pygtk library. I'm interest to know if there is a class in the graphics library that it can provide me with information about the CD-ROM label ( something similar to class KMount in the graphic library pykde[1]). At the time I'm using pycdio class[2],but i don't wont to my application by dependent on the above class mentioned. Thanks and kind regards from Argentina. P/D: my English it to bad, I'm a novice. [1]http://www.riverbankcomputing.com/Docs/PyKDE3/classref/allclasses.html [2]http://pypi.python.org/pypi/pycdio/0.12 -- Heizenreder Guillermo http://code.google.com/u/gheize/ From http Wed Aug 29 01:17:39 2007 From: http (Paul Rubin) Date: 28 Aug 2007 22:17:39 -0700 Subject: Creating a multi-tier client/server application References: <1188360460.838635.186930@w3g2000hsg.googlegroups.com> Message-ID: <7xbqcqhqbw.fsf@ruckus.brouhaha.com> Jeff writes: > Here's a broad overview of what I need to do: cross-platform, client- > side GUI apps that interact with a server backed by a database. I'd > also like the possibility of having a web interface for small portions > of the app. ... any advice on anything I've mentioned > (or haven't?) Why not do the entire app as a web app, completely bagging the client side and just using a browser? It will help your deployment problems a lot, and using https will help with security since it looks like the app will be transmitting sensitive data. It also will simplify your networking questions a lot since you're just writing a server. See the big debate between Chris Mellon and me a few weeks ago about web apps vs client gui apps. Yes you can get a level of responsiveness from a client app that can't easily be done with a web app. However, relatively few client gui business apps that I've personally used really seem better than the equivalent things done as web apps in the obvious way. I would certainly prototype the app as a web app, and then think about writing a client gui only if it was clear that usability would really benefit from it. Even still, the server would still look like a web server, translating xml requests into database actions and responding with xml. > I want to plan this application out as thoroughly > as possible before writing any code, There is a school of thought (sometimes associated with "extreme programming") that this is more planning than you should really do. Think of a cross-country automobile trip. Figure out the general route you want to take, then get in the car and go, making low-level decisions as you get to them, rather than trying to plan every gas and rest and restaurant stop before you leave. From attn.steven.kuo at gmail.com Mon Aug 20 18:02:05 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Mon, 20 Aug 2007 22:02:05 -0000 Subject: Python equivalent of Perl's $/ In-Reply-To: References: <1187637588.073514.202930@x40g2000prg.googlegroups.com> Message-ID: <1187647325.321147.70810@j4g2000prf.googlegroups.com> On Aug 20, 1:02 pm, John K Masters wrote: > On 19:19 Mon 20 Aug , attn.steven.... at gmail.com wrote: > > > > > import StringIO > > > text = """\ > > To mimic Perl's input record separator in > > Python, you can use a generator. > > And a substring test. > > Perhaps something like the following > > is what you wanted. > > """ > > > mockfile = StringIO.StringIO(text) > > > def genrecords(mockfile, sep=".\n"): (snipped) > > Thanks, this also looks like a good way to go but ATM beyond my level of > Python knowledge. I've not reached the generator chapter yet but I'll > flag the message and return later. > > Regards, John Some features in Perl can be found in Python, so if you know the former, then learning the latter ought to go smoothly. In any case, here's an updated version of the generator that avoid repeating an unncessary string search: def genrecords(mockfile, sep=".\n"): """ """ buffer = "" while True: idx = buffer.find(sep) + len(sep) while idx >= len(sep): yield buffer[:idx] buffer = buffer[idx:] idx = buffer.find(sep) + len(sep) rl = mockfile.readline() if rl == "": break else: buffer = '%s%s' % (buffer, rl) yield buffer raise StopIteration -- Regards, Steven From steve at holdenweb.com Thu Aug 9 11:52:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 09 Aug 2007 11:52:51 -0400 Subject: Stackless Integration In-Reply-To: <46bb1df0$0$403$426a74cc@news.free.fr> References: <46bb1df0$0$403$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Jean-Paul Calderone a ?crit : >> On Thu, 09 Aug 2007 09:00:27 -0000, "Justin T." >> wrote: >>> Hi, >>> >>> I've been looking at stackless python a little bit, and it's awesome. >>> My question is, why hasn't it been integrated into the upstream python >>> tree? Does it cause problems with the current C-extensions? It seems >>> like if something is fully compatible and better, then it would be >>> adopted. However, it hasn't been in what appears to be 7 years of >>> existence, so I assume there's a reason. >> It's not Pythonic. > > Hum... Yes ? Really ? Care to argument ? Unfortunately such arguments quickly descend to the "yes it is", "no it isn't" level, as there is no objective measure of Pythonicity. Twisted is a complex set of packages which is difficult to understand from the outside,and is motivated by a specific approach to asynchronous operations that is neither well understood by the majority of programmers nor easily-explained to them. All the teaching sessions on Twisted I have attended have involved a certain amount of hand-waving or some over-heavy code examples with inadequate explanations. However I would say that Twisted has improve enormously over the last five years, and should really be a candidate for inclusion in the standard library. It would be a large component, though, and so there would be a number of heavy tasks involved, not least of them updating the documentation. So maintenance might be a worry unless a group stood up and committed to the task. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From jwaixs at gmail.com Wed Aug 8 04:10:39 2007 From: jwaixs at gmail.com (Noud Aldenhoven) Date: Wed, 8 Aug 2007 08:10:39 +0000 Subject: passing vars to py scipts in cron jobs In-Reply-To: <20070807220209.GX22017@lass.lfod.us> References: <20070807220209.GX22017@lass.lfod.us> Message-ID: On 8/7/07, Will Maier wrote: > > On Tue, Aug 07, 2007 at 05:45:46PM -0400, brad wrote: > > What's the proper way to call a py script and pass in variables > > while doing cron jobs? I can run the scripts fine from idle, > > python, etc using raw_input() to prompt users. The scripts have > > classes with methods that need arguments. > > This is commonly done with either sys.argv (a list of arguments > passed when invoking the script) or os.environ (a dictionary of > environment variables and values). Use either to instantiate your > classes or run functions. You might also want to look at the function getopt < http://docs.python.org/lib/module-getopt.html>. It's used to parse the variables in sys.argv which makes it (in my opinion) more user friendly. -- <:3 )~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From aboudouvas at panafonet.gr Fri Aug 10 11:34:15 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Fri, 10 Aug 2007 08:34:15 -0700 Subject: Ipc mechanisms and designs. Message-ID: <1186760055.658942.116300@x40g2000prg.googlegroups.com> Hi, inspired of the topic "The Future of Python Threading", i started to realize that the only way to utilize the power of multiple cores using Python, is spawn processes and "communicate" with them. If we have the scenario: 1. Windows (mainly) development 2. Processes are running in the same machine 3. We just want to "pass" info from one process to another. Info may be simple data types or user defined Python objects. what is the best solution (besides sockets) that someone can implement so to have 2 actually processes that interchanged data between them ? I looked at Pyro and it looks really good but i wanted to experiment with a simpler solution. From steve at holdenweb.com Fri Aug 24 00:00:37 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 24 Aug 2007 00:00:37 -0400 Subject: creating a tar file with python In-Reply-To: <46CE51E1.9020608@holdenweb.com> References: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> <93066C069973ED448DC2BCEA9C44A7383BE2ED@efmailx> <46CE4D3D.7020106@holdenweb.com> <93066C069973ED448DC2BCEA9C44A7383BE2EE@efmailx> <46CE51E1.9020608@holdenweb.com> Message-ID: <46CE57E5.9080908@holdenweb.com> Steve Holden wrote: > Brian McCann wrote: >> >> >> Steve, >> >> I ran the code as you suggested, didn't work, tried variations of it >> didn't work, >> If you don't know the answer don't pretend you do! >> >> Apology not accepted, please don't wake up! >> >> Future correspondence on any python questions from you go to trash. >> May your pillow not have pity on your head! >> > Well in that case it might have been a good idea to post the error > message you got from trying what I suggested rather than the one you got > from your fifteenth variation on my (admittedly untested) suggestion. > > Not to worry, I know not to try and help you any further. > > Sorry my limited Python experience wasn't able to help you solve your > problem. > > [plonk] > > regards > Steve > > PS: this reply is *much* more polite than the one that first came to > mind, which involved making suggestions involving sex and travel. You're > on your own from here on in. I don't like being incited to spew > profanity on a list of people I respect. I see you *did* post it, but then followed up with personal mail complaining about your lack of success and quoting another unsuccessful attempt to get your program working. naturally I received that before reading c.l.py and seeing the post I missed. I'm not a fucking computer, you know. There, you *have* goaded me into profanity. So now I'm going to follow the only sensible suggestion you've made and get some sleep. Feel better now? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From gagsl-py2 at yahoo.com.ar Sun Aug 5 06:29:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 05 Aug 2007 07:29:16 -0300 Subject: File Handling & TRY/EXCEPT References: <33119.3366124809$1186129744@news.gmane.org> <13677.732498809$1186148538@news.gmane.org> Message-ID: En Fri, 03 Aug 2007 10:38:17 -0300, Robert Rawlins - Think Blue escribi?: > Thanks for your ideas guys, > > I'm unfortunately tied to 2.4 so don't have the full try except status, > but > I'm now working with the following code: > > def addApp(self, event): > try: > logfile = > open('/pblue/new/Logs/Application.csv','a') > > now = datetime.datetime.now() > logstring = '%s,%s \n' % (event, str(now)) > > try: > logfile.write(logstring) > finally: > logfile.close() > except: > self.addApp(event) > > I'm trying to slowly debug my app and get rid of all the memory leaks, > but > its pain staking work, any help you can offer on that stuff would be a > god > send, I'm a little reluctant about posting all my app code on the lists > as > I'd like to keep some of it private. > > How does that new version look? A little tidier? If the logging error is rather permanent (disk full) or a programming error (e.g. you forget to import datetime) this will cause an infinite recursion. Don't try to log again, at least not the same way. The version below writes to the console when a logging error happens. And note the reordered open/try/finally: you want to ensure that after a call to open, no matter what happens, the file will be closed. def addApp(self, event): try: now = datetime.datetime.now() logstring = '%s,%s \n' % (event, str(now)) logfile = open('/pblue/new/Logs/Application.csv','a') try: logfile.write(logstring) finally: logfile.close() except: print >>sys.stderr, "%s: %s while attempting to log event '%s'" % ( sys.exc_info()[0], sys.exc_info()[1], event) -- Gabriel Genellina From horpner at yahoo.com Sat Aug 11 18:18:12 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 11 Aug 2007 22:18:12 GMT Subject: Something in the function tutorial confused me. References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <1186424693.529497.217040@w3g2000hsg.googlegroups.com> <46B8626A.2070303@bigfoot.com> <5hsoi3F3mlni2U1@mid.individual.net> <1186581124.3383.55.camel@dot.uniqsys.com> <1i2nhxn.tme05x17r39odN%aleax@mac.com> Message-ID: > On 2007-08-11, Alex Martelli wrote: >> Neil Cerutti wrote: >> ... >>> The Python Language Reference seems a little confused about >>> the terminology. >>> >>> 3.4.7 Emulating numeric types >>> 6.3.1 Augmented assignment statements >>> >>> The former refers to "augmented arithmetic operations", which >>> I think is a nice terminology, since assignment is not >>> necessarily taking place. Then the latter muddies the waters. >> >> Assignment *IS* "necessarily taking place"; if you try the >> augmented assignment on something that DOESN'T support >> assignment, you'll get an exception. Consider: >> >>>>> tup=([],) >>>>> tup[0] += ['zap'] >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: 'tuple' object does not support item assignment >> >> Tuples don't support item ASSIGNMENT, and += is an ASSIGNMENT, >> so tuples don't allow a += on any of their items. >> >> If you thought that += wasn't an assignment, this behavior and >> error message would be very problematic; since the language >> reference ISN'T confused and has things quite right, this >> behavior and error message are perfectly consistent and clear. > > Thanks for the correction. I was under the illusion that > sometimes augmented assignment would instead mutate the object. OK, I've thought about this some more and I think the source of my confusion was I thought assignment in Python meant binding a name to something, not mutating an object. But in the case of augmented assignment, assignment no longer means that? -- Neil Cerutti From kyosohma at gmail.com Mon Aug 27 09:36:45 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 27 Aug 2007 06:36:45 -0700 Subject: wxpython on FreeBSD 6.2 broken In-Reply-To: References: Message-ID: <1188221805.256643.185610@o80g2000hse.googlegroups.com> On Aug 26, 7:35 am, Michael S wrote: > Good day all, > > I was wondering if anyone was using the latest > wxpython on FreeBSD 6. I just installed it yesterday > as well as wxGlade. wxGlade doesn't function properly > - it does not display any controls. I then tried some > simple examples from the web and half of them don't > work. > > Anyone aware of this? > Michael I'm not, but the wxpython group might. Try posting there: http://www.wxpython.org/maillist.php Mike From ldo at geek-central.gen.new_zealand Wed Aug 29 03:42:19 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 29 Aug 2007 19:42:19 +1200 Subject: tempfile.mkstemp and os.fdopen References: <1188323759.955043.317630@19g2000hsx.googlegroups.com> Message-ID: In message , Michael J. Fromberger wrote: > ... since os.fdopen() only has access to the file descriptor, it > does not have a convenient way to obtain the file's name. You can do this under Linux as follows: os.readlink("/proc/%d/fd/%d" % (os.getpid(), fileno)) From mal at egenix.com Sat Aug 25 16:35:59 2007 From: mal at egenix.com (M.-A. Lemburg) Date: Sat, 25 Aug 2007 22:35:59 +0200 Subject: Filemaker interactions In-Reply-To: <1186004514.108975.119380@e9g2000prf.googlegroups.com> References: <1186004514.108975.119380@e9g2000prf.googlegroups.com> Message-ID: <46D092AF.80800@egenix.com> On 2007-08-01 23:41, Ian Witham wrote: > Hello, > > I'm hoping someone here can put me on the right track with some broad > concepts here. > > What I am hoping to achieve is a simple HTML page to be served over > our company LAN, into which the users (Real Estate Agents) can enter a > property address or reference number. > > My next thought was to have a Python CGI script query our filemaker > database of property listings, construct a PDF from the relevant > information, and finally return this PDF to the user. > > At no stage do I want the user to have unfettered access to the > database or the ability to alter/delete records. > > My question is: what is the most appropriate way for my script to > interact with Filemaker? Can this be done with Filemaker Pro 6? > > According to the Filemaker Help, the "Local Data Access Companion" > shares the FileMaker Pro database with ODBC-compliant applications on > the same computer. Is this the right option? > > Can my CGI script be an ODBC client? How? Would it need to be > Filemaker specific code or does ODBC have a standardised format? > > I'm grateful for any advice and a nudge in the right direction. You could try our mxODBC extension for Python which will likely just work out of the box: https://www.egenix.com/products/python/mxODBC/ with the Filemaker ODBC driver. Or give this module a try (if you have more time at hand and can do without a DB-API interface): http://www.lfd.uci.edu/~gohlke/code/filemaker.py.html It uses Filemaker's XML interface. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Aug 25 2007) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From stefan.behnel-n05pAM at web.de Sun Aug 19 13:01:38 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 19 Aug 2007 19:01:38 +0200 Subject: Sorting a list of Unicode strings? In-Reply-To: <1187542237.139346.6910@o80g2000hse.googlegroups.com> References: <1187542237.139346.6910@o80g2000hse.googlegroups.com> Message-ID: <46C87772.2010603@web.de> oliver at obeattie.com wrote: > Hey Guys, ... and girls - maybe ... > Maybe I'm missing something fundamental here, but if I have a list of > Unicode strings, and I want to sort these alphabetically, then it > places those that begin with unicode characters at the bottom. That's because "Unicode" is more than one alphabet. unicode objects compare based on the Unicode character value, so sort() does alike. Stefan From oliver at obeattie.com Sat Aug 4 18:43:39 2007 From: oliver at obeattie.com (oliver at obeattie.com) Date: Sat, 04 Aug 2007 15:43:39 -0700 Subject: Encoding DeprecationWarning In-Reply-To: References: <1186254427.792114.173170@q75g2000hsh.googlegroups.com> Message-ID: <1186267419.999613.209480@q75g2000hsh.googlegroups.com> >>> from wt.lib.misc_lists import all_countries __console__:1: DeprecationWarning: Non-ASCII character '\xc3' in file / Django/wt/../wt/lib/misc_lists.py on line 141, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details From ldo at geek-central.gen.new_zealand Fri Aug 31 23:32:22 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 01 Sep 2007 15:32:22 +1200 Subject: Non-Blocking IO References: <1188614575.647228.248640@k79g2000hse.googlegroups.com> Message-ID: In message <1188614575.647228.248640 at k79g2000hse.googlegroups.com>, mp wrote: > Calling try3() yields the error: > File "./test.py", line 54, in try3 > print os.read(fout.fileno(),256) > OSError: [Errno 35] Resource temporarily unavailable That's what's supposed to happen. That's telling you there are no bytes currently available to be read. From tim at tdw.net Thu Aug 2 11:41:55 2007 From: tim at tdw.net (Tim Williams) Date: Thu, 2 Aug 2007 16:41:55 +0100 Subject: beginner in python In-Reply-To: References: Message-ID: <9afea2ac0708020841j1d196dc8n5f6fc8ecbddfa146@mail.gmail.com> On 02/08/07, Beema shafreen wrote: > Hi everybody , > I am a beginner in python, > I have to fetch the redundant entries from a file, > > code: > > import re > L = [] > fh = open('ARCHITECTURE_MAIN.txt', > 'r') > for line in fh.readlines(): > data =line.strip() > # splitted = data.split('#') > L.append(data) > fh.close() > > > > M=L > for x in L: > x = x.split('#') > for y in M: > y = y.split('#') > x_data = x[0],x[1],x[2],x[3] > #print x_data > y_data = y[0],y[1],y[2],y[3] > #print y_dat > if x_data[0] == y_data[0]: > print x_data > > > i get the result as a tupule, > the text file which has datas separated by hash > entry#isoform#start#stop# i have to check upto this > > 00250_1#ARCH_104#61#89#Literature#9224948#00250#### > 00250_1#ARCH_104#97#126#Literature#9224948#00250#### > 00250_1#ARCH_104#139#186#Literature#9224948#00250#### > 00251_1#ARCH_463#7#59#SMART##00251#### > 00251_1#ARCH_463#91#121#SMART##00251#### > 00251_1#ARCH_463#251#414#SMART##00251#### > 00251_1#ARCH_463#540#624#SMART##00251#### > 00252_1#ARCH_474#1#21#Literature#8136357#00252#### > 00252_1#ARCH_393#481#501#Literature#8136357#00252#### > 00252_1#ARCH_463#523#553#SMART##00252#### > 00253_1#ARCH_82#37#362#SMART##00253#### > 00253_1#ARCH_54#365#522#SMART##00253#### > 00253_1#ARCH_104#589#617#SMART##00253#### > 00253_1#ARCH_104#619#647#SMART##00253#### > 00253_1#ARCH_104#684#712#SMART##00253#### > 00254_1#ARCH_82#27#352#SMART##00254#### > 00254_1#ARCH_54#355#510#SMART##00254#### > 00254_1#ARCH_104#576#604#SMART##00254#### > 00254_1#ARCH_104#606#634#SMART##00254#### > 00254_1#ARCH_104#671#699#SMART##00254#### > 00255_1#ARCH_82#56#425#SMART##00255#### > 00255_1#ARCH_54#428#582#SMART##00255#### > 00255_1#ARCH_104#696#724#SMART##00255#### > > > > > can you suggest me ,what are the improvement i have to make in the above > code > regards > shafreen Shafreen, your code snippet (as you posted it) prints any lines that end with an entry code equal the entry code on the last line of the file, with these lines split at #. The whole thing (as you posted it) could probably be written something like this: =================== # not tested or optimised fh = open('ARCHITECTURE_MAIN.txt').read().splitlines() last_code = fh[-1].split('#')[0] for line in fh: if out_line.startswith(last_code): print out_line.split('#') # it will always print at least the last line of the file =================== HTH :) From Shawn at Milochik.com Fri Aug 17 13:47:16 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Fri, 17 Aug 2007 13:47:16 -0400 Subject: Making a copy (not reference) of a file handle, or starting stdin over at line 0 Message-ID: <2dc0c81b0708171047w7af563ael9c430f38a266bea7@mail.gmail.com> I wrote a script which will convert a tab-delimited file to a fixed-width file, or a fixed-width file into a tab-delimited. It reads a config file which defines the field lengths, and uses it to convert either way. Here's an example of the config file: 1:6,7:1,8:9,17:15,32:10 This converts a fixed-width file to a tab-delimited where the first field is the first six characters of the file, the second is the seventh, etc. Conversely, it converts a tab-delimited file to a file where the first six characters are the first tab field, right-padded with spaces, and so on. What I want to do is look at the file and decide whether to run the function to convert the file to tab or FW. Here is what works (mostly): x = inputFile.readline().split("\t") inputFile.seek(0) if len(x) > 1: toFW(inputFile) else: toTab(inputFile) The problem is that my file accepts the input file via stdin (pipe) or as an argument to the script. If I send the filename as an argument, everything works perfectly. If I pipe the input file into the script, it is unable to seek() it. I tried making a copy of inputFile and doing a readline() from it, but being a reference, it makes no difference. How can I check a line (or two) from my input file (or stdin stream) and still be able to process all the records with my function? Thanks, Shawn From Shawn at Milochik.com Mon Aug 20 16:35:33 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Mon, 20 Aug 2007 16:35:33 -0400 Subject: reading a line in file In-Reply-To: <46C9F88A.9090400@jayloden.com> References: <93066C069973ED448DC2BCEA9C44A7383BE2B2@efmailx> <2dc0c81b0708201029k5909d919vcf0deebae74a79c7@mail.gmail.com> <93066C069973ED448DC2BCEA9C44A7383BE2B4@efmailx> <2dc0c81b0708201207p7f83f2e0l6de15fd70be252a5@mail.gmail.com> <93066C069973ED448DC2BCEA9C44A7383BE2B6@efmailx> <46C9F561.50405@jayloden.com> <2dc0c81b0708201314q727ca3a1s12bef74a25b20abc@mail.gmail.com> <46C9F88A.9090400@jayloden.com> Message-ID: <2dc0c81b0708201335m1a158176o9ea456778d2a8597@mail.gmail.com> Although you're technically correct, I think there's a knee-jerk anti-regex reaction, citing the meaningless overhead. If you're running many thousands of records or something then it becomes a small issue compared to a replace statement or something. But in most cases it makes no difference at all. Run the example script both ways and I'm sure there will be no difference, and I prefer a clear regex to a convoluted (in my opinion) substring call. In any case, it's a preference, and I have never seen anything which convinced me that one should avoid regexes at all costs unless there's no other way to do it. And the comment about solving a problem by using regular expressions creating another problem is just asinine. Like so many other things, it's often repeated without any thought about whether it is true in general, much less in the situation in question. From steven.bethard at gmail.com Tue Aug 7 12:50:10 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 07 Aug 2007 10:50:10 -0600 Subject: Adding a list of descriptors to a class In-Reply-To: <1186503932.110835.293640@x40g2000prg.googlegroups.com> References: <1186503932.110835.293640@x40g2000prg.googlegroups.com> Message-ID: Bob B. wrote: > I've been playing with descriptors lately. I'm having one problem I > can't seem to find the answer to. I want to assign a descriptor to a > list of attributes. I know I should be able to add these somewhere in > the class's __dict__, but I can't figure out where. Here's some code: > > class MyDesc(object): > def __init__(self, name=None, initVal=None): > self.name = name > self.value = initVal > > def __get__(self, obj, objtype): > // Do some stuff > self.value = "blah" > return self.value > > class MyClass(object): > attributes = ('attr1', 'attr2') > for attr in attributes: > exec ("%s=MyDesc('%s')") % (attr, attr) > > // More stuff in the class > > Ok, that "exec" is an ugly hack. There's gotta be someway to plop > this straight into the class's __dict__ without doing that, but when I > try adding self.__class__.__dict__[attr] = MyDesc(attr) in MyClass's > __init__ method, I get the error: "TypeError: 'dictproxy' object does > not support item assignment" Probably the simplest thing is to just add the attributes after the class body, e.g.:: >>> class MyClass(object): ... pass ... >>> for attr in ['attr1', 'attr2']: ... setattr(MyClass, attr, MyDesc(attr)) ... >>> c = MyClass() >>> c.attr1 'blah' Another option would be to use a metaclass to set the class attributes at class creation time:: >>> class Meta(type): ... def __init__(cls, name, bases, bodydict): ... for attr in cls._desc_attrs: ... setattr(cls, attr, MyDesc(attr)) ... >>> class MyClass(object): ... __metaclass__ = Meta ... _desc_attrs = ['attr1', 'attr2'] ... >>> c = MyClass() >>> c.attr1 'blah' HTH, STeVe From exarkun at divmod.com Thu Aug 9 07:48:32 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 9 Aug 2007 07:48:32 -0400 Subject: Stackless Integration In-Reply-To: <1186650027.043779.276520@i38g2000prf.googlegroups.com> Message-ID: <20070809114832.4947.1833247582.divmod.quotient.20482@ohm> On Thu, 09 Aug 2007 09:00:27 -0000, "Justin T." wrote: >Hi, > >I've been looking at stackless python a little bit, and it's awesome. >My question is, why hasn't it been integrated into the upstream python >tree? Does it cause problems with the current C-extensions? It seems >like if something is fully compatible and better, then it would be >adopted. However, it hasn't been in what appears to be 7 years of >existence, so I assume there's a reason. It's not Pythonic. Jean-Paul From willmaier at ml1.net Thu Aug 23 13:34:12 2007 From: willmaier at ml1.net (Will Maier) Date: Thu, 23 Aug 2007 12:34:12 -0500 Subject: My 'time' module is broken, unsure of cause In-Reply-To: <200708231122.55588.bulliver@badcomputer.org> References: <200708231122.55588.bulliver@badcomputer.org> Message-ID: <20070823173412.GP19274@lass.lfod.us> On Thu, Aug 23, 2007 at 11:22:55AM -0600, darren kirby wrote: > Python 2.4.4 (#1, Aug 23 2007, 10:51:29) > [GCC 4.1.2 (Gentoo 4.1.2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import time > 40:42:0 > >>> now = time.time() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'time' Uh...that's obviously not right (as you noticed). You probably have a different module that's shadowing the stdlib's time. To check: Python 2.4.4 (#1, Jul 26 2007, 14:42:10) [GCC 3.3.5 (propolice)] on openbsd4 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> print time.__file__ /usr/local/lib/python2.4/lib-dynload/time.so -- [Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/] From duncan.booth at invalid.invalid Sat Aug 11 12:06:18 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Aug 2007 16:06:18 GMT Subject: Metaclass v.s. Property function. References: <1186835613.178733.81210@q75g2000hsh.googlegroups.com> Message-ID: Jens Thiede wrote: > I don't like the property function, usable in the new-style classes, > because having to remember to manage a list of "foo = property(...)" > assignments just plain sucks, so I wrote a metaclass that does things > a little differently. Please have a look and tell me whether this is > useful or impractical. The metaclass is here: > http://pastebin.com/m5b06b571 and some simple testcode is here: > http://pastebin.com/m382f2ae9. Notice the first line though. > Here's something I posted a while back which lets you use property as a decorator: class C(object): def __init__(self, colour): self._colour = colour @property.set def colour(self, value): self._colour = value @property.get def colour(self): return self._colour @property.delete def colour(self): self._colour = 'none' See: http://groups.google.co.uk/group/comp.lang.python/browse_thread/thread/b442d08c9a019a8/8a381be5edc26340 Whether you like that style is of course a matter of personal opinion. From __peter__ at web.de Fri Aug 17 14:34:14 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 17 Aug 2007 20:34:14 +0200 Subject: question References: <1187373737.410546.70930@w3g2000hsg.googlegroups.com> Message-ID: CarpeSkium at gmail.com wrote: > "I've parsed a webpage into a text file. In doing so, I've kept all > the text I'm interested in, and removed all the text I don't want. My > result is a text file that is comma-separated. However, the text file > is one, very long, single string. I need to substitute every eighth > (8th) comma with a new line ("\n"). I've tried regular expressions, > but don't know how to make this happen on only every eighth comma. I'd > post my code, but none of it works. Thanks for the help." >>> text = "aaa," * 20 >>> from itertools import cycle, groupby >>> print "\n".join(",".join(g) for k, g in groupby(text.split(","), ... key=lambda key, c=cycle([True]*8+[False]*8): c.next())) aaa,aaa,aaa,aaa,aaa,aaa,aaa,aaa aaa,aaa,aaa,aaa,aaa,aaa,aaa,aaa aaa,aaa,aaa,aaa, :-) Peter From david at asdf.asdf Sun Aug 26 23:41:17 2007 From: david at asdf.asdf (bambam) Date: Mon, 27 Aug 2007 13:41:17 +1000 Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com><1187898049.734696.9500@l22g2000prc.googlegroups.com><13csi2tn49esmc3@corp.supernews.com> <13csqk47j0c56b0@corp.supernews.com> <13ct7v3qn2v5206@corp.supernews.com> <13d49lk6ue2as6d@corp.supernews.com> Message-ID: <13d4hutad1dq699@corp.supernews.com> Is it safe to write A = [x for x in A if x in U] or is that undefined? I understand that the slice operation can be used to make a temporary copy, so I could write A=[x for x in A[:] if x in U] but I've just copied that without any understanding. Steve. "bambam" wrote in message news:13d49lk6ue2as6d at corp.supernews.com... > That looks good, and perhaps a difference operator > would be too simple to be useful anyway. > > Steve. > > "Mikael Olofsson" wrote in message > news:mailman.238.1187948359.32294.python-list at python.org... >> >> >> bambam wrote: >>> >>> In this case it doesn't matter - my lists don't contain >>> duplicate elements this time - but I have worked with lists in >>> money market and in inventory, and finding the intersection >>> and difference for matching off and netting out are standard >>> operations. >> >> I would use a list comprehension for that case: >> >> A = ['a','b','c','a','c','d'] >> U = ['a','b','e'] >> B = [x for x in A if x in U] >> >> The result would be B==['a','b','a'] >> >> /MiO > > From erik at myemma.com Thu Aug 23 13:44:21 2007 From: erik at myemma.com (Erik Jones) Date: Thu, 23 Aug 2007 12:44:21 -0500 Subject: comparing two lists In-Reply-To: <46CDB57C.9080701@iptel.org> References: <46CDB57C.9080701@iptel.org> Message-ID: On Aug 23, 2007, at 11:27 AM, Ladislav Andel wrote: > Hi, > what would be the most efficient way to do following? > > I have a list of dictionaries taken from DB e.g. > dblist = [{'id:1, 'host':'google.com','ip_address':'1.2.3.4'}, > {'id:3, 'host':'yahoo.com','ip_address':'5.6.7.8'}, > {'id:9, 'host':'msn.com','ip_address':'11.3.2.3'}] > > and list of object instances in memory(it's just for example) > which are looping within itself and testing particular hosts > > memlist = [,] > memlist[0].id is 1 and memlist[0].host is google.com etc. > memlist[1].id is 9 and memlist[1].host is msn.com etc. > > Now I want to add a new instance to memlist since id=3(in dblist) > is not > in memlist. > How would you iterate through it and insert a new instance? > > The result should be: > memlist = [,, ] > memlist[0].id is 1 and memlist[0].host is google.com etc. > memlist[1].id is 3 and memlist[1].host is yahoo.com etc. > memlist[2].id is 9 and memlist[2].host is msn.com etc. Well, if you add a constructor for object instances that can take those dictionaries you could do something like: for row in dblist.iteritems(): obj = Obj(row) # where Obj is your classname if obj is not in memlist: memlist.append(obj) > > Furthermore, I can have the opposite situation. > This time I need to remove from memlist a host which is not in dblist. > How would you do this? Similarly, if you add an toHash() method to you object class you could do something like (using the reverse iteration solution mentioned in another reply): for i in range(len(memlist) -1, -1, -1): if memlist[[i].toHash() not in dblist: del memlist[i] Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From aboudouvas at panafonet.gr Fri Aug 10 06:21:29 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Fri, 10 Aug 2007 03:21:29 -0700 Subject: Question about properties. Message-ID: <1186741289.074717.174370@e16g2000pri.googlegroups.com> Hi, i read in a book the following code snippet that is dealing with properties: class ProtectAndHideX(object): def __init__(self, x): assert isinstance(x, int), '"x" must be an integer!"' self.__x = ~x def get_x(self): return ~self.__x x = property(get_x) Can anyone please help me understand what the symbol "~" does here ?? Thanks for any help! From lew at lewscanon.com Mon Aug 20 17:51:51 2007 From: lew at lewscanon.com (Lew) Date: Mon, 20 Aug 2007 17:51:51 -0400 Subject: Latest models of Gibson guitars In-Reply-To: <1187623025.845370.251530@x40g2000prg.googlegroups.com> References: <1187544898.289948.322160@22g2000hsm.googlegroups.com> <190820071924351381%rag@nospam.techline.com> <1187623025.845370.251530@x40g2000prg.googlegroups.com> Message-ID: RickH wrote: > On Aug 19, 9:24 pm, Randall Ainsworth > wrote: >> In article , Hermit >> >> wrote: >>> How does the image quality compare with a DSLR? >> Depends on whether it's a Paul or a Strat. > > A Strat is a Fender, but I'd rather win a Gibson es175. Please do not include comp.lang.java.programmer in this discussion, as it is waaaay off topic. -- Lew From pavlovevidence at gmail.com Mon Aug 20 01:55:17 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 20 Aug 2007 05:55:17 -0000 Subject: Python question (PyNoob) In-Reply-To: <3uOdnbA4Bc27fFXbnZ2dnUVZ8vidnZ2d@bt.com> References: <3uOdnbA4Bc27fFXbnZ2dnUVZ8vidnZ2d@bt.com> Message-ID: <1187589317.743813.241930@l22g2000prc.googlegroups.com> On Aug 19, 8:33 pm, Anonymous wrote: > I have exp with C/C++ (and a few other langs). I want to use Python to > start doing the ff: > > 1). Data Munging (text processing) - instead of Perl > 2). Automating my build process > 3). (Possibly) some web data retrieval jobs > > Can anyone point me to resurces/possibly scripts that can get me up to > speed (to do these 3 things) ASAP, without having to learn the basics of > programming? You want the Python Library Reference (quod googla). If you know the basics of programming already, any old Python tutorial will do, so just skim through the official one (q.g.) to pick up the syntax and semantic rules. Then refer to the Library Reference, which is well organized and make it easy to track down what you need. The libraries come with very good built-in support for tasks 1 and 3; for 2 Python supports timestamp checking and subprocess calling and whatnot, but stuff like dependency trees you'll have to work out yourself. (BTW, if "make" is failing or annoying you, you might want to consider SCons, which for me has been a lot more intelligent and straightforward than make ever was.) Carl Banks From jantod at gmail.com Tue Aug 14 06:16:24 2007 From: jantod at gmail.com (Janto Dreijer) Date: Tue, 14 Aug 2007 10:16:24 -0000 Subject: Fast kNN from python Message-ID: <1187086584.076990.260680@r34g2000hsd.googlegroups.com> Hi! I am looking for a Python implementation or bindings to a library that can quickly find k-Nearest Neighbors given an arbitrary distance metric between objects. Specifically, I have an "edit distance" between objects that is written in Python. I haven't looked at the methods in detail but I think I'm looking for one of the data structures listed on http://en.wikipedia.org/wiki/Metric_trees (i.e. vp-trees, cover trees, m-trees or bk trees). But I might be wrong. An approximate kNN would also work. If there doesn't exist such an implementation yet, any advice on a library I can wrap myself would also be appreciated. Thanks! Janto PS Before anyone suggests it, I can't use the library at http://www.cs.umd.edu/~mount/ANN/ as it assumes Minkowski distance functions. From steve at holdenweb.com Thu Aug 16 23:23:13 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 16 Aug 2007 23:23:13 -0400 Subject: why psyco using more memery in liunx? In-Reply-To: <005d01c7e078$c13d0ed0$811ba8c0@kyom> References: <005d01c7e078$c13d0ed0$811ba8c0@kyom> Message-ID: <46C514A1.9060503@holdenweb.com> kyo guan wrote: > Hi all: > > When you import psyco in python2.5, you can see the memery grow up near 40MB in linux. but the same version python and > psyco, is only grow up 1MB under windows. > Please don't repeat the question again. It *has* reached the list. Patience is a virtue ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From dogatemycomputer at gmail.com Wed Aug 22 16:27:17 2007 From: dogatemycomputer at gmail.com (dogatemycomputer at gmail.com) Date: Wed, 22 Aug 2007 20:27:17 -0000 Subject: Learning Python using a book based on version 1.5 Message-ID: <1187814437.775758.159510@e9g2000prf.googlegroups.com> Greetings, A friend of mine dropped off a copy of Sams Teach Yourself Python in 24 Hours published in 2000. I skimmed the first couple of chapters looking for the interpreter version and the book was based on version Python version 1.5. Is this book still relevant? Should I toss it and look for something newer? Any thoughts would be appreciated. Best Regards, Dave From mccredie at gmail.com Mon Aug 27 12:52:50 2007 From: mccredie at gmail.com (Matt McCredie) Date: Mon, 27 Aug 2007 09:52:50 -0700 Subject: the del function In-Reply-To: References: Message-ID: <9e95df10708270952p188b8702r3b778d6a1e60c30c@mail.gmail.com> > For some odd reason the del array[ray] isn't actually deleting the array > item in the list I get the following output: > > C:\Documents and > Settings\program\Desktop\python\pygame>remix.py > [2, 2, 2, 4, 4, 4, 4, 3, 3, 3, 3] > [2, 2, 2, 4, 4, 4, 4, 3, 3, 3, 3] > [2, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3] > [2, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3] > [2, 2, 4, 4] > > The _red function is fine, but the del function isn't working. What did I > do wrong? The code is doing what you told it to: [code] while x < 4: array = single_players[4:17] # <-- you are re-creating `array' in every loop length = len(array) - 1 ray = random.randint(0,length) _red[x] = array[ray] del array[ray] print array x = x + 1 print _red [/code] My guess is that you want this: [code] array = single_players[4:17] while x < 4: length = len(array) - 1 ray = random.randint(0,length) _red[x] = array[ray] del array[ray] print array x = x + 1 print _red [/code] I'm sure you could do something with random.shuffle or random.choice though that would be much cleaner. It isn't entirely clear what you are trying to do though, so I'm stopping short of posting any code. Matt From BjornSteinarFjeldPettersen at gmail.com Sun Aug 19 21:47:05 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Mon, 20 Aug 2007 01:47:05 -0000 Subject: Sorting a list of Unicode strings? In-Reply-To: <1i338vd.1kisqttkij0d9N%aleax@mac.com> References: <1187542237.139346.6910@o80g2000hse.googlegroups.com> <46C87772.2010603@web.de> <1187543116.941243.200960@r34g2000hsd.googlegroups.com> <1i338vd.1kisqttkij0d9N%aleax@mac.com> Message-ID: <1187574425.046278.140930@o80g2000hse.googlegroups.com> On Aug 19, 8:09 pm, al... at mac.com (Alex Martelli) wrote: [...] > In both Swedish and Danish, I believe, A-with-ring sorts AFTER the > letter Z in the alphabet; so, having ?aland (where I'm using Aa for > A-with-ring, since this newsreader has some problem in letting me enter > non-ascii characters;-) sort "right at the bottom", while it "doesn't > look right" to YOU (maybe an English-speaker?) may look right to the > inhabitants of that locality (be they Danes or Swedes -- but I believe > Norwegian may also work similarly in terms of sorting). You're absolutely correct, the Norwegian and Danish alphabets end with ..xyz???, while the Swedish alphabet ends with ..xyz??? and sort order follows placement. Indeed, my first reaction to the op was: where else would ?land be but at the end? One, perhaps interesting, tidbit, is that ?land "belongs" to Finland (it's an autonomous, demilitarized, monolingually Swedish-speaking administrative province of Finland). The Finnish alphabet is identical to the Swedish alphabet, including sort order (at least in this case) For the ascii-speakers out there, the key point to remember is that the letter ? (pronounced like the au in brittish autumn) is not an ascii A with a ring on top. The ring-on-top is an intrinsic part of the letter, in the same way the tail on the letter Q isn't a decoration of the letter O. -- bjorn From http Mon Aug 6 18:25:51 2007 From: http (Paul Rubin) Date: 06 Aug 2007 15:25:51 -0700 Subject: Tkinter or wxpython? References: <1186410331.905174.21370@q3g2000prf.googlegroups.com> <7xps204tin.fsf@ruckus.brouhaha.com> <7xlkcopu4r.fsf@ruckus.brouhaha.com> <7x3aywr4tc.fsf@ruckus.brouhaha.com> <7x8x8oqy17.fsf@ruckus.brouhaha.com> Message-ID: <7xy7gopafk.fsf@ruckus.brouhaha.com> "Chris Mellon" writes: > You repeatedly have used the word "slickness" as a pejorative. I find > that offensive and it's insulting to users. When I write applications, > I want the interface to be as smooth and trouble free as possible, It's a perjorative when it's done for its own sake and doesn't really help the user. This happens a lot. When it helps the user, as it sometimes does, then it's not perjorative. > As a matter of time spent in development, I do not find that > non-trivial UIs are significantly easier to develop using web > interfaces. That's possibly true, but a lot of the time, trivial interfaces are enough. Look at Google search, one of the most complex apps ever built (tens or hundreds of MLOC, massive distributed crawler infrastructure, 100's of PhD's figuring out the algorithms, etc.) but its interface is simple HTML that you would probably call trivial. It is quite possibly the most popular application in the world. > As a matter of respect for the user, I'm not going to tell them to use > a trivial UI if a non-trivial one will save them time, learning > effort, or frustration. In order to make this decision, I like to work > with the people actually using it and watch them at work. To see what > kind of extra steps they have to take and where I can save them time > or inaccuracy or frustration. Right. Obviously this has to be decided according to the specific needs of the application. A lot of times, trivial interfaces are easier to learn than nontrivial ones, precisely because they are trivial so there is less to learn. Again look at Google search for an example. Also, at least for in-house applications, while the user's time counts (since their time costs your customer money), your development time and deployment effort also costs money that comes from exactly the same place, so you have to take into consideration the number of users, amount of time they will spend using the program, just how much of that time (if any) a fancier interface will save, etc. From esj at harvee.org Wed Aug 29 22:09:54 2007 From: esj at harvee.org (Eric S. Johansson) Date: Wed, 29 Aug 2007 22:09:54 -0400 Subject: IDE for Python In-Reply-To: <87tzqhewsq.fsf@benfinney.id.au> References: <46CAB7D4.5070308@gmail.com> <87tzqhewsq.fsf@benfinney.id.au> Message-ID: <46D626F2.80803@harvee.org> Ben Finney wrote: > Stefan Behnel writes: > "Neither"? Emacs is both editor *and* IDE. I think of it more as feature full but somehow unsatisfying. For example, for those of us PRDs ( Politely Referred to as Disabled) who are trying to program by voice could use an enumeration of all symbols visible from a cursor on outward through method, class, and file scope, etc. then we can take we can speak symbols and make them pronounceable as well as synthesize a grammar so that one can refer to symbols in the object hierarchy by absolute paths as well as individual symbols. it's just an idea at this stage but it could be fun to see how well it would work in real life From pyscottishguy at hotmail.com Wed Aug 8 12:00:12 2007 From: pyscottishguy at hotmail.com (pyscottishguy at hotmail.com) Date: Wed, 08 Aug 2007 16:00:12 -0000 Subject: 'Advanced' list comprehension? query Message-ID: <1186588812.006107.185570@o61g2000hsh.googlegroups.com> Hi, I'm playing around with list comprehension, and I'm trying to find the most aesthetic way to do the following: I have two lists: noShowList = ['one', 'two', 'three'] myList = ['item one', 'item four', 'three item'] I want to show all the items from 'myList' that do not contain any of the strings in 'noShowList'. i.e. 'item four' I can do it like this: def inItem(noShowList, listitem): return [x for x in noShowList if x in listitem] print [x for x in myList if not inItem(noShowList, x)] and I can do it (horribly) with: print [x for x in myList if not (lambda y, z:[i for i in y if i in z]) (noShowList, x)] I can also print out the items that DO contain the 'noShowList' strings with: print [x for x in myList for y in noShowList if y in x] but I can't get the 'not' bit to work in the above line. Any ideas? Thanks! From kyosohma at gmail.com Tue Aug 14 08:57:11 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 14 Aug 2007 05:57:11 -0700 Subject: Opinions about this new Python book? In-Reply-To: References: Message-ID: <1187096231.194685.86030@m37g2000prh.googlegroups.com> On Aug 14, 7:05 am, Dick Moores wrote: > I'd appreciate opinions about this new Python book. > > Title: Python Power!: The Comprehensive Guide > Author: Matt Telles > Publisher: Course Technology > Pub. Date: Jul 27, 2007 > Edition: 1st edition > Binding: Paperback > Pages: 508 > ISBN: 1598631586 > List Price: 34.99 USD > > The book on the publisher's website: > > And at BestBookDeal.com: > > > Thanks, > > Dick Moores I just got this book over the weekend. I'll start reading/skimming through it this week and hopefully remember to get back to you. By the way, why do you want to know? Mike From aleax at mac.com Mon Aug 13 11:28:23 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 13 Aug 2007 08:28:23 -0700 Subject: Help with optimisation References: <46c06b51$0$11684$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <1i2rzhj.sv9wn758l2grN%aleax@mac.com> special_dragonfly wrote: ... > dom=xml.dom.minidom.parseString(text_buffer) If you need to optimize code that parses XML, use ElementTree (some other parsers are also fast, but minidom ISN'T). Alex From robin at reportlab.com Tue Aug 28 13:03:33 2007 From: robin at reportlab.com (Robin Becker) Date: Tue, 28 Aug 2007 18:03:33 +0100 Subject: sys.setdefaultencoding Message-ID: <46D45565.8000701@chamonix.reportlab.co.uk> Can someone explain the rationale of making the default encoding a sitewide setting? I could live with the the default being set on a per process basis, but it baffles me why even that possibility is taken away as site.py removes sys.setdefaultencoding. Is there a way to allow the process to specify that unicode-->str should use 'utf8' rather than 'ascii' in all non-specific cases? -- Robin Becker From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Aug 13 18:44:18 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 14 Aug 2007 00:44:18 +0200 Subject: wxPython - drawing without paint event References: <1186710391.148396.113490@d30g2000prg.googlegroups.com> <1186738813.373909.96230@x35g2000prf.googlegroups.com> <1186796567.331348.42450@q3g2000prf.googlegroups.com> <5i5l0dF2lortaU1@mid.individual.net> <1186883988.585048.16590@m37g2000prh.googlegroups.com> <5i8befF3o5no1U1@mid.individual.net> <1186928595.014008.61950@b79g2000hse.googlegroups.com> <5i98bsF3nmbavU1@mid.individual.net> <1186951326.218981.17820@b79g2000hse.googlegroups.com> <1186966731.768800.81620@x40g2000prg.googlegroups.com> <5ibsenF3nq29uU2@mid.individual.net> <1187037162.322154.319540@x40g2000prg.googlegroups.com> Message-ID: <5ic562F3pi903U2@mid.individual.net> kyosohma at gmail.com wrote: > I guess I haven't looked up any wxPython tutorials. I typically > use a combination of the wxPython wiki, the demo and the WIA book > for my work. Me too (except the mailing list, occasionally), and it works quite well. Regards, Bj?rn -- BOFH excuse #306: CPU-angle has to be adjusted because of vibrations coming from the nearby road From fshu at cisco.com Wed Aug 15 12:32:55 2007 From: fshu at cisco.com (Fred Shu (fshu)) Date: Wed, 15 Aug 2007 09:32:55 -0700 Subject: how to convert a c program to java program Message-ID: I heard I need to port C program to JPython first and compile it to native JAVA. I don't know anything about JPython. Is there a tool to do the porting? If not, what is the quickest way to learn JPython? Thanks, Fred -------------- next part -------------- An HTML attachment was scrubbed... URL: From mccredie at gmail.com Fri Aug 17 16:11:34 2007 From: mccredie at gmail.com (Matt McCredie) Date: Fri, 17 Aug 2007 13:11:34 -0700 Subject: how to convert a c program to java program In-Reply-To: <9e95df10708171310s5df2e2cjbe4885bb2d5e401a@mail.gmail.com> References: <9e95df10708171310s5df2e2cjbe4885bb2d5e401a@mail.gmail.com> Message-ID: <9e95df10708171311p5f9ad99dn373e0ad69f716d6e@mail.gmail.com> > I heard I need to port C program to JPython first and compile it to native > JAVA. I don't know > anything about JPython. Is there a tool to do the porting? If not, what is > the quickest way to learn > JPython? I'm assuming that you are refering to Jython. You probably want to start by learning Python, since Jython is essentially just an implementation of Python written in Java. I'm not sure why you need to involve Jython at all though. Syntax wise there are many more similarities between C and Java than there are between C and Python or Python and Java. Anyway, if you want to learn Python try one of these: http://python.org/doc/tut/ or http://www.diveintopython.org/. Matt From maventheextrawords at techie.com Wed Aug 8 06:18:02 2007 From: maventheextrawords at techie.com (-Lost) Date: Wed, 08 Aug 2007 05:18:02 -0500 Subject: Compiling PythonD using DJGPP References: <46a38c61$0$16279$88260bb3@free.teranews.com> Message-ID: John Simeon's response: > My problem is that I am getting a compiler error that I do not > understand: > > gcc -c -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes > -I. -I./Include > -DPy_BUILD_CORE -o Python/compile.o Python/compile.c > Python/compile.c: In function 'optimize_code': > Python/compile.c:512: warning: pointer targets in assignment differ in > signedness > Python/compile.c: At top level: > Python/compile.c:1038: error: two or more data types in declaration > specifiers > Python/compile.c:1232: error: two or more data types in declaration > specifiers > Python/compile.c: In function 'com_addbyte': > Python/compile.c:1232: error: parameter name omitted > Python/compile.c:1241: error: expected expression before 'unsigned' > make.exe: *** [Python/compile.o] Error 1 > > Does anyone have any ideas that could help shed some light on this and > help me get back on track? You realize this is not a Python question right? Or rather, it is not an error specific to Python. It is an error related to a specific compiler, and more specifically a non-standard implementation of Python. You'd have much better luck following the advice of the author of PythonD and and taking this question to [ news:comp.os.msdos.djgpp ]. -- -Lost Remove the extra words to reply by e-mail. Don't e-mail me. I am kidding. No I am not. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Aug 11 07:31:25 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 11 Aug 2007 13:31:25 +0200 Subject: wxPython - drawing without paint event References: <1186710391.148396.113490@d30g2000prg.googlegroups.com> <1186738813.373909.96230@x35g2000prf.googlegroups.com> <1186796567.331348.42450@q3g2000prf.googlegroups.com> Message-ID: <5i5l0dF2lortaU1@mid.individual.net> glenn.chappell at gmail.com wrote: > On a related topic, it seems like it would be nice to do *all* > drawing in > response to paint events. When I get an event from the timer, I > would just tell wx that part of the window needs redrawing, and > depend on it to give me a paint even when nothing of higher > priority needs to be done. > I've seen this kind of logic recommended in other GUI tookits. Is > it a good idea in wxPython, and, if so, how does one do it? At least it is not required -- there are device contexts for use inside and outside of paint events. One nice strategy from an example in "wxPython in Action" is the following: * the frame has Draw methods that draw into a BufferedDC, which is chained to a bitmap member * inside the paint method, the bitmap member is drawn to screen Regards, Bj?rn -- BOFH excuse #393: Interference from the Van Allen Belt. From gagsl-py2 at yahoo.com.ar Wed Aug 22 09:45:29 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 22 Aug 2007 06:45:29 -0700 Subject: Design philosophy of HTTPServer and BaseHTTPRequestHandler In-Reply-To: <1187776216.269456.310230@q4g2000prc.googlegroups.com> References: <1187776216.269456.310230@q4g2000prc.googlegroups.com> Message-ID: <1187790329.575480.14070@i38g2000prf.googlegroups.com> On 22 ago, 06:50, "tzuchien chiu gmail com" wrote: > Hello, everyone. > > Several instances of a same script, which accepts parameters and does > a lengthy job, are executed on a remote machine. I want to couple the > script with a tiny HTTP server so that I can connect to the machine > with a browser and monitor the progress of jobs. The HTTP server of > each instance will bind to different ports. > > A BaseHTTPRequestHandler-derived class must somehow know the > parameters of each instance/job in order to return instance/job- > specific result back to the client in do_GET. However, there is no way > to pass parameters (of the lengthy job) because the constructor of > HTTPServer expects a BaseHTTPRequestHandler-derived "class", instead > of an "object". > > I cannot (or should not) dynamically create a "BaseHTTPRequestHandler- > derived "class" for each instance of the script, right? > > Do I misunderstand the design philosophy of HTTPServer and > BaseHTTPRequestHandler, and they should not be used in this way? The server is permanent; request handler instances are created and destroyed as HTTP requests arrive and are processed. You should store any permanent info in the server; your "BaseHTTPRequestHandler-derived class" can reference the server using its "server" attribute. -- Gabriel Genellina From wbrehaut at mcsnet.ca Tue Aug 21 16:56:31 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Tue, 21 Aug 2007 14:56:31 -0600 Subject: How to optimise this code? References: <46CB3635.7050705@biotec.tu-dresden.de> <87mywk1x25.fsf@mulj.homelinux.net> Message-ID: <1bkmc31iqs6udgl7of7f9q8bjq9fknfkgg@4ax.com> On Tue, 21 Aug 2007 21:56:18 +0200, Hrvoje Niksic wrote: >Christof Winter writes: > >> To get rid of the if statements, replace __init__ function with: >> >> def __init__(self, tc): >> functionToCall = eval("self.testCase%s" % tc) > >Or functionToCall = getattr(self, "testCase" + tc) > >eval can introduce unwanted side effects. Hence the slogan "Do No Eval!" wwwayne From I_Dickinson at bitwise.co.uk Mon Aug 20 09:00:24 2007 From: I_Dickinson at bitwise.co.uk (Ian Dickinson) Date: Mon, 20 Aug 2007 14:00:24 +0100 Subject: Handwriting Recognition Message-ID: <46C99E77.F136.00C8.0@bitwise.co.uk> Hi My name is Ian Dickinson and I am a professional software developer working in the UK and reasonably familiar with Python. However a friend of mine who is a special educational needs teacher was asking me if I could write some handwriting recognition software for her, which would allow here pupils to write their input directly on a graphics tablet and then have this input converted to a text sting for further processing. The handwriting would be distinct letters either upper or lower case but not joined up writing. I would like to help out here as I think this is a valuable and worthwhile area of education so has anyone out there got any advice that could help me out. Thanks in advance Ian From http Mon Aug 27 15:27:26 2007 From: http (Paul Rubin) Date: 27 Aug 2007 12:27:26 -0700 Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com> <1187898049.734696.9500@l22g2000prc.googlegroups.com> <13csoronscqp7d2@corp.supernews.com> <1188090322.663217.102750@22g2000hsm.googlegroups.com> <13d4bucfm4m1lc4@corp.supernews.com> <13d4gjm3qq0lt7c@corp.supernews.com> Message-ID: <7x1wdohj6p.fsf@ruckus.brouhaha.com> Neil Cerutti writes: > i = 0 > while i < self.parent.GetPageCount(): > # do stuff > i += 1 Alternatively: from itertools import count for i in count(): if i >= self.parent.GetPageCount(): break ... From no at spam.com Thu Aug 2 15:37:11 2007 From: no at spam.com (Farshid Lashkari) Date: Thu, 02 Aug 2007 12:37:11 -0700 Subject: Catching SystemExit in C API code when embedding Python? In-Reply-To: <20070802212949.222081eb@cube.tz.axivion.com> References: <20070802141906.2581c099@cube.tz.axivion.com> <20070802212949.222081eb@cube.tz.axivion.com> Message-ID: Stefan Bellon wrote: > Thanks for your hints ... > > The interesting part is "Call python code". In my example this is done > with PyRun_SimpleString which does not return if an exception is not > handled but raised "out of" the interpreter. So I am unsure of what you > mean with "Call python code". > > When installing an excepthook (see my other posting), then I can indeed > catch all exceptions ... except for SystemExit which is the one I'm > after. > You cannot use PyRun_SimpleString, since it will automatically print and clear the error. You will need to use PyRun_String instead. From hd1956 at yahoo.com Tue Aug 21 12:52:11 2007 From: hd1956 at yahoo.com (hd1956 at yahoo.com) Date: Tue, 21 Aug 2007 16:52:11 -0000 Subject: Newbee Question In-Reply-To: <1187685502.855643.122800@r34g2000hsd.googlegroups.com> References: <1187621470.484615.7010@i13g2000prf.googlegroups.com> <1187622390.854759.162320@q3g2000prf.googlegroups.com> <1187650036.450645.185500@a39g2000hsc.googlegroups.com> <1187685502.855643.122800@r34g2000hsd.googlegroups.com> Message-ID: <1187715131.514463.84960@57g2000hsv.googlegroups.com> On Aug 21, 4:38 am, Ant wrote: > On Aug 20, 11:47 pm, hd1... at yahoo.com wrote: > ... > > > Thanks for the help. By the way I am trying to learn the python after > > work and on weekends. If it was a dumb question, to this group, I will > > not bother you all again. > > It's not so much that it was a dumb question, but that it was asked in > a dumb way :-) You'll get the most help in this group if you can show > some evidence that you've had a go (the size of this thread ironically > trounces that argument of course ;-) .) > > It's better to learn if people give you a critique of your own attempt > at the code, rather than looking at other peoples efforts. There's a > guide on how to ask good questions here:http://www.catb.org/~esr/faqs/smart-questions.html > > For what it's worth, here's a gratuitous version using generators, and > one you should come back to once you've mastered the basics of Python: > > def counter(std_rate, over_rate, limit): > stops = 0 > while True: > stops += 1 > wage = stops * std_rate + max(0, stops - limit) * (over_rate - > std_rate) > yield stops, wage > > truck = counter(0.4, 1.4, 22) > > for i in range(30): > print "Stopped %s times, with accumulated wage of $%s" % > truck.next() > > -- > Ant... > > http://antroy.blogspot.com/ I tryed your code and got an error message #I use Wing IDE: Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] Type "help", "copyright", "credits" or "license" for more information. >>> Evaluating lines 1-16 from truckStops.py :7: Warning: 'yield' will become a reserved keyword in the future Could not execute because an error occurred: invalid syntax: , line 7, pos 19: yield stops, wage From stefan.behnel-n05pAM at web.de Wed Aug 29 12:51:59 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 29 Aug 2007 18:51:59 +0200 Subject: general function for sorting a matrix In-Reply-To: <1188402447.290663.307640@z24g2000prh.googlegroups.com> References: <1188402447.290663.307640@z24g2000prh.googlegroups.com> Message-ID: <46D5A42F.3080900@web.de> Xah Lee wrote: [undermotivated blah stripped] don't feed the troll. Stefan From DjGoldsmith at googlemail.com Mon Aug 13 05:57:21 2007 From: DjGoldsmith at googlemail.com (DjGoldsmith at googlemail.com) Date: Mon, 13 Aug 2007 09:57:21 -0000 Subject: Complexity of methods etc In-Reply-To: References: Message-ID: <1186999041.283576.211210@22g2000hsm.googlegroups.com> On Aug 13, 1:04 am, "Nathan Harmston" wrote: > Hi, > > I was wondering if anyone knew of any resources, where I might be able > to find information about the complexity of certain python functions > or little tips on how to reduce complexity. I mean like the "".join(), > kind of thing? > > I want to see if there are any improvements I can add to my coding in > order to reduce time/space usage/ > > Many Thanks in advance > > Nathan I found the two Python Speed articles useful for demonstrating new ways to optimise code. Each is full of little tricks and tips on efficent ways of doing things. http://wiki.python.org/moin/PythonSpeed http://wiki.python.org/moin/PythonSpeed/PerformanceTips Dan From byte8bits at gmail.com Tue Aug 21 15:58:52 2007 From: byte8bits at gmail.com (brad) Date: Tue, 21 Aug 2007 15:58:52 -0400 Subject: Microsoft Vista and os.exec In-Reply-To: <1187725385.938752.290390@r34g2000hsd.googlegroups.com> References: <1187725385.938752.290390@r34g2000hsd.googlegroups.com> Message-ID: franko353 wrote: > I have wxPython programs that work fine in Win2000/XP using os.exec(). > > They do not work in MS Vista. Has anyone else had any luck with > exec()? > > I keep getting an 'invalid option' error. > > It turn out it was really a security issue and I had to move to a > "win32process.CreateProcess" solution to fix this under Vista. > > There is a good example of using CreateProcess in the "Python > programming on Win32" book. > I've also had issues with Vista... mine have to do with the execution of scripts. I don't have a test vista box in front of me right now, all of my vmware vistas have deactivated me into 'reduced functionality mode'. Basically, on XP, when I execute a script it runs in the directory that it executed in, but in Vista, it executes elsewhere... I don't remember where exactly right off the top of my head. Other than that issue it seems to work fine even with wxPython. From fdu.xiaojf at gmail.com Thu Aug 2 02:51:52 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Thu, 02 Aug 2007 14:51:52 +0800 Subject: a dict trick In-Reply-To: <1186036331.304916.304020@e9g2000prf.googlegroups.com> References: <1186036331.304916.304020@e9g2000prf.googlegroups.com> Message-ID: <46B17F08.8030209@gmail.com> james_027 wrote: > hi > > for example I have this dictionary > > dict = {'name':'james', 'language':'english'} > > value = 'sex' in dict and dict['sex'] or 'unknown' > > is a right pythonic of doing this one? I am trying to get a value from > the dict, but if the key doesn't exist I will provide one. > > THanks > james > value = your_dict.get(key, default_value) From uymqlp502 at sneakemail.com Fri Aug 31 21:32:55 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Fri, 31 Aug 2007 18:32:55 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> Message-ID: <1188610375.710983.4780@m37g2000prh.googlegroups.com> Ricardo Ar?oz wrote: > Actually my point was that if a program is to be trusted in a critical > situation (critical as in catastrophe if it goes wrong) then the OS, the > compiler/interpreter etc should abide by the same rules. That is > obviously not possible, so there's not much case in making the time > investment necessary for correctness proof of a little program (or > usually a little function inside a program) when the possibilities for > failure are all around it and even in the code that will run that > function. And we should resort to other more sensible answers to the > safety problem. I don't quite see it that way. I would agree that if your OS and compiler are unreliable, then it doesn't make much sense to bend over backwards worrying about the reliability of your application. But for real safety-critical applications, you have no excuse for not using a highly reliable OS and compiler. For really critical stuff, I think the real-time OSs are usually stripped down to the bare basics. And if you are using something like SPARK Ada, the language itself is stripped of many of the fancier features in Ada itself. (There's also something called the Ada Ravenscar profile, which I believe is geared for safety-critical use but is not quite as restrictive as SPARK.) Keep in mind that the OS and compiler are typically also used for many other applications, so they tend to get tested fairly thoroughly. And remember also that you won't have extraneous applications running -- like a web browser or a video game, so the OS will probably not be heavily stressed. The most likely source of failure is likely to be your application, so bending over backwards to get it right makes sense. Then again, if you are running C on Windows, you might as well just give up on reliability from the start. You don't have a prayer. From steve at holdenweb.com Thu Aug 23 17:24:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 23 Aug 2007 17:24:52 -0400 Subject: creating a tar file with python In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> Message-ID: Brian McCann wrote: > Hi, > > I'm trying to create a tar file of the contents of the current directory > > right now there is only one file "text.xml" in the current dir, I'm > using"." current dir as source > but that gives syntax error > > any help would be greatly appreciated > --Brian > > > #!/usr/bin/python > import string > import os > import sys > import time > import errno > import shutil > import tarfile > > > tar = tarfile.open(.,"test.tar.gz", "w:gz) > > > well, /probably/ (meaning I haven't done any testing) you need quotes around the name of the current directory just like you do around the name of the file. Try tar = tarfile(".", "test.tar.gz", "w:gz") regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From danmcleran at yahoo.com Wed Aug 1 12:09:00 2007 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: Wed, 01 Aug 2007 09:09:00 -0700 Subject: Assertion in list comprehension In-Reply-To: <1185982643.001546.138180@e16g2000pri.googlegroups.com> References: <1185982643.001546.138180@e16g2000pri.googlegroups.com> Message-ID: <1185984540.245193.270110@i13g2000prf.googlegroups.com> On Aug 1, 9:37 am, beginner wrote: > Hi, > > Does anyone know how to put an assertion in list comprehension? I have > the following list comprehension, but I want to use an assertion to > check the contents of rec_stdl. I ended up using another loop which > essentially duplicates the functions of list comprehension. It just > look like a waste of coding and computer time to me. > > I just wish I could put the assertions into list comprehensions. > > x=[(rec_stdl[0].st/10000.0, > rec_stdl[0].cl, > rec_stdl[0].bb, > rec_stdl[0].bo, > rec_stdl[1].bb, > rec_stdl[1].bo, > rec_stdl[0].ex > ) > for rec_stdl in rec_by_ex if len(rec_stdl)==2 > ] > > #duplicated loop > if __debug__: > for rec_stdl in rec_by_ex: > l=len(rec_stdl) > assert(l<=2 and l>0) > if l==2: > assert(rec_stdl[0].c=="C" and rec_stdl[1].c=="P") > assert(rec_stdl[0].ex==rec_stdl[1].ex) > assert(rec_stdl[0].st==rec_stdl[1].st) > assert(rec_stdl[0].cp==rec_stdl[1].cp) > > Thanks, > Geoffrey Can't you just call a function from within your list comprehension and do whatever you want for each item? Something like this (not tested): def checker(item): assert(len(item) <= 2 and len(item) > 0) if len(item) == 2: assert(item[0].c == "C" and item[1].c == "P" return len(item) == 2 x = [whatever for item in all_items if checker(item = item)] From __peter__ at web.de Tue Aug 21 16:53:04 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 21 Aug 2007 22:53:04 +0200 Subject: Adjusting the names of custom exceptions (since raising strings is deprecated) References: <1187672085.263963.157470@z24g2000prh.googlegroups.com> <5qxyi.18719$eY.12647@newssvr13.news.prodigy.net> <1187723880.146487.36250@l22g2000prc.googlegroups.com> Message-ID: Silfheed wrote: > On Aug 21, 1:32 am, James Stroud wrote: >> Silfheed wrote: >> > Heyas >> >> > So this probably highlights my lack of understanding of how naming >> > works in python, but I'm currently using FailUnlessRaises in a unit >> > test and raising exceptions with a string exception. It's working >> > pretty well, except that I get the deprecation warning that raising a >> > string exception is going to go away. So my question is, how do I >> > mangle the name of my exception class enough that it doesnt stick the >> > name of the module before the name of the exception? >> >> > Namely I'd like to get the following >> >> > *** >> > Traceback (most recent call last): >> > File "", line 1, in ? >> > MyError: 'oops!' >> >> > instead of >> >> > *** >> > Traceback (most recent call last): >> > File "", line 1, in ? >> > __main__.MyError: 'oops!' >> >> > (or even test_thingie.MyError as is usually the case). >> >> > Creating a class in a separate file and then doing >> >> > *** >> > from module import MyError >> > raise MyError >> >> > still gives >> >> > *** >> > Traceback (most recent call last): >> > File "", line 1, in >> > module.MyError >> >> > Anyway, any help appreciated. >> >> Would it be cheating to use metaclasses? >> >> # myModule.py >> class ExampleType(type): >> def __repr__(cls): >> return cls.__name__ >> >> class ExampleError(Exception): >> __metaclass__ = ExampleType >> __name__ = 'ExampleError' >> def __repr__(self): >> return 'ExampleError' >> >> py> import myModule >> py> raise myMo >> myModule myModule.py myModule.pyc myModule.py~ >> py> raise myModule.Ex >> myModule.ExampleError myModule.ExampleType >> py> raise myModule.ExampleError >> ------------------------------------------------------------ >> Traceback (most recent call last): >> File "", line 1, in >> ExampleError >> >> James > > It doesnt appear to work for me. > Same exact code as you have but I still get: > >>>> raise myModule.ExampleError > Traceback (most recent call last): > File "", line 1, in > myModule.ExampleError James tested his code in the ipython console which obviously uses a different routine to produce the traceback. Try >>> class MyError(Exception): ... __module__ = None ... >>> raise MyError("oops") Traceback (most recent call last): File "", line 1, in MyError: oops Peter From aleax at mac.com Fri Aug 3 11:38:00 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 3 Aug 2007 08:38:00 -0700 Subject: Efficient Rank Ordering of Nested Lists References: <1186104049.022836.253470@e9g2000prf.googlegroups.com> Message-ID: <1i29gpw.1vh7eku1iauistN%aleax@mac.com> pablo.mitchell at gmail.com wrote: > A naive approach to rank ordering (handling ties as well) of nested > lists may be accomplished via: > > def rankLists(nestedList): > def rankList(singleList): > sortedList = list(singleList) > sortedList.sort() > return map(sortedList.index, singleList) > return map(rankList, nestedList) > > >>> unranked = [ [ 1, 2, 3, 4, 5 ], [ 3, 1, 5, 2, 4 ], [ -1.1, 2.2, > 0, -1.1, 13 ] ] > >>> print rankLists(unranked) > > [[0, 1, 2, 3, 4], [2, 0, 4, 1, 3], [0, 3, 2, 0, 4]] > > This works nicely when the dimensions of the nested list are small. > It is slow when they are big. Can someone suggest a clever way to > speed it up? Each use of sortedList.index is O(N) [where N is len(singleList)], and you have N such uses in the map in the inner function, so this approach is O(N squared). Neil's suggestion to use bisect replaces the O(N) .index with an O(log N) search, so the overall performance is O(N log N) [[and you can't do better than that, big-O wise, because the sort step is also O(N log N)]]. "beginner"'s advice to use a dictionary is also good and may turn out to be faster, just because dicts are SO fast in Python -- but you need to try and measure both alternatives. One way to use a dict (warning, untested code): def rankList(singleList): d = {} for i, item in reversed(enumerate(sorted(singleList))): d[item] = i return [d[item] for item in singleList] If you find the for-clause too rich in functionality, you can of course split it up a bit; but note that you do need the 'reversed' to deal with the corner case of duplicate items (without it, you'd end up with 1s instead of 0s for the third one of the sublists in your example). If speed is of the essence you might try to measure what happens if you replace the returned expression with map(d.__getitem__, singleList), but I suspect the list comprehension is faster as well as clearer. Another potential small speedup is to replace the first 3 statements with just one: d = dict((item,i) for i,item in reversed(enumerate(sorted(singleList)))) but THIS density of functionality is a bit above my personal threshold of comfort ("sparse is better than dense":-). Alex From vedrandekovic at v-programs.com Sun Aug 19 14:41:56 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Sun, 19 Aug 2007 11:41:56 -0700 Subject: Latest models of Gibson guitars In-Reply-To: <1187544898.289948.322160@22g2000hsm.googlegroups.com> References: <1187544898.289948.322160@22g2000hsm.googlegroups.com> Message-ID: <1187548916.909340.37420@k79g2000hse.googlegroups.com> On 19 kol, 19:34, mobile... at gmail.com wrote: > Reviews of latest models of best guitars, fender, gibson, yamaha, and > many more, with pictures and prices. > > http://pro-guitars.blogspot.com/ > > And if you want to win a free guitar go here > > http://freeguitars.blogspot.com/ Hello, This is a newsgroup of programming language Python, stop with this! Regards, Vedran From povkra at gmail.com Wed Aug 22 18:47:28 2007 From: povkra at gmail.com (fritz) Date: Wed, 22 Aug 2007 22:47:28 -0000 Subject: Car Air Conditioners! Message-ID: <1187822848.038813.158390@l22g2000prc.googlegroups.com> http://car-air-conditioning.blogspot.com/ From rcdailey at gmail.com Fri Aug 17 14:16:32 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 17 Aug 2007 13:16:32 -0500 Subject: Problem with directory recursion! Message-ID: <496954360708171116t4370c2ddra3d7905bc956c7eb@mail.gmail.com> Hi, I've created a function that is used to recurse a directory tree in Windows XP using os.walk(). For the most part it works, however in some instances the data is incorrect and I'm getting invalid sub-directory paths. Here's the function: def __doSearch( root_dir, sub_path, restype, ext ): print sub_path # Searches the specified directory and generates a # list of files to preload. complete_path = osp.normpath( osp.join( root_dir, sub_path ) ) for root, dirs, files in os.walk( complete_path ): # Record the list of file hash ID's for file in files: split = __resType( file ) if split[1] == restype: # print sub_path print "\t", file __appendResource( ext, sub_path, split[0] ) # Remove .svn subdirectories; we don't walk these. if ".svn" in dirs: dirs.remove( ".svn" ) # Recurse child directories for dir in dirs: __doSearch( root_dir, osp.join( sub_path, dir ), restype, ext ) Does anyone see anything immediately suspicious about the code? I'm assuming that in Python, every time a function is called recursively it gets its own copy of local variables. For some reason the sub_path variable isn't consistent depending on where I use it. For example, if you notice the print call at the very start of the function, it will output something like "models/ships". However, after passing it into __appendResource(), it appears to be just "models". -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Mon Aug 20 23:40:07 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 20 Aug 2007 20:40:07 -0700 Subject: Pattern for error checking easiest-first? In-Reply-To: <1187643719.772672.70780@w3g2000hsg.googlegroups.com> References: <1187643719.772672.70780@w3g2000hsg.googlegroups.com> Message-ID: <1187667607.283840.160690@k79g2000hse.googlegroups.com> On 20 ago, 18:01, jquinn+goo... at cs.oberlin.edu wrote: > The problem is that code like this does error checking backwards. A > call to NetworkedThing.changeMe will first do a slow error check and > then a fast one. Obviously there are various ways to get around this - > either have the subclass explicitly ask the superclass to error check > first, or vice totally versa. Is there some accepted pattern/idiom for > handling this issue? What about this: class AbstractThing(): def changeMe(self,blah): self.verify_blah(blah) self.blah = blah def verify_blah(self, blah): if blah < 1: raise MyException class NetworkedThing(AbstractThing): def verify_blah(self, blah): AbstractThing.verify_blah(blah) if blah > self.getUpperLimitOverTheNetworkSlowly: raise MyOtherException That is, it's the verify step that is overriden/enhanced, not the changeMe method that stays the same. -- Gabriel Genellina From steve at holdenweb.com Sun Aug 12 07:06:32 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 12 Aug 2007 07:06:32 -0400 Subject: Ligmail bug? In-Reply-To: <20070812182439.GA2427@ob41.org> References: <20070812005057.GA15805@ob41.org> <20070812182439.GA2427@ob41.org> Message-ID: <46BEE9B8.8080904@holdenweb.com> No.23 wrote: > yes, repeatable: > > Shell:~ >: date > Sun Aug 12 17:42:10 GMT 2007 > Shell:~ >: gmail.py > ..... > > Shell:~ >: date > Sun Aug 12 18:21:22 GMT 2007 > Shell:~ >: > > >> Is the error repeatable? How many times over what period of time have >> you experienced it? > >> No.23 wrote: >> [way too much, ending with] >>> File "/usr/local/lib/python2.5/urllib2.py", line 1076, in do_open >>> raise URLError(err) >>> urllib2.URLError: >>> >>> >>> other information: >>> Shell:~ >: uname -a >>> OpenBSD ob41.org 4.1 ob41#0 i386 >>> Shell:~ >: python >>> Python 2.5 (r25:51908, Mar 8 2007, 20:46:47) >>> [GCC 3.3.5 (propolice)] on openbsd4 >>> Type "help", "copyright", "credits" or "license" for more information. >>>>>> import libgmail >>>>>> print libgmail.Version >>> 0.1.6 >>> >>> >> So why does a temporary failure in name resolution seem like a library >> bug? This is just the library reporting back an error from the network >> or transport layer. >> >> Is the error repeatable? How many times over what period of time have >> you experienced it? >> [Please reply via the list when a response is made via the list. You may now have detached the follow-ups from your original question, but at least if you use the list there's a chance someone else will help you if I give up or don't have time. Note I have sent this response to the list; you are Cc'd to make sure you pick it up even though it may not appear in the same thread.] Well, now you need to do some investigation of the problem. The easiest way to do this is to make a local copy of the library that is reporting the error (in this case urllib2) - put it in the same directory as your program, so it will be picked up in preference to the library module, then insert prints at appropriate places to tell you what is actually going on as it fails. I think to start with you may want to look at the value of the "host" variable, since it appears that it may not be resolving, and see of you can resolve the same host yourself. It's possible someone is just using or referencing a bogus domain name, but you need solid information before deciding whether it's a bug or a feature. If you come across more puzzling behavior that you need the list's help with then please try to use short code samples, and avoid including thousands of lines of output that don't add anything to the description of the problem. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bbxx789_05ss at yahoo.com Wed Aug 22 19:03:02 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Wed, 22 Aug 2007 16:03:02 -0700 Subject: Learning Python using a book based on version 1.5 In-Reply-To: <1187814437.775758.159510@e9g2000prf.googlegroups.com> References: <1187814437.775758.159510@e9g2000prf.googlegroups.com> Message-ID: <1187823782.264415.294570@r23g2000prd.googlegroups.com> dogatemycomputer at gmail.com wrote: > Greetings, > > A friend of mine dropped off a copy of Sams Teach Yourself Python in > 24 Hours published in 2000. I skimmed the first couple of chapters > looking for the interpreter version and the book was based on version > Python version 1.5. > > Is this book still relevant? Should I toss it and look for something > newer? > > Any thoughts would be appreciated. > > Best Regards, > Dave The Sam's 24 hour books are wonderful tutorials(who wants to waste more than 24 hours learning a language), and the fact that it's based on python 1.5 shouldn't make any difference. From thomas at jollans.com Mon Aug 6 06:42:10 2007 From: thomas at jollans.com (Thomas Jollans) Date: Mon, 6 Aug 2007 12:42:10 +0200 Subject: webbrowser.open question force Firefox In-Reply-To: References: Message-ID: <200708061242.11147.thomas@jollans.com> On Monday 06 August 2007, dimitri pater wrote: > Hi, > I have a question regarding the use of webbrowser.open. > On a windows XP machine, MS-IE is set as the default browser so when I do: > webbrowser.open('http://localhost:8080') IE starts with this address. > But in stead of launching IE, I want to launch Firefox *without* setting > Firefox as the default browser globally on this machine. > > Any hints, ideas? Your help is most appreciated. take an educated guess where to find firefox, check if it's there, and do something like os.spawnl(os.P_NOWAIT, where_firefox_is, "http://localhost:8080") -- Regards, Thomas Jollans GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu Hacker key : v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part. URL: From vanrpeterson at gmail.com Thu Aug 30 09:12:49 2007 From: vanrpeterson at gmail.com (vanrpeterson at gmail.com) Date: Thu, 30 Aug 2007 06:12:49 -0700 Subject: Creating a multi-tier client/server application In-Reply-To: <7xy7ft4fqg.fsf@ruckus.brouhaha.com> References: <1188360460.838635.186930@w3g2000hsg.googlegroups.com> <7xbqcqhqbw.fsf@ruckus.brouhaha.com> <46d54ed8$0$429$426a34cc@news.free.fr> <1188393925.007952.313110@r29g2000hsg.googlegroups.com> <7xy7ft4fqg.fsf@ruckus.brouhaha.com> Message-ID: <1188479569.948608.306120@e9g2000prf.googlegroups.com> We totally agree with your software engineering goals. Relying on wxPython and minimizing web reliance brings sanity to the enterprise. We too love PostgreSQL and avoid XML whether cleaned by SOAP at all costs. We have found the object-relationship managers to be bloated and unruly. What are you building and how many hours per month are you willing to spend supporting it? From jstroud at mbi.ucla.edu Sun Aug 19 23:17:08 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 19 Aug 2007 20:17:08 -0700 Subject: How do I call anonymous classes from imported modules? In-Reply-To: References: Message-ID: JoeSox wrote: > I am importing 3rd party modules via a plugin script. I wish to > iterate thru the modules and call a common method like .do_foobar() or > something with all the imports. > But I can't figure out how to do something like below without knowing > the class name before hand. Is there a builtin that helps call > classes anonymously? > > > (Calling example.do_foobar() works because I manually enter the classes' name) > >>>>a=MyApp() >>>>sensorsList = [] >>>>for snames in a.pluginsDict["sensorsplugins"]: > > sensorsList.append(__import__(snames)) > >>>>sensorsList[0].example.do_foobar() > > > but I need something like > >>>>sensorsList[0][0].do_foobar() > > because I will not know the plugin class names. > Quick and dirty (you could also use a try: except:): f = __import__(module_name) for anobj in f.__dict__.values(): if hasattr(anobj, 'do_foobar'): anobj.do_foobar() Note that this does not test whether anobj is a class as this would entail a type-check, which hints to poor design. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From crodetsky at gmail.com Mon Aug 13 13:10:18 2007 From: crodetsky at gmail.com (srage) Date: Mon, 13 Aug 2007 17:10:18 -0000 Subject: Assignments and Variable Substitution In-Reply-To: References: Message-ID: <1187025018.744809.103030@l70g2000hse.googlegroups.com> On Aug 13, 1:00 pm, brad wrote: > I'd like to do something like this: > > var = '123' > %s = [], %var > > So that, in the end, var is '123' and an empty list is named '123' as > well. The list assignments are created during a loop. > > Thanks, > Brad You probably want to use a dictionary to store your lists... code like: variableDict = {} variableDict[var] = ['value1', 'value2', 'value3'] From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Aug 22 08:07:57 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 22 Aug 2007 14:07:57 +0200 Subject: Where we need to use Python ? In-Reply-To: References: <1187596936.136499.200280@l22g2000prc.googlegroups.com> Message-ID: <46cc26ed$0$432$426a74cc@news.free.fr> Terry Reedy a ?crit : > wrote in message > news:1187596936.136499.200280 at l22g2000prc.googlegroups.com... > | And Is it a interpreted language or a programming language > | It comes in which category > > Python is an algorithm programming language. > > The CPython implementation of the langauge compiles Python to proprietary > byte code Hahem... "proprietary" is certainly not the right term here. > and then interprets the byte code. (snip the rest) From marduk at nbk.hopto.org Sat Aug 4 12:08:30 2007 From: marduk at nbk.hopto.org (marduk) Date: Sat, 04 Aug 2007 11:08:30 -0500 Subject: the one python book In-Reply-To: <1186240249.433185.291390@r34g2000hsd.googlegroups.com> References: <1186240249.433185.291390@r34g2000hsd.googlegroups.com> Message-ID: <1186243710.28026.2.camel@blackwidow.nbk> On Sat, 2007-08-04 at 15:10 +0000, Michael Tobis wrote: > Like most people I eventually plan to read Moby Dick, War and Peace, > and Lutz's Programming Python. Maybe when I retire. LOL. Lutz's Programming Python is actually how I learned Python. From stefan.behnel-n05pAM at web.de Fri Aug 3 11:50:41 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 03 Aug 2007 17:50:41 +0200 Subject: Replacing _xmlplus.dom.minidom with xml.dom.minidom In-Reply-To: References: <1186148352.647143.68890@l70g2000hse.googlegroups.com> Message-ID: <46B34ED1.60402@web.de> Robert Rawlins - Think Blue wrote: > Just as a heads up, minidom is pretty inefficient and difficult to work with > too. > > On someone else's advice I switched over to ElementTree and have been really > pleased with the results, its much simpler to work with and more efficient > too. /and/ lxml.etree is compatible to ElementTree, so once you have written your code for ElementTree, you can switch to lxml.etree if ever you need things like XPath, XSLT or validation. However, as I understand the OP, the question deals with old code, so porting it to ET (i.e. reimplementing it) might not be that easy... Stefan From paul at boddie.org.uk Fri Aug 31 12:50:19 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 31 Aug 2007 09:50:19 -0700 Subject: So what exactly is a complex number? In-Reply-To: References: <1188576174.3479.9.camel@dot.uniqsys.com> Message-ID: <1188579019.141544.292210@50g2000hsm.googlegroups.com> On 31 Aug, 18:12, "Chris Mellon" wrote: > On 8/31/07, Carsten Haese wrote: > > > On Thu, 2007-08-30 at 20:11 -0500, Lamonte Harris wrote: > > > Like in math where you put letters that represent numbers for place > > > holders to try to find the answer type complex numbers? > > > Is English your native language? I'm having a hard time decoding your > > question. > > I'm pretty sure he was describing middle school algebra. Yes, I imagine that the "letters that represent numbers" is intended to refer to this: http://en.wikipedia.org/wiki/Elementary_algebra Whereas complex numbers are, of course, described here: http://en.wikipedia.org/wiki/Complex_number I hope the above resources are informative for the original inquirer. Paul From carsten at uniqsys.com Mon Aug 20 08:52:28 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 20 Aug 2007 08:52:28 -0400 Subject: Xah's Edu Corner: Under the spell of Leibniz's dream In-Reply-To: <1187598193.118227.270460@19g2000hsx.googlegroups.com> References: <1187567809.896668.228650@z24g2000prh.googlegroups.com> <1187598193.118227.270460@19g2000hsx.googlegroups.com> Message-ID: <1187614348.3398.8.camel@dot.uniqsys.com> On Mon, 2007-08-20 at 01:23 -0700, Ingo Menger wrote: > On 20 Aug., 01:56, Xah Lee wrote: > > > (for you math illiterates out there: ... > > (for you mathematicians out there: ... > > Please, Xah Lee, could you possibly stop to "explain" things that are > absolutely trivial? If somebody has doubts about the etymology of a > word, he may use the dictionary, or he could ask. And to underline your criticism, allow me to point out the irony: "No one can write decently who is distrustful of the reader's intelligence, or whose attitude is patronizing." (From "The elements of Style" by Strunk and White as quoted by Dijkstra in the very paper Xah Lee pointed out to us.) -- Carsten Haese http://informixdb.sourceforge.net From __peter__ at web.de Mon Aug 13 04:48:12 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 13 Aug 2007 10:48:12 +0200 Subject: verify whether "str" is still callable in Python 2.5.1 References: <1186994287.527549.119170@19g2000hsx.googlegroups.com> Message-ID: Ge Chunyuan wrote: > Once use ActivePython latest version for Python 2.5.1. > I happened to find function "str" is not callable, but it is available > for Python 2.5. If it's not callable it's not the str() function, but something else with a badly chosen variable name. >>> callable(str) True >>> str = "yadda" >>> callable(str) False Peter From Shawn at Milochik.com Mon Aug 20 13:29:48 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Mon, 20 Aug 2007 13:29:48 -0400 Subject: reading a line in file In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE2B2@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE2B2@efmailx> Message-ID: <2dc0c81b0708201029k5909d919vcf0deebae74a79c7@mail.gmail.com> Write some code, even if it doesn't quite work, and post it. We'll help you fix it. You can open a file with: input = open("file.txt", "r") You can read a line with: someText = input.readline() You can loop through an open file like this: for line in input: #do something with line That should get you started. From nospam at nospam.com Thu Aug 2 17:27:33 2007 From: nospam at nospam.com (Gilles Ganault) Date: Thu, 02 Aug 2007 23:27:33 +0200 Subject: Reading a two-column file into an array? References: <1185857837.610635.206270@e9g2000prf.googlegroups.com> <5h81mbF3j641tU1@mid.uni-berlin.de> <1i23xec.1r6z2ai14ntdgxN%aleax@mac.com> Message-ID: On Tue, 31 Jul 2007 08:41:45 -0700, aleax at mac.com (Alex Martelli) wrote: >That's what 2.5's with statement is all about...: Thanks everyone. Python power :-) from __future__ import with_statement import csv with open('import.csv', 'rb') as f: for item in list(csv.reader(f, delimiter='\t')): print item[0] + "," + item[1] From martin at v.loewis.de Wed Aug 8 16:39:45 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 08 Aug 2007 22:39:45 +0200 Subject: Misleading wikipedia article on Python 3? In-Reply-To: References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <7xzm15q8fy.fsf@ruckus.brouhaha.com> <41Dti.37401$G23.10727@newsreading01.news.tds.net> <1186582066.096793.14700@57g2000hsv.googlegroups.com> <1186600271.858692.182090@22g2000hsm.googlegroups.com> <7xmyx1bxkf.fsf@ruckus.brouhaha.com> Message-ID: <46BA2A11.6030307@v.loewis.de> > I don't see how file() can be "removed", actually, unless the > file type itself is getting axed. Indeed, that's the case. Py3k won't use stdio for file input and output, but the io module. Regards, Martin From hg at nospam.org Fri Aug 3 18:34:26 2007 From: hg at nospam.org (hg) Date: Fri, 03 Aug 2007 17:34:26 -0500 Subject: Eclipse/PyDev question. References: <1186153119.391091.275860@r34g2000hsd.googlegroups.com> Message-ID: king kikapu wrote: > Hi, > this is actually a question to those of us who use Eclipse and Pydev > as their main Python developing environment. As i use Eclipse (3.3 > Europa) only for Python and i have nothing to do with Java, is there a > way to disable/uninstall some Java-specific stuff and make the > environment actually more snappy ?? > > thanks for any help I like pydev and purchased the extensions ... there are bugs of course but what stopped me from using it is a project were I had some very large files (my fault). I stopped using it and went for wing dev (I need Windows and Linux access) and "there are bugs of course" ... but it is snappier. I still like pydev and will try it again ... once I can afford a faster PC / or have the time to re-factor my code. PS: I just got today news about a "free" version of wing dev .. .worth the try. hg From greg at cosc.canterbury.ac.nz Fri Aug 31 20:15:23 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 01 Sep 2007 12:15:23 +1200 Subject: ANN: PROBE 1.0 Message-ID: I have released an updated version of my PyWeek4 game competition entry, PROBE. In PROBE, you get to plan and execute space probe missions to other planets, using a fairly realistic (except for a couple of things) simulation of the physics involved. This version has been greatly expanded, and can actually be played in a deliberate way now instead of just trial and error like the first one. Currently available here: http://www.cosc.canterbury.ac.nz/greg.ewing/python/PyWeek4/Probe-1.0.zip -- Greg From raims at dot.com Mon Aug 13 18:33:01 2007 From: raims at dot.com (Lawrence Oluyede) Date: Tue, 14 Aug 2007 00:33:01 +0200 Subject: chmod g+ Equivalent References: <1187042290.821786.178420@19g2000hsx.googlegroups.com> Message-ID: <1i2t81z.1f4cmrhu1sy8iN%raims@dot.com> milan_sanremo wrote: > I've read the documentation on os.chmod() and can implement all the > standard commands, but what is the syntax for the equivalent of chmod g > + to set the group id? chmod() [1] takes as the second parameter a bitwise or-ed combination of a series of values. If you look at chmod's man page ("man 2 chmod" on the shell) you can see the following values for the group id (I have OSX so the actual value may be different on your OS): #define S_IRWXG 0000070 /* RWX mask for group */ #define S_IRGRP 0000040 /* R for group */ #define S_IWGRP 0000020 /* W for group */ #define S_IXGRP 0000010 /* X for group */ So you just have to OR them to accomplish your goal. 1 - -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From zzbbaadd at aol.com Thu Aug 30 14:21:13 2007 From: zzbbaadd at aol.com (zzbbaadd at aol.com) Date: Thu, 30 Aug 2007 11:21:13 -0700 Subject: list index() In-Reply-To: References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <46d674c2$0$417$426a34cc@news.free.fr> <1188496588.750629.208100@g4g2000hsf.googlegroups.com> Message-ID: <1188498073.997168.282420@q5g2000prf.googlegroups.com> > While I agree that Bruno's response was perhaps needlessly snippy, your > original question was needlessly inflammatory, as if you somehow wanted > some "religious zealot" to act the way Bruno did. If we start labeling > people, this thread will earn you a label that rhymes with "roll". > That is correct. I did word it in a way that would hook the Bruno's of the group. But I will probably have some more important questions so I will word it differently in the future. Such as: I wish they were not getting rid of dict.has_key() in Python 3, which I prefer to IN. From Michael.J.Fromberger at Clothing.Dartmouth.EDU Fri Aug 31 14:25:01 2007 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Fri, 31 Aug 2007 14:25:01 -0400 Subject: fcntl problems References: <1188512377.441241.107900@q4g2000prc.googlegroups.com> <1188515889.352267.220790@q5g2000prf.googlegroups.com> <1188568022.988154.188230@y42g2000hsy.googlegroups.com> <1188573280.155018.109360@o80g2000hse.googlegroups.com> Message-ID: In article <1188573280.155018.109360 at o80g2000hse.googlegroups.com>, "mhearne808[insert-at-sign-here]gmail[insert-dot-here]com" wrote: > Looking at my flock(3) man page, I'm guessing that "35" is the error > code for EWOULDBLOCK. Which system header file am I supposed to look > in to figure that magic number out? On a MacOS system, you can find them in /usr/include/sys/errno.h On a Linux system, try /usr/include/asm-generic/errno.h However, if you're writing in Python, you will probably have an easier time using the "errno" module, e.g., ] import errno ] errno.errorcode[35] 'EDEADLOCK' Note that some codes have multiple names (e.g., EAGAIN and EWOULDBLOCK) so that this lookup may not return exactly the name you're expecting. Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From martin at v.loewis.de Wed Aug 15 18:46:58 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 16 Aug 2007 00:46:58 +0200 Subject: threads, mutual exclusion, and lists In-Reply-To: <1187206583.255588.57920@e9g2000prf.googlegroups.com> References: <1187206583.255588.57920@e9g2000prf.googlegroups.com> Message-ID: <46c38262$0$14338$9b622d9e@news.freenet.de> > I have two threads that share a python list. One thread adds to the > list with append(), the other thread removes items with pop(). > > My question is -- are python list operations atomic? Yes, they are in the current implementation of CPython (all versions). Notice that not *all* operations are atomic (e.g. .sort() is not), but both append and pop happen to be atomic (which is primarily because they don't need to call back to user-defined functions, unlike sort). It's not a language property, though; things may be different in Jython or IronPython. Regards, Martin From ca.allen at gmail.com Mon Aug 6 18:18:11 2007 From: ca.allen at gmail.com (Chris Allen) Date: Mon, 06 Aug 2007 15:18:11 -0700 Subject: Global package variable, is it possible? In-Reply-To: <87vebt813u.fsf@benfinney.id.au> References: <1186160415.065108.139160@e9g2000prf.googlegroups.com> <46b6d0b4$0$29273$426a74cc@news.free.fr> <87vebt813u.fsf@benfinney.id.au> Message-ID: <1186438691.720218.234850@i13g2000prf.googlegroups.com> On Aug 6, 2:27 am, Ben Finney wrote: > Bruno Desthuilliers writes: > > I've read all the thread, and it seems that your problem is mostly > > to share a single dynamic state (the config) between several > > modules. So I do wonder: have you considered the use of the > > Singleton pattern (or one of it's variants...) ? > > Python modules are effectively singletons. So the idiomatic way to do > this is to create a module for configuration (perhaps named 'config'), > import that into every other module that needs it, and use its > attributes. > > -- > \ "[On the Internet,] power and control will shift to those who | > `\ are actually contributing something useful rather than just | > _o__) having lunch." -- Douglas Adams | > Ben Finney Yes, that's what I ended up doing. Which is creating a configure module and then importing it into my modules that use it. I did something very similar to the code I posted above. From b at bcc.com Tue Aug 14 12:22:04 2007 From: b at bcc.com (Bryan) Date: Tue, 14 Aug 2007 12:22:04 -0400 Subject: Simple python iteration question Message-ID: Hi, I just started with python, and have a for loop question In c++ (or a number of other languages) I can do this: for (int i=0, j=0; i < i_len, j< j_len; ++i, ++j) {} If I have this in python: l = ['a', 'b', 'c'] I want to get the value and also an iterator: for i,v in len(l), l: print v print i Or something like this without declaring the iterator outside my loop... How do I do this? Thanks! From http Mon Aug 20 17:29:48 2007 From: http (Paul Rubin) Date: 20 Aug 2007 14:29:48 -0700 Subject: I Need help from all the group participants References: <1187636668.436474.289220@o80g2000hse.googlegroups.com> <1187638964.815505.85390@57g2000hsv.googlegroups.com> Message-ID: <7xd4xh99o3.fsf@ruckus.brouhaha.com> Jason writes: > I want the result of John's auscultation. Give me > John's heart beats, or give John death! > > Okay, probably not the last one. "Hmm, either he's dead, or my watch has stopped." --Groucho Marx From hat at se-162.se.wtb.tue.nl Fri Aug 24 10:25:38 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 24 Aug 2007 16:25:38 +0200 Subject: Regular expression use References: Message-ID: On 2007-08-24, Nick Maclaren wrote: > people actually use regular expressions for. Not the subject > domain, but the construction of the regular expressions. This is easy. I use RE for checking whether some input matches a certain pattern, and optionally, to extract some special part from the text. Albert From sbellon at sbellon.de Thu Aug 9 02:25:17 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Thu, 9 Aug 2007 08:25:17 +0200 Subject: Destruction of generator objects References: <20070808002852.6228ae91@cube.tz.axivion.com> <1186618661.845525.225010@x35g2000prf.googlegroups.com> Message-ID: <20070809082517.6af28eaf@cube.tz.axivion.com> On Thu, 09 Aug, Graham Dumpleton wrote: > result = application(environ, start_response) > try: > for data in result: > if data: # don't send headers until body appears > write(data) > if not headers_sent: > write('') # send headers now if body was empty > finally: > if hasattr(result,'close'): > result.close() Hm, not what I hoped for ... Isn't it possible to add some __del__ method to the generator object via some decorator or somehow else in a way that works even with Python 2.4 and can then be nicely written without cluttering up the logic between consumer and producer? -- Stefan Bellon From nospam.themindstorm at gmail.com Fri Aug 3 08:28:52 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Fri, 3 Aug 2007 12:28:52 +0000 (UTC) Subject: File Handling & TRY/EXCEPT References: <33119.3366124809$1186129744@news.gmane.org> Message-ID: "Robert Rawlins - Think Blue" wrote in news:33119.3366124809$1186129744 at news.gmane.org: > This is a multipart message in MIME format. > > ------=_NextPart_000_00B0_01C7D5B0.02EB8BA0 > Hello Guys, > > > > I'm looking for some advice on how best to handle file read/write > errors with try/except as i'm a little vague on this, I have a small > memory leak in my app and I'm starting to think its generated by my > log file write. For an example of the function look below. > > > > def addAppLog(self, event): > > try: > > logfile = > open('/pblue/new/Logs/Application.csv','a') > > > > now = datetime.datetime.now() > > > > logstring = '%s,%s \n' % (event, str(now)) > > > > logfile.write(logstring) > > except: > > self.addAppLog(event) > > else: > > logfile.close() > Shouldn't you always close the file? So, a finally block with if logfile: logfile.close() ./alex -- .w( the_mindstorm )p. From jkrukoff at ltgc.com Wed Aug 8 13:34:47 2007 From: jkrukoff at ltgc.com (John Krukoff) Date: Wed, 8 Aug 2007 11:34:47 -0600 Subject: 'Advanced' list comprehension? query In-Reply-To: <1186588812.006107.185570@o61g2000hsh.googlegroups.com> Message-ID: <003b01c7d9e2$6ae3d1a0$0201a8c0@naomi> pyscottishguy at hotmail.com wrote: > Hi, > > I'm playing around with list comprehension, and I'm trying to find the > most aesthetic way to do the following: > > I have two lists: > > noShowList = ['one', 'two', 'three'] > > myList = ['item one', 'item four', 'three item'] > > I want to show all the items from 'myList' that do not contain any of > the strings in 'noShowList'. > > i.e. 'item four' > > I can do it like this: > > def inItem(noShowList, listitem): > return [x for x in noShowList if x in listitem] > > print [x for x in myList if not inItem(noShowList, x)] > > and I can do it (horribly) with: > > print [x for x in myList if not (lambda y, z:[i for i in y if i in z]) > (noShowList, x)] > > I can also print out the items that DO contain the 'noShowList' > strings with: > > print [x for x in myList for y in noShowList if y in x] > > but I can't get the 'not' bit to work in the above line. > > Any ideas? > Thanks! > > -- > http://mail.python.org/mailman/listinfo/python-list So, conceptually speaking, you're dealing with two loops here, one over the items to filter, and one over the items to check for substring matches. If you want to do that with list comprehensions, I'd make it obvious that there's two of them: >>> [ listItem for listItem in myList if not [ noShow for noShow in noShowList if noShow in listItem ] ] ['item four'] This is a pretty good place for the functional programming tools though, specifically "filter", http://docs.python.org/tut/node7.html#SECTION007130000000000000000 , which gives a solution that looks like this: >>> filter( lambda listItem : not [ noShow for noShow in noShowList if noShow in listItem ], myList ) ['item four'] or using purely functional tools, like this: >>> filter( lambda listItem : not sum( map( lambda noShow: noShow in listItem, noShowList ) ), myList ) ['item four'] All these solutions have the problem that they're still less efficient than the unwrapped for loop, like so: >>> aFiltered = [] >>> for listItem in myList: ... for noShow in noShowList: ... if noShow in listItem: ... break ... else: ... aFiltered.append( listItem ) ... >>> aFiltered ['item four'] This is due to the list comprehensions testing all the possiblities, instead of giving up on the first one found. You can jam that early break into the functional approach using itertools, but it starts to look really ugly on one line (requires 2.5 for if expression): >>> list( itertools.ifilter( lambda listItem : True if len( list( itertools.takewhile( lambda test : not test, itertools.imap( lambda noShow: noShow in listItem, noShowList ) ) ) ) == len( noShowList) else False, myList ) ) ['item four'] Which can be made to look much better by breaking the 'noShow in listItem' test out into a separate function, and does have the advantage that by using itertools.ifilter this is a lazy approach. There's got to be a better way to do the test to see if takewhile bailed early than using len, though. --------- John Krukoff helot at comcast.net From dubs0123 at gmail.com Thu Aug 16 09:54:57 2007 From: dubs0123 at gmail.com (Baisong Du) Date: Thu, 16 Aug 2007 09:54:57 -0400 Subject: How do you guys convert a tuple into a Set in ABAQUS? References: Message-ID: A function is defined to get a tuple. def searchObjectByRange(partObject, objectType, xRange, yRange, zRange): """In the partObject, search objects (edge, face, etc.) within the given region""" TOLERANCE_GLOBAL = 1.0E-6 INFINITE_RANGE = (-1.0E309, 1.0E309) tolerance = TOLERANCE_GLOBAL #Convert into list type xyzRange = [xRange, yRange, zRange] for i in range(len(xyzRange)): xyzRange[i] = list(xyzRange[i]) if len(xyzRange[i]) == 0: xyzRange[i] = INFINITE_RANGE else: if xyzRange[i][0] == None: xyzRange[i][0] = INFINITE_RANGE[0] if xyzRange[i][1] == None: xyzRange[i][1] = INFINITE_RANGE[1] if xyzRange[i][0] == xyzRange[i][1]: xyzRange[i][0] = xyzRange[i][0] - tolerance xyzRange[i][1] = xyzRange[i][1] + tolerance myObjects = [] #Find out the edges within the given region if objectType == 'EDGE': for edge in partObject.edges: ptsList = [] flag = 1 ptsList.append(edge.pointOn[0]) #Get the vertices on the edge for index in edge.getVertices(): ptsList.append(partObject.vertices[index].pointOn[0]) for ptCoords in ptsList: if (ptCoords[0] < xyzRange[0][0] or ptCoords[0] > xyzRange[0][1]): flag = 0 break if (ptCoords[1] < xyzRange[1][0] or ptCoords[1] > xyzRange[1][1]): flag = 0 break if (ptCoords[2] < xyzRange[2][0] or ptCoords[2] > xyzRange[2][1]): flag = 0 break if flag == 1: myObjects.append(edge) myObjects= tuple(myObjects) return myObjects sub_1=searchObjectByRange(myModel.parts['Part-1'], 'EDGE', (), (), (0, 0)) #Getting EDGES has the same z-coordinate, and I 166 edges are obtained. myModel.parts['Part-1'].Set(edges=sub_1,name='sub_set') #I wish to get the set 'sub_set', but doen't work. The error shows "TypeError: edges; too many arguments; expected 0, got 166". Is there somebody can help me with that? Thanks. Baisong From almadhu at gmail.com Tue Aug 7 00:29:16 2007 From: almadhu at gmail.com (Madhu Alagu) Date: Tue, 07 Aug 2007 04:29:16 -0000 Subject: Web based Reporting tool for Python Message-ID: <1186460956.945148.162610@k79g2000hse.googlegroups.com> Hi I am looking template based report tools for python.It has the ability to deliver rich content onto the screen, to the printer or into PDF, HTML, XLS, CSV and XML files. Thanks, Madhu Alagu From p.f.moore at gmail.com Wed Aug 15 11:13:47 2007 From: p.f.moore at gmail.com (Paul Moore) Date: Wed, 15 Aug 2007 08:13:47 -0700 Subject: Memory leak when creating lots of object In-Reply-To: <1187067442.084074.55010@z24g2000prh.googlegroups.com> References: <1187067442.084074.55010@z24g2000prh.googlegroups.com> Message-ID: <1187190827.395382.85740@57g2000hsv.googlegroups.com> On 14 Aug, 05:57, Godzilla wrote: > Hello, > > I have a program that create and pop an object off a queue, but it is > experiencing some memory leakage. I have been unable to detect where > the memory leakage occur. The strange thing is when i replace the > object creation with a plain integer/string, the leak goes away... > Here's the code I used as my test: [...] > I can see the memory usage increases slowly in Task Manager under XP, > but do not know why. Anyone help? I tried your code on my (Windows XP SP2, Python 2.5) system. No memory leak here - I left it running for over 5 minutes and memory usage was static at just under 4MB. Do you see memory growth with precisely this code? Over what period? How much? Paul. From horpner at yahoo.com Thu Aug 30 14:51:39 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 30 Aug 2007 18:51:39 GMT Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <46d674c2$0$417$426a34cc@news.free.fr> <1188496588.750629.208100@g4g2000hsf.googlegroups.com> <1188498073.997168.282420@q5g2000prf.googlegroups.com> <1188499525.827573.128170@x35g2000prf.googlegroups.com> Message-ID: On 2007-08-30, zzbbaadd at aol.com wrote: >> That wish will only come true if you maintain your own fork of >> Python 3. has_key() will go away, period. It has been made >> obsolete by "in", which is faster and more concise. > > Is there really some reason "key" IN dict can be implemented > faster than dict.has_key("key")??? Yes. Looking up the has_key method by name is the slower part. -- Neil Cerutti We're not afraid of challenges. It's like we always say: If you want to go out in the rain, be prepared to get burned. --Brazillian soccer player From gandalf at shopzeus.com Fri Aug 17 08:13:47 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 17 Aug 2007 14:13:47 +0200 Subject: advice about `correct' use of decorator In-Reply-To: <46C4C1B4.6050605@fmed.uba.ar> References: <46C4B097.4080309@fmed.uba.ar> <46C4B81A.8000304@shopzeus.com> <46C4C1B4.6050605@fmed.uba.ar> Message-ID: <46C590FB.9090403@shopzeus.com> >> >> Are you developing a website or a GUI program? >> >> > It will be used in a web development. It is an important point? Yes, I think. Unless you use AJAX. :-) Most web sites work this way: user clicks -> request to server -> process on server -> response I would rather enclose the whole handler in try/except and raise a custom PermissionDenied exception when the user has inscuficient permissions. There are problems with a decorator used for authorization. The context needs to be determined. E.g. which user is accessing the method? (It can be hard to tell if the method is part of a thread object that lies in a thread pool and is shared between simultaneous clients...) Also it might be that the method's purpose is to change objects of the same class, and the user has permission to modify one object but not the other. In this case, authorization must be done inside the function call... How do you express this with a decorator? These are just ideas. You should analyze your problem and make your decision. If you only want to restrict access to functions, then probably using decorators is perfect. Best, Laszlo From __peter__ at web.de Mon Aug 27 11:56:29 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 27 Aug 2007 17:56:29 +0200 Subject: How to free memory ( ie garbage collect) at run time with Python 2.5.1(windows) References: <1188224306.863247.127890@50g2000hsm.googlegroups.com> <1i3hujk.ulsjt32wqtq0N%aleax@mac.com> Message-ID: Alex Martelli wrote: > Integer objects that are once generated are kept around in a "free list" > against the probability that they might be needed again in the future (a Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> x = 1000 >>> y = 1000 >>> x is y False Why don't x and y point to the same object then? Peter From hniksic at xemacs.org Mon Aug 13 07:25:31 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 13 Aug 2007 13:25:31 +0200 Subject: Fatest standard way to sum bytes (and their squares)? References: <87r6m8egee.fsf@mulj.homelinux.net> Message-ID: <87lkcfbrro.fsf@mulj.homelinux.net> Erik Max Francis writes: > Hrvoje Niksic wrote: > >> For ordinalSum, using imap is almost twice as fast: >> $ python -m timeit -s 'data=[chr(x) for x in xrange(256)]' >> 'sum(ord(x) for x in data)' >> 10000 loops, best of 3: 92.4 usec per loop >> $ python -m timeit -s 'data=[chr(x) for x in xrange(256)]; from itertools import imap' 'sum(imap(ord, data))' >> 10000 loops, best of 3: 55.4 usec per loop > > You're using data which is a list of chars (strings), rather than a > string itself, which is what the format is in. The imap > optimization doesn't appear to work quite as dramatically well for > me with strings instead of lists, but it certainly is an > improvement. I wouldn't expect to see any difference in strings and lists. In this simple test I get approximately the same ~1.7x speedup: $ python -m timeit 'sum(ord(x) for x in "abcdefghijklmnopqrstuvwxyz")' 100000 loops, best of 3: 12.7 usec per loop $ python -m timeit -s 'from itertools import imap' 'sum(imap(ord, "abcdefghijklmnopqrstuvwxyz"))' 100000 loops, best of 3: 7.42 usec per loop From Brian.McCann at viziant.net Mon Aug 20 13:10:23 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Mon, 20 Aug 2007 13:10:23 -0400 Subject: reading a line in file Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE2B2@efmailx> Hi, does anyone have a good example of how to read a line in a file? say you have a file build.log and in the file are values like buildnum = 1 date = 20070820 I know how to read the contents and write them to a file, but how would one grab just the date or build number in order to create a directory named 20070820_build1 Thanks, Brian -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Wed Aug 1 00:16:43 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 31 Jul 2007 21:16:43 -0700 Subject: split a string of space separated substrings - elegant solution? In-Reply-To: <46af9beb$0$14242$ba620e4c@news.skynet.be> References: <46af9beb$0$14242$ba620e4c@news.skynet.be> Message-ID: <1185941803.577841.178550@l70g2000hse.googlegroups.com> On Jul 31, 3:30 pm, Helmut Jarausch wrote: > I'm looking for an elegant solution to the following (quite common) > problem: > > Given a string of substrings separated by white space, > split this into tuple/list of elements. > The problem are quoted substrings like > > abc "xy z" "1 2 3" "a \" x" > > should be split into ('abc','xy z','1 2 3','a " x') > Pyparsing has built-in support for special treatment of quoted strings. Observe: from pyparsing import * data = r'abc "xy z" "1 2 3" "a \" x"' quotedString.setParseAction(removeQuotes) print OneOrMore(quotedString | Word(printables) ).parseString(data) prints: ['abc', 'xy z', '1 2 3', 'a \\" x'] Or perhaps a bit trickier, do the same while skipping items inside /* */ comments: data = r'abc /* 456 "xy z" */ "1 2 3" "a \" x"' quotedString.setParseAction(removeQuotes) print OneOrMore(quotedString | Word(printables) ) \ .ignore(cStyleComment).parseString(data) prints: ['abc', '1 2 3', 'a \\" x'] -- Paul From stefan.behnel-n05pAM at web.de Thu Aug 30 03:17:59 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 30 Aug 2007 09:17:59 +0200 Subject: replacing xml elements with other elements using lxml In-Reply-To: <1188438371.064824.13020@l22g2000prc.googlegroups.com> References: <1188399381.188639.289480@57g2000hsv.googlegroups.com> <46D5A272.2000509@web.de> <1188428655.300330.213430@r29g2000hsg.googlegroups.com> <1188438371.064824.13020@l22g2000prc.googlegroups.com> Message-ID: <46D66F27.5040308@web.de> Ultrus wrote: > Ah! I figured it out. I forgot that the tree is treated like a list. > The solution was to replace the element with the first > child, then use Python's insert(i,x) function to insert elements after > the first one. You could also use slicing, something like: parent[2:3] = child[1:5] should work. > lxml rocks! I know, but it feels good to read it once in a while. :) Stefan From gherzig at fmed.uba.ar Thu Aug 23 15:49:19 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Thu, 23 Aug 2007 16:49:19 -0300 Subject: advice about `correct' use of decorator In-Reply-To: <740c3aec0708230520h6a92a29ar180efed41730f563@mail.gmail.com> References: <46C4B097.4080309@fmed.uba.ar> <740c3aec0708170529s6f7e7fe2l8c92771c2d0a51d4@mail.gmail.com> <46C5C9AE.5020508@fmed.uba.ar> <1187792001.935204.42330@e9g2000prf.googlegroups.com> <740c3aec0708230520h6a92a29ar180efed41730f563@mail.gmail.com> Message-ID: <46CDE4BF.6030409@fmed.uba.ar> BJ?rn Lindqvist wrote: >On 8/22/07, Gabriel Genellina wrote: > > >>On 22 ago, 10:00, "BJ?rn Lindqvist" wrote: >> >> >>>As I said, you can accomplish the exact same thing by calling a >>>function from within the function that requires the user to be logged >>>in. >>> >>>def change_pass(): >>> check_user_logged_in() >>> ... more stuff here... >>> >>>is less complex (and therefore preferable) than: >>> >>>@check_user_logged_in >>>def change_pass(): >>> ... more stuff here... >>> >>>An important principle in engineering is that you should always strive >>>to make your design as simple as possible. If you have two equal >>>designs, you should always choose the one that is simpler because >>>simple things are easier to understand than complex things. >>> >>> >>I don't see the complexity in this case - both are a single line of >>code. Any internal complexity is hidden by the language. In fact, I >> >> > >"Hiding" doesn't reduce complexity, quite the opposite. > > > >>consider the decorated function simpler than the other: its body >>represents exactly what the function does, without any distracting >>precondition calls. >> >> > >Think about how the decorator is implemented. It is a high order >function, taking a function and returning a new function. Something >like this: > >def check_user_logged_in(func): > def f(*args, **kwargs): > if global_state.the_user.is_logged_in: > return func(*args, **kwargs) > return show_login_page() > return f > >@check_user_logged_in >def change_pass(): > ... more stuff here... > >or: > >def check_user_logged_in(): > return global_state.the_user.is_logged_in > >def change_pass(): > if not check_user_logged_in(): > return show_login_page() > ... more stuff here ... > >or even: > >def change_pass(): > if not global_state.the_user.is_logged_in: > return show_login_page() > ... more stuff here ... > > > >>The decorator has some advantages: can have syntax support on your >>editor, can perform some registering/logging, it's even easier to >>quickly check visually if it's here. >> >> > >The decorator has just as many disadvantages. For example, what if you >want to redirect back to the change_pass page once the user has >pressed the Login button on the login_page? Or if you want to show >different login pages depending on user properties? How much control >flow do you really want to "hide" in your decorator? > > > Thanks Bj?rn. Maybe im blind here in my intent to use decorators somewhere, but even re-checking you samples (pretty much the kind of example i show to my boss), it looks nicer (to me) when using a decorator!! I guess im becoming a `deco junky' :) Later you expose some interesing points about that login page and redirecting stuff...well, im my case, the login page does depends on user properties, wich (at this point) are stored in a `session data variable' (actually a table row), so the login pages take care about user properties, not the decorator itself, but the other part of the page. I guess decorators has is own public, well, im one of that public. Let my be with my deco-junk alone, you bastard :) Thanks a lot for your opinnions, guys! Gerardo From nmin at freenet.de Wed Aug 8 08:10:29 2007 From: nmin at freenet.de (nmin at freenet.de) Date: Wed, 08 Aug 2007 05:10:29 -0700 Subject: Jython - problem import os Message-ID: <1186575029.494729.327550@b79g2000hse.googlegroups.com> Hi. I'm using Jython in combination with Java, webservices and jboss4.0.4. The webservice is implemented in java and creates an PythonInterpreter object which loads the jython scripts. I wrote an jython script which uses a function from another jython file called library.py. So, i wrote: service.java ======== public void webMethod(){ PythonInterpreter p = new PythonInterpreter() p.execfile(skript.py) } skript.py ====== from library import * test=testFunction() library.py ======= import os def testFunction(): os.getcwd() ...all these files are inside my ear-archive and the service.java represent my webservice class. So, calling WebMethod returns: ImportError: no module named javaos in library.py. Any ideas? From steve at REMOVE.THIS.cybersource.com.au Thu Aug 2 08:40:50 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 02 Aug 2007 22:40:50 +1000 Subject: Python end of file marker similar to perl's __END__ References: <1185940391.135261.130950@i38g2000prf.googlegroups.com> <1185976656.753817.27980@x40g2000prg.googlegroups.com> <874pjidcvv.fsf@benfinney.id.au> Message-ID: On Thu, 02 Aug 2007 10:00:04 +1000, Ben Finney wrote: > beginner writes: > >> Thanks everyone for responding. It doesn't look like python has >> it. I would definitely miss it. As Steve said, the nice thing about >> __END__ is that things below __END__ do not have to have legit >> syntax. > > I think the unaddressed question is: Why is there so much code in your > module with invalid syntax that this trick would be useful? It's not just "bad syntax" that makes the triple-quote or comment trick useful. Sometimes you're experimenting, or perhaps tinkering is a better description. Your aim isn't to end up with a working piece of code, but to learn something (e.g. "how do decorators work?"). You may end up with working code at the end, but the finished code isn't the aim of the exercise and may not be kept. Because you're experimenting, you might end up with ten different versions of a function, and not all of them will compile, let alone execute correctly. It's handy to be able to comment them out and reload() the file, and while some editors will do bulk comment/uncomment of text, the triple-quoted string trick is easy enough that you can use it in Microsoft's Notepad. >> That let me focus on the lines of code I am debugging and do not >> have to worry about some bad syntax down the line. This feature is >> especially handy if I am, saying, replacing modoules or changing >> data structures. > > I would strongly recommend you examine what part of your practice is > leading you to write so much code with invalid syntax, without > immediately testing and fixing it. Eliminate that part of the process > -- possibly with test-driven development. While the discipline of TDD is good and useful, there's a time and place for unstructured and informal experimentation too. -- Steven. From jmcmonagle at velseis.com.au Fri Aug 24 00:20:49 2007 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Fri, 24 Aug 2007 14:20:49 +1000 Subject: creating a tar file with python In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> Message-ID: <46CE5CA1.9070505@velseis.com.au> Brian McCann wrote: > Hi, > > I'm trying to create a tar file of the contents of the current directory > > right now there is only one file "text.xml" in the current dir, I'm > using"." current dir as source > but that gives syntax error > > any help would be greatly appreciated > --Brian > > > #!/usr/bin/python > import string > import os > import sys > import time > import errno > import shutil > import tarfile > > > tar = tarfile.open(.,"test.tar.gz", "w:gz) Contents of current directory in a new gzipped tarfile (includes "hidden" *nix files): import tarfile, glob t = tarfile.open('tarfilename.tar.gz', 'w:gz') for filename in glob.glob('*')+glob.glob('.*'): t.add(filename) t.close() Note: this includes any subdirectories and their files below the current level. Regards, John From ca.allen at gmail.com Mon Aug 6 18:16:15 2007 From: ca.allen at gmail.com (Chris Allen) Date: Mon, 06 Aug 2007 15:16:15 -0700 Subject: Global package variable, is it possible? In-Reply-To: <46b6d0b4$0$29273$426a74cc@news.free.fr> References: <1186160415.065108.139160@e9g2000prf.googlegroups.com> <46b6d0b4$0$29273$426a74cc@news.free.fr> Message-ID: <1186438575.861738.173900@g12g2000prg.googlegroups.com> On Aug 6, 12:41 am, Bruno Desthuilliers wrote: > Chris Allen a ?crit : > > > > > Hello fellow pythoneers. I'm stumped on something, and I was hoping > > maybe someone in here would have an elegant solution to my problem. > > This is the first time I've played around with packages, so I'm > > probably misunderstanding something here... > > > Here's what I'd like to do in my package. I want my package to use a > > configuration file, and what I'd like is for the config file to appear > > magically in each module so I can just grab values from it without > > having to load and parse the config file in each package module. Not > > quite understanding how the __init__.py file works, I expected it to > > be as easy as just setting up the ConfigParser object and then I > > figured (since a package is a module) that it would now be global to > > my package and I could access it in my modules, but I was wrong... I > > don't want to have to pass it in to each module upon init, or anything > > lame like that. A main reason for this is that I'd like to be able to > > reload the config file dynamically and have all my modules > > automatically receive the new config. There must be a way to do this, > > but seeing how __init__.py's namespace is not available within the > > package modules, I don't see a simple and elegant way to do this. > > Does anybody have any suggestions? Thanks! > > Hi Chris... > I've read all the thread, and it seems that your problem is mostly to > share a single dynamic state (the config) between several modules. So I > do wonder: have you considered the use of the Singleton pattern (or one > of it's variants...) ? Thanks, I don't know anything about python singletons. But I'll look it up. From Brian.McCann at viziant.net Thu Aug 23 20:20:17 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Thu, 23 Aug 2007 20:20:17 -0400 Subject: creating a tar file with python References: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE2EC@efmailx> Hi, I tried Steve's solution but get this error using the tar script below --Brian tar = tarfile.open(".","test.tar.gz",w:gz) [viz at vizbld02 tmp]$ ./tarup.py File "./tarup.py", line 24 tar = tarfile.open(".","test.tar.gz",w:gz) ^ SyntaxError: invalid syntax ###################################################### #!/usr/bin/python import string import os import sys import time import errno import shutil import tarfile tar = tarfile.open(".","test.tar.gz",w:gz) ________________________________ From: python-list-bounces+brian.mccann=viziant.net at python.org on behalf of Steve Holden Sent: Thu 8/23/2007 5:24 PM To: python-list at python.org Subject: Re: creating a tar file with python Brian McCann wrote: > Hi, > > I'm trying to create a tar file of the contents of the current directory > > right now there is only one file "text.xml" in the current dir, I'm > using"." current dir as source > but that gives syntax error > > any help would be greatly appreciated > --Brian > > > #!/usr/bin/python > import string > import os > import sys > import time > import errno > import shutil > import tarfile > > > tar = tarfile.open(.,"test.tar.gz", "w:gz) > > > well, /probably/ (meaning I haven't done any testing) you need quotes around the name of the current directory just like you do around the name of the file. Try tar = tarfile(".", "test.tar.gz", "w:gz") regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Fri Aug 3 13:07:47 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 03 Aug 2007 17:07:47 GMT Subject: (no) fast boolean evaluation ? References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> <46b2e56b$0$18879$426a74cc@news.free.fr> <46b35069$0$17822$426a74cc@news.free.fr> Message-ID: On 2007-08-03, Ed Leafe wrote: > On Aug 3, 2007, at 11:57 AM, Bruno Desthuilliers wrote: > >> Sorry, I forgot to mention the language did not allow to have else >> & if >> in the same statement. IOW : >> >> if some_condition then >> do_sometehing >> else >> if some_other_condition then >> do_something_else >> else >> if yet_another_condition then >> do_yet_another_thing >> else >> if your_still_here then >> give_up('this language is definitively brain dead') >> end if >> end if >> end if >> end if > > Usually that's because the language provides a switch/case > statement construct. If it does and you try to write the above > code, it isn't the language that's brain-dead! ;-) The switch statements I'm aware of are less generally applicable than a tower of "if { else if }* else". For example, with a switch statement you have to dispatch on the one value for every case. In some languages, it's even of more limited, e.g., C, which can switch on only integers. -- Neil Cerutti Next Sunday Mrs. Vinson will be soloist for the morning service. The pastor will then speak on "It's a Terrible Experience." --Church Bulletin Blooper From sisson.j at gmail.com Tue Aug 28 12:23:39 2007 From: sisson.j at gmail.com (J Sisson) Date: Tue, 28 Aug 2007 11:23:39 -0500 Subject: Asking all python programmers. In-Reply-To: References: <2dc0c81b0708280822t70bf0528s4f80fe926cbb91bf@mail.gmail.com> Message-ID: <4297a9020708280923j372cd840rc7e3f1dfbf0ea93d@mail.gmail.com> On 8/28/07, Lamonte Harris wrote: > > From a python starter, I don't like the word noob because it sounds very > unprofessional. > Touche`...haha I second the motion for "Dive Into Python." It's an excellent book, and you really can't beat the price (free online as Shawn has pointed out). I've also discovered that learning python is easier when you have a defined goal ("learn xyz language" has never cut it for me...I have to have a much more specific goal in mind to accomplish anything). For instance, during my senior project in college, my team lead was worried we wouldn't get enough data gathered in time to present our work. I took that opportunity to write a few Python scripts that would hunt the internet for the data we were looking for and insert it into our database (after scrubbing/etc...). Having that specific task (rather, having the specific problem to solve) accelerated my learning because I was focused on a *real* issue, not a vague "learn xyz". Tutorials and challenges, while useful, can't take the place of learning a language to solve a problem *you* want to solve. Look for a task that would make your life easier, then see how you can apply Python to it... -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at divmod.com Mon Aug 6 13:05:07 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 6 Aug 2007 13:05:07 -0400 Subject: udp, datagram sockets In-Reply-To: <1186416225.769753.307110@o61g2000hsh.googlegroups.com> Message-ID: <20070806170507.4947.1905302655.divmod.quotient.19571@ohm> On Mon, 06 Aug 2007 09:03:45 -0700, 7stud wrote: >I'm trying to understand datagrams. My client program sends a message >to the server, and then the server infinitely loops over the recv() to >make sure all the data was received. I'm trying to use an * to signal >the end of the message, so that the server can break out of the >infinite while loop used to check the recv(). However, my server >repeatedly outputs the client message over and over again. Can anyone >tell me why? The network is probably dropping some of your data, causing the server to never see the termination marker. UDP is difficult to use effectively. Fortunately, TCP is suitable for many applications. You should consider using it, instead. Jean-Paul From seberino at spawar.navy.mil Mon Aug 27 04:12:40 2007 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: Mon, 27 Aug 2007 01:12:40 -0700 Subject: Best open source Python online *CHAT* apps? Message-ID: <1188202360.562850.24860@e9g2000prf.googlegroups.com> Best open source Python online chat apps? I believe there are a few PHP online chat apps to allow people to have conversation via a web server but a Python one would soothe the soul. Any available? Thanks, Chris From mail at timgolden.me.uk Wed Aug 22 05:18:30 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 22 Aug 2007 10:18:30 +0100 Subject: Dispatching default application for file, cross platform. In-Reply-To: <01e101c7e48d$e0e9f860$03000080@hendrik> References: <01e101c7e48d$e0e9f860$03000080@hendrik> Message-ID: <46CBFF66.7030207@timgolden.me.uk> Hendrik van Rooyen wrote: > How do I do the equivalent of clicking (in SuSe) or double clicking (in Windows) > on a file? > > In effect I want to tell the OS - take this file and feed it to the application > that is registered for it. > > Not too sure what to Google for. > > - Hendrik os.startfile TJG From deets at nospam.web.de Sun Aug 19 15:53:17 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 19 Aug 2007 21:53:17 +0200 Subject: Python on Computation, Math and Statistics In-Reply-To: References: <5irgvaF3oi5dpU2@mid.uni-berlin.de> Message-ID: <5irldoF3qonnbU1@mid.uni-berlin.de> W. Watson schrieb: > Google? What's that? Thanks. I like to get a insider's view when I know > experts are out there. So now I ask a deeper question. Are there matrix > computation libraries or even statistical (regression, factor analysis) > libraries? That's your idea of an "in depth question"? Did you even consider googling the projects I told you about? Reading up on them just the tiniest? http://www.scipy.org/ """ SciPy (pronounced "Sigh Pie") is open-source software for mathematics, science, and engineering. It is also the name of a very popular conference on scientific programming with Python. The SciPy library depends on NumPy, which provides convenient and fast N-dimensional array manipulation. The SciPy library is built to work with NumPy arrays, and provides many user-friendly and efficient numerical routines such as routines for numerical integration and optimization. Together, they run on all popular operating systems, are quick to install, and are free of charge. NumPy and SciPy are easy to use, but powerful enough to be depended upon by some of the world's leading scientists and engineers. If you need to manipulate numbers on a computer and display or publish the results, give SciPy a try! """ Or do you wish a comprehensive overview as Powerpoint presentation in your favorite colors? Diez From corrodi.claudio at gmail.com Wed Aug 15 05:21:26 2007 From: corrodi.claudio at gmail.com (Claudio Corrodi) Date: Wed, 15 Aug 2007 11:21:26 +0200 Subject: What does r"""any text""" mean ? In-Reply-To: References: Message-ID: <20070815112126.53eef833@earth> Hi Alexander, Alexander Eisenhuth wrote: > ... as you can find in os.py at line 1 ? This is a raw string. Raw strings don't interpret the escape sequences. Try this: >>> print 'a\nb\tc' a b c >>> print r'a\nb\tc' a\nb\tc You needn't use the raw string for printing the backslashes. You can escape them like this: >>> print 'a\\nb\\tc' a\nb\tc > Regards Alexander Regards, Claudio From mblume at socha.net Mon Aug 13 11:46:21 2007 From: mblume at socha.net (Martin Blume) Date: Mon, 13 Aug 2007 17:46:21 +0200 Subject: strftime in python 2.2 References: <1187012631.102571.94210@w3g2000hsg.googlegroups.com> Message-ID: <46c07ccd$0$3807$5402220f@news.sunrise.ch> "Flyzone"schrieb > I'm trying to make work this code in python 2.2.3: > > check=datetime.datetime.today().strftime("%H%M") > > but datetime is not supported in that version but > just in the later. I can't upgrade python, too many > dependencies in a critical system. > How can i convert that string to have the same result? > import time time.strftime("%H%M) HTH Martin From timr at probo.com Fri Aug 3 02:39:00 2007 From: timr at probo.com (Tim Roberts) Date: Fri, 03 Aug 2007 06:39:00 GMT Subject: MIMEText breaking the rules? References: Message-ID: Dale Strickland-Clark wrote: > >The email module's mimetext handling isn't what you might expect from >something that appears to behave like a dictionary. >... >Having apparently REPLACED my recipient, what I've ended up with is both of >them. This behavior is documented in Message.Message, from which MIMEText eventually inherits. If you want to start over, delete the item: del Msg["To"] I would have to say that the existing behavior is more intuitive for an email object. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jstroud at mbi.ucla.edu Thu Aug 9 21:31:10 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 09 Aug 2007 18:31:10 -0700 Subject: beginner whitespace question In-Reply-To: References: <1186703261.136506.208660@x35g2000prf.googlegroups.com> <1186703525.591462.122140@m37g2000prh.googlegroups.com> <1186704161.334597.218750@z24g2000prh.googlegroups.com> <1186707164.095766.243480@q3g2000prf.googlegroups.com> <1186708404.901323.204730@g12g2000prg.googlegroups.com> Message-ID: James Stroud wrote: > def __unicode__(self): > return self.choice Laughing to hard at the tab & spaces thing to notice the lack of indentation here. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From luca.bertini at email.it Thu Aug 23 09:24:04 2007 From: luca.bertini at email.it (luca bertini) Date: Thu, 23 Aug 2007 15:24:04 +0200 Subject: Simple Python Spider Message-ID: Hi everybody, i'm new to the forum so: hello everybody (should I say "world"?) ^_^ I'm trying to do a simple spider in python which: 1) ask google a query 2) parse the data I'm a python newbie so *any* help would be very, very welcommed. Thanks in advice! cheers! From python at rcn.com Fri Aug 10 12:21:48 2007 From: python at rcn.com (Raymond Hettinger) Date: Fri, 10 Aug 2007 09:21:48 -0700 Subject: is there anybody using __del__ correctly?? In-Reply-To: <1186731369.073644.158490@z24g2000prh.googlegroups.com> References: <1186731369.073644.158490@z24g2000prh.googlegroups.com> Message-ID: <1186762908.121319.35900@x35g2000prf.googlegroups.com> [Michele Simionato] > Here and there I hear rumors about deprecating __del__ and > nothing > happens, are there any news about that? Expecially concerning Py3k? I was writing a Py3K PEP advocating the elimination of __del__ because: * 'with closing()' and try/finally are the preferred ways of calling close() * it is easy to accidently keep or introduce a reference that blocks the __del__ logic * under-the-hood, the implementation of __del__ clashes badly with GC logic and is a maintenance nightmare * the body of a __del__ method may unintentionally resurrect an object that was in the process of being deleted For the PEP to have a chance, I neede to make build-outs to the weakref module so that existing use cases for __del__ can be easily migrated. That hasn't been done yet, so the campaign to eliminate __del__ is stalled. > I should mention that if you search comp.lang.python > for __del__ you will find hundreds of people who were > bitten by __del__, so I usually give advices such as > "you should never __del__ in your code" Good advice. Explicit finalization is almost always preferable. Raymond Hettinger From carsten at uniqsys.com Thu Aug 16 08:57:25 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 16 Aug 2007 08:57:25 -0400 Subject: Hijack! Different book: (was: Opinions about this new Python book? In-Reply-To: <1187263267.314987.253590@a39g2000hsc.googlegroups.com> References: <1187096231.194685.86030@m37g2000prh.googlegroups.com> <20070814154913.D8C3C1E400A@bag.python.org> <8a6b8e350708141020q495b22der4c362ee3df618d82@mail.gmail.com> <1187117012.088495.247890@q4g2000prc.googlegroups.com> <1187191950.037749.8050@z24g2000prh.googlegroups.com> <13c6fb3pntv6n13@corp.supernews.com> <1187263267.314987.253590@a39g2000hsc.googlegroups.com> Message-ID: <1187269045.3385.11.camel@dot.uniqsys.com> On Thu, 2007-08-16 at 04:21 -0700, Paul Boddie wrote: > [...] I pity the people writing Python books given > continuous changes to the language and the associated recommended > development practices as new features go in, but tracking a target > prior to any kind of stable release seems a bit too ambitious, > especially for a book in print. The book was co-authored by Kevin Dangoor, who is the principal developer of TurboGears. He probably had a pretty good idea of what the stable release was going to look like. -- Carsten Haese http://informixdb.sourceforge.net From jfabiani at yolo.com Sun Aug 12 10:59:43 2007 From: jfabiani at yolo.com (johnf) Date: Sun, 12 Aug 2007 07:59:43 -0700 Subject: Database intensive application References: <1186895306.237395.189530@z24g2000prh.googlegroups.com> Message-ID: Rohit wrote: > I am a novice. I want to know whether Python can be used to develop > client/server database and web applications like .NET. Which is the > best book/source to learn Python? IMO you should use Dabo (www.dabodev.com). If you want to strike on your own check using SQLAlchemy as your database connection. Check out the O'Reilly books. John From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Aug 3 09:08:59 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 03 Aug 2007 15:08:59 +0200 Subject: (no) fast boolean evaluation ? missing NOT In-Reply-To: References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> <1186096979.397596.36640@e16g2000pri.googlegroups.com> Message-ID: <46b328ea$0$21525$426a74cc@news.free.fr> Stef Mientki a ?crit : (snip) > Gabriel: you pointed me to this page: > The exact behavior is defined in the Language Reference > > > > or_test ::= and_test | or_test "or" and_test > > Can you imagine, while I'm not a programmer, just a human, > that I don't understand one bit of this line. This is a variant[2] of the BNF notation[1] for languages grammar. You'll find such notation in almost any programming language. [1] http://en.wikipedia.org/wiki/Backus-Naur_form [2] http://docs.python.org/ref/notation.html > So now I'm left with just one question: > for bitwise operations I should use &, |, ^ yes. > for boolean operations I should use and, or, xor yes. > but after doing some test I find strange effects: > >>> A = 4 > >>> B = 5 > >>> A and B > 5 > >>> A & B > 4 > >>> A or B > 4 > >>> A | B > 5 Nothing strange here. You now know how boolean operators works. Bitwise operators are something different (while still related). Represent yourself ints as bit fields, ie (restricting ourselves to 4-bits words for the example): 0 => 0000 1 => 0001 2 => 0010 3 => 0011 4 => 0100 5 => 0101 6 => 0110 7 => 0111 8 => 1000 (etc) The bitwise operators works this way: 1/ the & operator compares each bit of it's operands, and for each returns '1' if both bits are '1', else '0'. So you have: A & B => 4 & 5 => 0100 & 0101 => 0100 => 4 0100 & 0101 ---- 0100 2/ the | operator compares each bit of it's operands, and for each returns '1' if one of the bits is '1', else '0'. So you have: A | B => 4 | 5 => 0100 | 0101 => 0101 => 5 0100 | 0101 ---- 0101 HTH From grahn+nntp at snipabacken.dyndns.org Sun Aug 12 13:44:48 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 12 Aug 2007 17:44:48 GMT Subject: Launch file from Python References: <1186594137.971393.128780@57g2000hsv.googlegroups.com> Message-ID: On Wed, 08 Aug 2007 10:28:57 -0700, jocago at gmail.com wrote: > Good afternoon from someone who is trying to learn Python. > > I would like to launch an app from within a Python script. From the > examples I have found, I should be able to do this with os.system. > > I use this: > os.system("xplanet-1.2.0/xplanet.exe -fontsize 24 -label -target earth > -lat 33.65 -lon -84.42 -radius 40 -num_times 1 -tmpdir .") > This is copied directly from the .bat file that launches the xplanet > app. It works there. > > and get this: > 1 That means "error", as others noted. It is odd that you get no printouts. Had this been on Unix, you'd either get "file not found" or similar from the shell trying to run the thing, or something from xplanet itself (only really badly programs return failure without printing some kind of cause). Two more comments, assuming you are on Windows (you mention ".bat files"): - You use the relative path xplanet-1.2.0/xplanet.exe. That should require your program to have the parent of xplanet-1.2.0 as current directory. Did the .bat script change directory first? - It is unusual to use / as a path separator on Windows -- xplanet-1.2.0\xplanet.exe is more normal. Some parts of Windows tolerate both, others do not, IIRC. But Python itself should not care in this case. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From __peter__ at web.de Fri Aug 24 01:28:58 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 24 Aug 2007 07:28:58 +0200 Subject: List Comprehension Question: One to Many Mapping? References: <1187929443.636690.287450@i13g2000prf.googlegroups.com> Message-ID: beginner wrote: > How do I map a list to two lists with list comprehension? > > For example, if I have x=[ [1,2], [3,4] ] > > What I want is a new list of list that has four sub-lists: > > [[1,2], [f(1), f(2)], [3,4], [f(3), f(4)]] > > [1,2] is mapped to [1,2] and [f(1), f(2)] and [3,4] is mapped to > [3,4], [f(3), f(4)]. > > I just can't find any way to do that with list comprension. >>> [a for b in ((item, map(f, item)) for item in x) for a in b] [[1, 2], [f(1), f(2)], [3, 4], [f(3), f(4)]] > I ended up > using a loop (untested code based on real code): > > l=[] > for y in x: > l.append(y) > l.append([f(z) for z in y]) Using a loop gives you clearer code in this case, so I'd use that. Peter From horpner at yahoo.com Fri Aug 31 08:57:15 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 31 Aug 2007 12:57:15 GMT Subject: Python doesn't see the directories I create References: <46d6856b$0$17674$426a74cc@news.free.fr> Message-ID: On 2007-08-31, Lawrence D'Oliveiro wrote: > In message , Neil > Cerutti wrote: >> Keeping in mind which came first, isn't it at least as >> accurate to attribute this problem to Python's choice of >> escape character? > > No, it's Microsoft's fault. The use of backslash as an escape > character goes back to Unix systems in the early 1970s--long > before Microsoft came on the scene. > > When Microsoft introduced MS-DOS 1.0 in 1981, it didn't have > directory hierarchies. Commands used the slash character to > delimit options. Then when MS-DOS 2.0 introduced subdirectories > in 1983, they decided they couldn't use the slash as the path > separator, so they used the backslash instead. That has been a > source of confusion ever since then. Going back and checking the Python History page, it seems I was off by four years with when I thought Python was first released (I was thinking 1995, when the first release was actually 1991). That makes Python's choice of escape character way more practical than I thought, since Microsoft hadn't yet conquered the desktop computing world when Python was in it's infancy. That strange whirring sound is me backpedaling furiously. Thanks very much for all your patiences. -- Neil Cerutti If you throw at someone's head, it's very dangerous, because in the head is the brain. --Pudge Rodriguez From jeremy at omba.demon.co.uk Wed Aug 15 09:33:51 2007 From: jeremy at omba.demon.co.uk (Jeremy C B Nicoll) Date: Wed, 15 Aug 2007 14:33:51 +0100 Subject: What order does info get returned in by os.listdir() References: <5igd1gF3mc1akU1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Wed, 15 Aug 2007 12:34:27 +0100, Jeremy C B Nicoll wrote: > > > I've some supplementary questions... my original code was looking at > > each leafname in turn via > > > > for leaf in os.listdir(path): > > wholefile = os.path.join(path,leaf) > > if os.path.isfile(wholefile): > > if leaf.startswith("~"): > > > > etc. But I now realise I might alternatively do something like: > > > > leaflist = os.listdir(path) > > > > for leaf in leaflist: > > But this is doing something different that the above code!? I'm not sure if I understand you. I know it's only "equivalent" to the first line of what's above, ie iterate over a list of names, and obviously it's got the sorting of that list done, but do you mean there's some other difference? > > How would I sort leaflist in a way that mimics the sort order that XP > > shows me things under? > > This depends on what XP is. Which program? Which locale? How does the > locale influence that programs sorting? Well... XP is Windows XP (Pro as I think I said earlier), and I'm in the UK. I explained earlier how XP shows me stuff in order when I tell it to sort by name. > > > Secondly, my code is wasting time looking at subdirectories/files which > > I already know I'm not interested in. Is there a way to restrict > > listdir to, say, only return info about subdirectories, or only about > > dirs/files whose names match a pattern? > > `os.listdir()` always returns all names. You can or have to filter the > result if you are only interested in some of the names. Simple pattern > matching on names can be done with `glob.glob()`. > > > Thirdly, once I've go a list of leafnames, somehow, is there a way to > > ask Python if a specific leaf-value is in that list, without explicitly > > looping through the items in the list? > > With the ``in`` operator you have an implicit loop over the list. > > if 'readme.txt' in leafnames: > print 'Hurray!' OK, that looks useful. Thanks. -- Jeremy C B Nicoll - my opinions are my own. From bjourne at gmail.com Sun Aug 5 07:33:33 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sun, 5 Aug 2007 11:33:33 +0000 Subject: Best programs written completly in Python In-Reply-To: References: Message-ID: <740c3aec0708050433x15979d6eq73031c962b0f52c5@mail.gmail.com> On 8/5/07, Franz Steinh?usler wrote: > Hello NG, > > wWhat are the best programs in your opinion, written entirly > in pyhton, divided into categories like: > a) Games > b) Utilities/System > c) Office > d) Web/Newsreader/Mail/Browser For b; trac: http://trac.edgewall.org/ There actually isn't that many widespread programs written in Python. -- mvh Bj?rn From steve at holdenweb.com Wed Aug 1 07:01:42 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 01 Aug 2007 07:01:42 -0400 Subject: access the name of my method inside it In-Reply-To: <5hb1ebF3inuf2U6@mid.uni-berlin.de> References: <1185959202.302467.276080@x35g2000prf.googlegroups.com> <5hb1ebF3inuf2U6@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Wed, 01 Aug 2007 09:06:42 +0000, james_027 wrote: > >> for example I have this method >> >> def my_method(): >> # do something >> >> # how do I get the name of this method which is my_method here? > > Why do you need this? There are ways but those are not really good for > production code. > Maybe he wants to write a recursive method? Once way is to call self.__calss__.mymethod(self). Ugly, isn't it? >>> class p: ... def mymethod(self, n): ... if n <= 1: ... return 1 ... else: ... return n * self.__class__.mymethod(self, n-1) ... >>> pp = p() >>> pp.mymethod(10) 3628800 >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bscrivener42 at gmail.com Thu Aug 23 00:23:38 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Thu, 23 Aug 2007 04:23:38 -0000 Subject: Baby Steps, optionDB In-Reply-To: References: Message-ID: <1187843018.391276.303410@z24g2000prh.googlegroups.com> On Aug 22, 10:41 pm, "W. Watson" wrote: > clError: couldn't open "optionDB": no such file or directory Because the file doesn't exist? Did you make an optionDB file? http://tinyurl.com/283o98 From carsten at uniqsys.com Thu Aug 30 20:58:38 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 30 Aug 2007 20:58:38 -0400 Subject: list index() In-Reply-To: <1188517370.998114.119940@q4g2000prc.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188495863.242815.236900@o80g2000hse.googlegroups.com> <87bqcod2gq.fsf@benfinney.id.au> <1188517370.998114.119940@q4g2000prc.googlegroups.com> Message-ID: <1188521918.3258.10.camel@localhost.localdomain> On Thu, 2007-08-30 at 16:42 -0700, zzbbaadd at aol.com wrote: > It suddenly dawned on me that what would be best would be a contains() > (or IN syntax for those who can't afford to wait) for lists. Either I'm misunderstanding what you mean or you need to get a clue about what Python can already do before you go around making suggestions for what Python needs. Lists have supported "in" tests since at least version 1.5.2: Python 1.5.2 (#1, Nov 6 1999, 14:53:40) [C] on sco_sv3 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> if 3 in [1,2,3]: print "Yup, got it!" ... Yup, got it! This feature may be older than version 1.5.2, but this is the oldest version that I still have running anywhere. -- Carsten Haese http://informixdb.sourceforge.net From Kevin.Smith at sas.com Wed Aug 15 12:39:31 2007 From: Kevin.Smith at sas.com (Kevin D. Smith) Date: Wed, 15 Aug 2007 10:39:31 -0600 Subject: Move files/directories to Recycle Bin using standard Python libs Message-ID: I would like to move files and directories to the Recycle Bin on Windows from Python. I have found some older articles describing how to do this, but they require additional packages to be installed. I'm working on a plugin for an existing project and only have the standard library to work with. Is there a way to use the Recycle Bin using standard Python? -- Kevin D. Smith From grante at visi.com Tue Aug 21 23:33:52 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 22 Aug 2007 03:33:52 -0000 Subject: Chaining programs with pipe References: <1187734166.384152.178040@o80g2000hse.googlegroups.com> <1187743235.124030.321200@l22g2000prc.googlegroups.com> Message-ID: <13cnbl0p9qf26e0@corp.supernews.com> On 2007-08-22, Karthik Gurusamy wrote: > Not sure on non-unix platforms, but in unix like platforms it's best > to reuse shell's power. > >>>> import commands >>>> commands.getoutput('ls | wc') > ' 4 4 24' >>>> Executing a shell just because you want a pipe seems like a bit of overkill. Doing it the "right" way with subprocess is pretty trivial. -- Grant Edwards grante Yow! I was born in a at Hostess Cupcake factory visi.com before the sexual revolution! From jarausch at skynet.be Sat Aug 11 14:30:54 2007 From: jarausch at skynet.be (Helmut Jarausch) Date: Sat, 11 Aug 2007 20:30:54 +0200 Subject: decorators - more than just syntactic sugar Message-ID: <46be005e$0$13866$ba620e4c@news.skynet.be> Hi, are decorators more than just syntactic sugar in python 2.x and what about python 3k ? How can I find out the predefined decorators? Many thanks for your help, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From __peter__ at web.de Thu Aug 16 04:12:13 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 16 Aug 2007 10:12:13 +0200 Subject: ploting issues in program References: <1187250500.571837.196940@19g2000hsx.googlegroups.com> Message-ID: yadin wrote: > can you please help me to fix these polar plot in db's > so that the center is at the minimun negative number in voltagedb > about [-50] > and the maximun is at zero and how can i see values on the axis like > showing that the axes start at -50 -40 -30 .....and end at zero You posted this question several times now and got no response that you liked enough to abstain from reposting. Now your options are: - Try another forum (the matplotlib mailing list would be a good candidate) - Show some initiative: add 50 to the dB values and be done > here is the program [...] > voltagedb = [-48.7906044 ,-11.51244516, -5.58650713, -2.34604603, > -0.56767793, 0. , > -0.60034598, -2.41427014, > -5.7042726 ,-11.75411924,-48.7906044 , > -11.51244516, -5.58650713, -2.34604603, -0.56767793, > 0. , > -0.60034598, -2.41427014, -5.7042726 ,-11.75411924,] voltagedb = [v+50 for v in voltagedb] > polar(angteta,voltagedb) > > show() Good luck, Peter From samushack at gmail.com Thu Aug 23 13:39:11 2007 From: samushack at gmail.com (samushack at gmail.com) Date: Thu, 23 Aug 2007 10:39:11 -0700 Subject: simple spider in python In-Reply-To: References: <1187876014.845912.236690@e9g2000prf.googlegroups.com> <1187879398.007797.128510@i13g2000prf.googlegroups.com> <1187880988.813113.20350@l22g2000prc.googlegroups.com> Message-ID: <1187890751.871660.275320@z24g2000prh.googlegroups.com> > Somewhere in the middle between the two suggestions you've already > received is . I followed that link, and got an error page... As to the Google API key issue, I was unaware of that. Very annoying of them to stop that service. PyGoogle will basically be useless. The next best thing might be getting an API key for the AJAX API, and using a browser based implementation... From ricaraoz at gmail.com Wed Aug 29 17:44:13 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 29 Aug 2007 18:44:13 -0300 Subject: copying files In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE30E@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE30C@efmailx> <46D5C01B.7080202@bigfoot.com> <93066C069973ED448DC2BCEA9C44A7383BE30E@efmailx> Message-ID: <46D5E8AD.8050505@bigfoot.com> Brian McCann wrote: > > > > Hi Ricardo, > > what do the + signs do? > Add the different strings. You had 'm' and 'TEST_HOME' inside a string, so they would be taken as characters and not variables. >>> TEST_HOME = "/v01/test_home" >>> m = "./lib" >>> "cp -r " + m + " " + TEST_HOME 'cp -r ./lib /v01/test_home' <----- This is what you want. >>> "cp -r m TEST_HOME" 'cp -r m TEST_HOME' <----- This is NOT what you want. > > ________________________________ > > From: Ricardo Ar?oz [mailto:ricaraoz at gmail.com] > Sent: Wed 8/29/2007 2:51 PM > To: Brian McCann > Cc: python-list at python.org > Subject: Re: copying files > > > > Brian McCann wrote: >> Hi, >> >> with the code below I set a variable TEST_HOME to a path and the >> variable m to a path >> in my current dir. >> I have a symbolic link setting m---->lib >> when I run the script I get no errors and the lib dir with its 20 files >> does not get copied to /v01/test_home >> any help would be greatly appreciated >> >> --Brian >> >> #!/usr/bin/python >> import string >> import os >> import sys >> import errno >> import shutil >> import tarfile >> >> TEST_HOME = "/v01/test_home" >> m = "./lib" >> os.system("cp -r m TEST_HOME") >> #os.system("tar -cvf viziant-ingestion.tar /v01/") >> > > Sorry, meant : os.system("cp -r " + m + " " + TEST_HOME) > > > > From arkanes at gmail.com Wed Aug 15 09:31:54 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 15 Aug 2007 08:31:54 -0500 Subject: wxPython before MainLoop In-Reply-To: References: <13bl9a75laqcm70@corp.supernews.com> <6a6dnfbbFJNzcCbbnZ2dnUVZ_oudnZ2d@comcast.com> Message-ID: <4866bea60708150631k58deff6coae7a45eb6a950d9a@mail.gmail.com> On 8/15/07, samwyse wrote: > Chris Mellon wrote: > > On 8/9/07, Heikki Toivonen wrote: > > > >>[david] wrote: > >> > >>>I'd like to refresh the display before I start the main loop. > > If your window isn't able to interact with the user, then I'd consider > it a splash screen, no matter if it does look exactly like your main > application interface. > > >>We have this kind of situation in Chandler, where we display and update > >>the splash screen before we enter MainLoop. > >> > [...] > >>3. The splash screen refresh is basically: draw new stuff, > >>self.Layout(), self.Update(), wx.Yield() > >>http://lxr.osafoundation.org/source/chandler/application/Application.py#1421 > > Looking at the Chandler code suggests a solution to [david]'s original > problem. It is possible that, on Windows only, he may need to call > Update to finish painting the display. > > 1432 self.Layout() > 1433 if wx.Platform == '__WXMSW__': > 1434 self.Update() > 1435 wx.GetApp().Yield(True) > > > wxYield spins the event loop in place. This can have some serious > > consequences if you aren't very careful with your usage, like > > recursively entering event handlers. I generally consider it an > > experts only interface, and avoid it. > > I'll confess to being one of those old-school programmers who, back in > the day, wrote his code around big select loops instead of using > threads, but I'm intriged by the "experts only" designation. Can > someone explain further? Thanks! The biggest problem is recursive events. You can end up entering an event handler downstack from itself. There's other common problems - event handlers are generally written to be short and sweet and not to expect recursion and to complete without interruption. wxYield can easily end up breaking that. Components that call wxYield are especially dangerous. For example, some parts of wxWidgets call wxYield internally. An event handler that aquired a lock was changed to use one of those components and ended up deadlocking when it was re-entered by the yield. I've also seen crashes when wxYield processed a destroy event for a window in the middle of it's own event handler. Because analyzing your event code to make sure it's reentrant is hard, and is complicated even more by the fact that wxYield in a component can cause problems far upstack in a caller, and because there is an excellent alternative in the form of python generators, I avoid it's usage from wxPython entirely. From p.f.moore at gmail.com Sat Aug 18 12:48:29 2007 From: p.f.moore at gmail.com (Paul Moore) Date: Sat, 18 Aug 2007 09:48:29 -0700 Subject: Memory leak when creating lots of object In-Reply-To: <1187322688.545415.122010@i38g2000prf.googlegroups.com> References: <1187067442.084074.55010@z24g2000prh.googlegroups.com> <1187190827.395382.85740@57g2000hsv.googlegroups.com> <1187322688.545415.122010@i38g2000prf.googlegroups.com> Message-ID: <1187455709.206054.16380@a39g2000hsc.googlegroups.com> On 17 Aug, 04:51, Godzilla wrote: > On Aug 16, 1:13 am, Paul Moore wrote: > > On 14 Aug, 05:57, Godzilla wrote: > > Do you see memory growth with precisely this code? Over what period? > > How much? > > I have it running for more than 1 hour... the main application > software runs for about 50 days non stops and the memory just keep > growing... I'm sorry. Just to be precise, how long would I need to run the code you posted to see a memory growth? > What should I do next? Can I force garbage collection manually? If so, > how do I do that? As Terry suggested, look at the gc module (gc.collect). But on inspection, I don't see a memory leak that would be cured by forcing a collection, which is why I'd like to reproduce the problem before offering suggestions... Paul. From richmoore44 at gmail.com Thu Aug 16 08:03:41 2007 From: richmoore44 at gmail.com (richmoore44 at gmail.com) Date: Thu, 16 Aug 2007 12:03:41 -0000 Subject: Layer 2 socket connection In-Reply-To: <1187202110.958564.206770@l22g2000prc.googlegroups.com> References: <1187202110.958564.206770@l22g2000prc.googlegroups.com> Message-ID: <1187265821.989249.276090@r34g2000hsd.googlegroups.com> On Aug 15, 7:21 pm, alisonken1 wrote: > Hello all - > > I'm looking at trying to write a python script to connect to a layer 2 > bridge (no IP available). > > Looking at the sockets function, it's not clear if I can connect using > only the mac address - it appears to want either a broadcast address > or a specific IP address. > > Can anyone give me a clue on opening a layer 2 socket in Python? I use impacket for stuff like that, see http://oss.coresecurity.com/projects/impacket.html Cheers Rich. From bj_666 at gmx.net Sat Aug 11 15:01:15 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Aug 2007 19:01:15 GMT Subject: Who told str() to round my int()'s!!! References: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> <5i67roF3ml00gU4@mid.uni-berlin.de> <1186852205.973858.284130@r34g2000hsd.googlegroups.com> Message-ID: <5i6fbrF3ml00gU6@mid.uni-berlin.de> On Sat, 11 Aug 2007 17:10:05 +0000, Adam W. wrote: > On Aug 11, 12:53 pm, Marc 'BlackJack' Rintsch wrote: >> If `str()` would not round you would get very long numbers because of the >> inaccuracies of floating point values. I know Python is lying when 0.1 >> prints as 0.1, but do you really want to see >> 0.10000000000000000555111512312578270211815834045410156250 instead? > > I want str() to convert whatever I give it to a string and do nothing > else. But those long numbers are very disturbing and nobody wants them as usual string representation. Most programming languages "lie" at this point to the user so it would be very unexpected too. > I will worry about long FP values in previous steps. What do you mean here? Have you looked at the example above? That is the closest you get to 0.1 -- there's no way to round the floating point value, it can only be done by converting to `str()`. Ciao, Marc 'BlackJack' Rintsch From vedrandekovic at v-programs.com Tue Aug 7 08:27:56 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Tue, 07 Aug 2007 05:27:56 -0700 Subject: distutils Message-ID: <1186489676.042901.236140@w3g2000hsg.googlegroups.com> Hello again, Is there any patch for python "distutils", for this >>> from distutils import log,dir_util ImportError: cannot import name log Regards, Vedran From kyosohma at gmail.com Tue Aug 14 14:43:32 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 14 Aug 2007 11:43:32 -0700 Subject: Opinions about this new Python book? In-Reply-To: References: <1187096231.194685.86030@m37g2000prh.googlegroups.com> <20070814154913.D8C3C1E400A@bag.python.org> <8a6b8e350708141020q495b22der4c362ee3df618d82@mail.gmail.com> Message-ID: <1187117012.088495.247890@q4g2000prc.googlegroups.com> On Aug 14, 12:46 pm, "Shawn Milochik" wrote: > Yes, please post back to the list. I saw this book on Amazon, but > there's no table of contents listed, nor is there one on the > publisher's site. > > Thanks, > Shawn > > On 8/14/07, James Matthews wrote: > > > > > i got to say that the best python book i bought was Core Python Programming > > (2nd) by Wesly Chun! Aside for all the spelling mistakes and syntax errors > > that there are i feel that the book really explained the language well for > > someone coming from another programming language! > > > On 8/14/07, Dick Moores wrote: > > > At 05:57 AM 8/14/2007, kyoso... at gmail.com wrote: > > > >On Aug 14, 7:05 am, Dick Moores wrote: > > > > > I'd appreciate opinions about this new Python book. > > > > > > Title: Python Power!: The Comprehensive Guide > > > > > Author: Matt Telles > > > > > Publisher: Course Technology > > > > > Pub. Date: Jul 27, 2007 > > > > > Edition: 1st edition > > > > > Binding: Paperback > > > > > Pages: 508 > > > > > ISBN: 1598631586 > > > > > List Price: 34.99 USD > > > > > > The book on the publisher's website: > > > > > > And at BestBookDeal.com: > > > > > > > > > > > Thanks, > > > > > > Dick Moores > > > > >I just got this book over the weekend. I'll start reading/skimming > > > >through it this week and hopefully remember to get back to you. > > > > Thanks! > > > > > By the > > > >way, why do you want to know? > > > > If the experts like it, I'll buy it. > > > > Dick > > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > -- > >http://www.goldwatches.com/ > >http://www.jewelerslounge.com > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Please read:http://milocast.com/2007/07/31/this-i-believe/ Here's an abbreviated Table of Contents...just chapter titles. The book's table of contents also lists section headers. Chapter 1: About Python Chapter 2: Python Language Overview Chapter 3: Tools Chapter 4: Data Types Chapter 5: Control Flow Chapter 6: Input & Output Chapter 7: Functions & Modules Chapter 8: Exception Handling Chapter 9: Object-Oriented Programming Chapter 10: Classes and Objects in Python Chapter 11: The Python Library Chapter 12: The GUI - Tkinter Chapter 13: The Web Server - Apache Chapter 14: Working with Databases Chapter 15: Putting It All Together Chapter 16: Python and Graphics Mike From fdu.xiaojf at gmail.com Thu Aug 23 03:02:18 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Thu, 23 Aug 2007 15:02:18 +0800 Subject: Are there precompiled python for sgi ? Message-ID: <46CD30FA.4030201@gmail.com> Hi, Are there precompiled python for sgi(IRIX6.5) to download? Several packages(_socket, Tkinter, ...) always failed when I tried to build python from source on our machine running IRIX6.5. Thanks! From andre.roberge at gmail.com Thu Aug 2 10:14:58 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Thu, 02 Aug 2007 14:14:58 -0000 Subject: Determining if file is valid image file Message-ID: <1186064098.587590.91210@g4g2000hsf.googlegroups.com> Other than installing PIL, is there a "simple" way using Python only to determine if a file is a valid image file? I'd be happy if I could at least identify valid images files for gif, jpeg and png. Pointers to existing modules or examples would be appreciated. The reason why I'd prefer not using PIL is that I'd like to bundle such a function/module in my app. Andr? From JYOUNG79 at kc.rr.com Fri Aug 3 20:48:56 2007 From: JYOUNG79 at kc.rr.com (JYOUNG79 at kc.rr.com) Date: Fri, 03 Aug 2007 19:48:56 -0500 Subject: xlrd question Message-ID: Hi John, Thanks very much for your reply. And thanks for taking the time to create xlrd... this is a very cool and impressive program!! :-) I ran your code which gave me this: >>> import sys, xlrd; print sys.version; print xlrd.__file__ 2.3.5 (#1, Jan 30 2006, 13:30:29) [GCC 3.3 20030304 (Apple Computer, Inc. build 1819)] /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/ xlrd/__init__.pyc and as far as I can tell, the runxlrd.py file is located here (where I had drug this folder originally): Macintosh HD/xlrd-0.6.1/scripts/runxlrd.py So if I'm understanding this correctly, xlrd only uses the folder you download (xlrd-0.6.1) and then moves the '__init__.pyc' file to the location mentioned above? I apologize if I don't sound very intelligent with this - I'm completely new to Python. There's definitely no problems or concerns. :-) I'm doing a bit of research to see if this might be something I use down the road at work. Our I/T department is extremely strict as to what we put on employees machines so I want to have a good understanding as to where files are installed so I can let i/T know all the details. One department in particular that I support uses a lot of Excel macros that I wrote quite awhile back. Unfortunately, I've heard that Microsoft is planning on taking VBA out of the next version of Excel on the Mac platform. I don't mind converting everything over to AppleScript but I'm researching other alternatives. I just installed xlrd on my home machine last night and was really impressed with the few things I was able to figure out. While I'm talking about Excel, is there any other program (for Python) that can edit Excel files? Will xlrd ever get this capability (I believe someone mentioned xlwr on another post)? Thanks again for replying to my post and thank you very much for sharing your awesome program! :-) Jay From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Aug 27 07:51:36 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 27 Aug 2007 13:51:36 +0200 Subject: beginner, idomatic python 2 In-Reply-To: <13d4jfjfogbvq6f@corp.supernews.com> References: <13csjmeaoqh9le3@corp.supernews.com> <1187927388.173203.298660@e9g2000prf.googlegroups.com> <13d4jfjfogbvq6f@corp.supernews.com> Message-ID: <46d2ba7a$0$430$426a74cc@news.free.fr> bambam a ?crit : Steve, could you please stop top-posting ?-) TIA > "Dan Bishop" wrote in message > news:1187927388.173203.298660 at e9g2000prf.googlegroups.com... >> On Aug 23, 10:21 pm, "bambam" wrote: >>> Would someone like to suggest a replacement for this? This is a >>> function that returns different kinds of similar objects, depending >>> on what is asked for. PSP and PWR are classes. I don't really >>> want to re-write the calling code very much: I'm just wondering >>> if the function can be replaced with some kind of OOP pattern. >>> >>> def Device(DeviceType): >>> if DeviceType=='PSP': >>> return PSP() >>> elif DeviceType=="Power Supply" >>> return PWR() >>> etc... >>> >>> Thanks! >> Typically, you'd use a dictionary: >> >> DEVICE_DICT = { >> 'PSP': PSP. >> 'Power Supply': PWR, >> # etc. >> } >> >> and your function would simply return DEVICE_DICT[device_type]() >> > Thank you. I didn't reply earlier because I was trying to get my > head around what you wrote, which was strange and foreign > to me. > > It seems to me that the dictionary object you suggested is a > direct replacement for the function code, Almost, yes !-) > only more efficient > because the case table is internalised with a hash table, and > the original if/elif/else case table was unlikely to be implemented > as a hash table. > > And presumably, it is idiomatic It is. Dicts are probably the central data structure in Python, and are highly optimised. You'll find quite a lot of dict-based dispatch in Python code. > because Python programmers > expect to use dictionaries for their lookup tables. Indeed - that's what dictionnaries are for. > You have answered a question I didn't know enough to ask :~) > --which is why I started with the general question, so I don't > feel too stupid about that --. > > And now I wonder about the 'other' question. Should I consider > dynamically overriding the methods in my 'Device' class, instead > of creating separate classes for the Psp and Pwr devices? > I could create an object of the base Device class, and at init > I could make sure the methods were connected for a Psp or > a Pwr device. When (if ever) is that a good idea? While it's technically possible, I wouldn't advise such a design (which looks pretty close to the Prototype pattern) unless you need to have something *highly* extensible and customisable (and even then, there are other - possibly better - ways, depending on the context). If the Device taxonomy is stable and well defined, you're certainly DoingTheSimplestThing (here, a dict-based dispatch encapsulated in a factory function...). As a side note, in Python, inheritance is mostly an implementation detail, and should usually not be used for typing. My 2 cents... From steve at holdenweb.com Sat Aug 11 10:19:29 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 11 Aug 2007 10:19:29 -0400 Subject: LRU cache? In-Reply-To: References: <7x8x8ixomj.fsf_-_@ruckus.brouhaha.com> Message-ID: Thomas Wittek wrote: > Paul Rubin schrieb: >> Anyone got a favorite LRU cache implementation? I see a few in google >> but none look all that good. I just want a dictionary indexed by >> strings, that remembers the last few thousand entries I put in it. > > I don't know a module for that (although it might exist), but I could > imagine how to implement it. > > Generally a LRU cache could be implemented as a (linked) list with a > max. size of N. > On usage of an object this object will be moved to the top of the list > (and removed from the old position). > If it's not yet stored in the cache, you (fetch it from the source and) > add it on top and remove the last one, if the list exceeds N entries. > > So you need to do two things: > 1) Maintain a list: Use a (linked) list. > 2) Random access to that list: Use a dict (hash), that also has to be > updated on removal/addition of objects. > Paul's an old enough hand that he's well able to determine this for himself. He's also polite enough not to reply along those lines :-) *I* don't know of module for tracking how plants grow, but I could imagine how to implement it ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From paul at boddie.org.uk Fri Aug 3 10:51:17 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 03 Aug 2007 07:51:17 -0700 Subject: (no) fast boolean evaluation ? missing NOT In-Reply-To: References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> <1186096979.397596.36640@e16g2000pri.googlegroups.com> Message-ID: <1186152677.730158.111420@w3g2000hsg.googlegroups.com> On 3 Aug, 11:45, Stef Mientki wrote: > > Sorry, my question missed the essential "NOT", > here is an example, that behaves different in Delphi, > (so I guess Delphi is not a real language ;-) Delphi is based on Pascal, and from what I can recall from my university textbook, there isn't any mandatory short-circuit evaluation in Pascal: it's an implementation-dependent feature. Consequently, an expression involving boolean operators in such languages may well evaluate each term (potentially causing side- effects) before determining the final result. Paul From semanticist at gmail.com Fri Aug 31 10:42:49 2007 From: semanticist at gmail.com (Miles) Date: Fri, 31 Aug 2007 10:42:49 -0400 Subject: fcntl problems In-Reply-To: <1188568022.988154.188230@y42g2000hsy.googlegroups.com> References: <1188512377.441241.107900@q4g2000prc.googlegroups.com> <1188515889.352267.220790@q5g2000prf.googlegroups.com> <1188568022.988154.188230@y42g2000hsy.googlegroups.com> Message-ID: On 8/31/07, mhearne808 wrote: > I have a script that will be run from a cron job once a minute. One > of the things this script will do is open a file to stash some > temporary results. I expect that this script will always finish its > work in less than 15 seconds, but I didn't want to depend on that. > Thus I started to look into file locking, which I had hoped I could > use in the following fashion: > > Process A opens file foo > Process A locks file foo > Process A takes more than a minute to do its work > Process B wakes up > Process B determines that file foo is locked > Process B quits in disgust > Process A finishes its work That would look like (untested): import fcntl, sys f = open('foo', 'w+') try: fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError, e: if e.args[0] == 35: sys.exit(1) else: raise f.seek(0, 2) # seek to end # do your thing with the file f.flush() fcntl.flock(f.fileno(), fcntl.LOCK_UN) f.close() -Miles From robert.rawlins at thinkbluemedia.co.uk Fri Aug 3 04:23:53 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 3 Aug 2007 09:23:53 +0100 Subject: File Handling & TRY/EXCEPT Message-ID: <00af01c7d5a7$a12723a0$e3756ae0$@rawlins@thinkbluemedia.co.uk> Hello Guys, I'm looking for some advice on how best to handle file read/write errors with try/except as i'm a little vague on this, I have a small memory leak in my app and I'm starting to think its generated by my log file write. For an example of the function look below. def addAppLog(self, event): try: logfile = open('/pblue/new/Logs/Application.csv','a') now = datetime.datetime.now() logstring = '%s,%s \n' % (event, str(now)) logfile.write(logstring) except: self.addAppLog(event) else: logfile.close() Now I'm looking for some help to sort this out as I'm sure it's pretty untidy, I want to make it as air tight as possible. The basic concept was that if it tries writing to the log file and it fails, then it needs to reattempt it, right? What's the best way to handle this to ensure that there are not any memory leaks caused when the file is open() but not followed by a close(). I'm running 2.4 and I know some of these newer versions don't need you to explicitly close() the file objects, but I would certainly feel a lot better. Any advice? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From roger.miller at nova-sol.com Thu Aug 16 16:49:09 2007 From: roger.miller at nova-sol.com (Roger Miller) Date: Thu, 16 Aug 2007 13:49:09 -0700 Subject: A problem with Time In-Reply-To: <1187293581.631314.243650@a39g2000hsc.googlegroups.com> References: <46c469be$0$66145$7b0f0fd3@mistral.news.newnet.co.uk> <1187293581.631314.243650@a39g2000hsc.googlegroups.com> Message-ID: <1187297349.471976.318460@x40g2000prg.googlegroups.com> On Aug 16, 9:46 am, MRAB wrote: > > As well as the other replies, this also works (as far as I can tell!): > > import time > today = time.localtime() > yesterday = today[ : 2] + (today[2] - 1, ) + today[3 : ] > yesterday = time.localtime(time.mktime(yesterday)) This is something I have wondered about. The C library mktime function is documented to fix up out of range values,. For example July 32 becomes August 1 and August -1 becomes July 31. Python presumably inherits this very useful (and seemingly not well known) behavior, but it is not documented. Is this just an oversight, or is it intentional on the grounds that it might be platform-dependent? Any language lawyers out there that would care to comment? From martin at v.loewis.de Thu Aug 9 03:00:12 2007 From: martin at v.loewis.de (=?ISO-8859-2?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 09 Aug 2007 09:00:12 +0200 Subject: tokenize module after installation In-Reply-To: <1186599829.900252.127640@g4g2000hsf.googlegroups.com> References: <1186599829.900252.127640@g4g2000hsf.googlegroups.com> Message-ID: <46babb7c$0$2914$9b622d9e@news.freenet.de> > After installation my program that uses tokenize module,when I run > myprogram.exe (vgsveki.exe): > > AttributeError: 'module' object has no attribute 'untokenize' Perhaps you use the 2.4 version of tokenize.py here, which did not have untokenize. Regards, Martin From martin.marcher at gmail.com Thu Aug 30 01:10:47 2007 From: martin.marcher at gmail.com (Martin Marcher) Date: Thu, 30 Aug 2007 07:10:47 +0200 Subject: We need PIGs :) Message-ID: Hello, having worked quite a bit with python in the last months (some Java before, and some C++ before that) I was very impressed by an idea the Java people had. Explanation: the JSRs define how to implement certain services and or features in Java so that they can be reused. I haven't found such a thing for python yet. Say I have the problem of authentication. Now I can implement authentication against a text file with a "key : value" format. However someone may find it more suitable to implement a authentication backend for exactly this app that can use postgres. Who else can use the authentication for my program created by a third party in his or her own app/package/module? To my knowledge noone as there's nothing you could at least theoretically keep to. My idea was to define "Python Implementation Guidelines" (PIGs) that specify a problem formalize it enough so that implementations are interchangeable (in this example create a module that has an "authenticate(username, password)" method so that one could easily take that module for any given app and then authenticate against postgres, and also against my plaintext file (which was the original - quite useless - implementation). Does that sound like a good idea or would that be over formalization? Personally I think that would be great as I could search the PIGs at (hopefully) python.org find out the number and search at koders.com or code.google.com for python code that has "PIG: XXX" in the metadata docstring or wherever - maybe even a __pig__ = XXX variable. any input is welcome (also point me to the place where that can be found if it already exists) martin From gagsl-py2 at yahoo.com.ar Thu Aug 2 18:52:07 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 02 Aug 2007 19:52:07 -0300 Subject: (no) fast boolean evaluation ? References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> Message-ID: En Thu, 02 Aug 2007 18:47:49 -0300, Stef Mientki escribi?: > I discovered that boolean evaluation in Python is done "fast" > (as soon as the condition is ok, the rest of the expression is ignored). > > Is this standard behavior or is there a compiler switch to turn it > on/off ? The exact behavior is defined in the Language Reference "The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned. The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned. Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value." Tutorial section 5.7 say the same thing in a colloquial way. -- Gabriel Genellina From daniels at dsl-only.net Tue Aug 28 00:14:59 2007 From: daniels at dsl-only.net (Scott David Daniels) Date: Mon, 27 Aug 2007 21:14:59 -0700 Subject: "Try:" which only encompasses head of compound statement In-Reply-To: <87wsvgfszm.fsf@benfinney.id.au> References: <1188250535.607963.42540@22g2000hsm.googlegroups.com> <87wsvgfszm.fsf@benfinney.id.au> Message-ID: <13d7898odj2g19b@corp.supernews.com> Ben Finney wrote: > Jameson.Quinn at gmail.com writes: > ... try to only catch exceptions from the > minimum amount of code that does one discrete action. > > try: > input_file = open(my_filename) > except IOError, exc: > print "Can't open myfile: %(exc)" % locals() > > for line in input_file: > count += open_and_process_subfile(line) Actually, this will be followed by some foolishness because (1) print "Can't open myfile: %(exc)" % locals() Should at least be: print "Can't open myfile: %(exc)s" % locals() But more reasonably: print "Can't open myfile: %s" % exc and (2) Even if the print succeeds, the code will fall through into the loop and you'll (if you are lucky) get a complaint about NameError: name 'input_file' is not defined You'd need to "raise" after the print, but the normal IOError failure to open message already includes the name of the file it tried to get to in an attribute "filename", so just catch it outside this code (as others have already suggested). -Scott David Daniels Scott.Daniels at Acm.Org From wahab-mail at gmx.net Fri Aug 24 09:07:56 2007 From: wahab-mail at gmx.net (Mirco Wahab) Date: Fri, 24 Aug 2007 15:07:56 +0200 Subject: Regular expression use In-Reply-To: References: Message-ID: Nick Maclaren wrote: > For reasons that I won't explain, as they are too complicated > and not terribly relevant, I am interested in discovering what > people actually use regular expressions for. Not the subject > domain, but the construction of the regular expressions. After I figured out how to solve a problem, I'll surely rewrite the solution again in pure Perl5 regular expressions in order to outrun the normal mental degradation processes related to aging ... :) > I know about computer scientists and parsing, and I know about > the use of relatively simple ones for things like extracting > HTML links from Web pages. But I don't have much feel for the > (probably rare but difficult) uses of more complex ones for Using complex regular expressions is like tank destruction with contact charges glued on them. Only a few people will even survive the first "usage", but survivors will then eventually be able to destroy almost every tank with tremendous speed and precision. > other purposes. I have heard of several such uses, but don't > have an overall idea of what is going on. On business software projects, maintainability is a key prerequisite - after using complex regular expressions on business critical parts you are bound to involve very very expensive maintenance programmers ... :) What exactly did you "hear" of several "uses"? Which application? Academia, Business, ...? Regards M. From steve at holdenweb.com Fri Aug 24 07:42:12 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 24 Aug 2007 07:42:12 -0400 Subject: Does shuffle() produce uniform result ? In-Reply-To: References: Message-ID: tooru honda wrote: > Hi, > > I have read the source code of the built-in random module, random.py. > After also reading Wiki article on Knuth Shuffle algorithm, I wonder if > the shuffle method implemented in random.py produces results with modulo > bias. > > The reasoning is as follows: Because the method random() only produces > finitely many possible results, we get modulo bias when the number of > possible results is not divisible by the size of the shuffled list. > > 1. Does shuffle() produce uniform result ? > Given the cycle length of the Mersenne twister algorithm that generates the underlying random numbers, it would have to be a pretty long list to see a significant bias, don't you think? Have you done any calculations on the length of list you propose to use? > 2. If not, is there a fast and uniform shuffle() available somewhere ? > Frankly I don't think you need to worry. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From neptundancer at gmail.com Sun Aug 26 15:17:39 2007 From: neptundancer at gmail.com (neptundancer at gmail.com) Date: Sun, 26 Aug 2007 19:17:39 -0000 Subject: lisper learning python, ... could you please comment my first python program? In-Reply-To: <1188150028.716338.64390@57g2000hsv.googlegroups.com> References: <1188143768.742884.38520@r29g2000hsg.googlegroups.com> <1188150028.716338.64390@57g2000hsv.googlegroups.com> Message-ID: <1188155859.366489.142760@r34g2000hsd.googlegroups.com> On Aug 26, 7:40 pm, Michele Simionato wrote: > On Aug 26, 5:56 pm, neptundan... at gmail.com wrote: > > > Hi, > > to extend my skills, I am learning python. I have written small > > program which computes math expression like "1+2*sin(y^10)/cos(x*y)" > > and similar, so far only + - * / ^ sin con tan sqrt are supported. But > > my program is quite inextensible, I have to change the code to add new > > functions... Could some fellow experienced pythonista give me some > > tips how to make my program shorter, and more extensible? > > I understand that you are doing this as a learning exercise. Still, I > would > recommend you to have a look at the shlex module in the standard > library > and to pyparsing. Looking at their source code should should give you > some > idea. BTW, since you are familiar with Lisp, I would recommend you > IPython > for a better interactive experience. > > Michele Simionato thanks for the tip! Now I have IPython working nicely. The shell now looks a little like Christmas tree but I think it can be reduced a bit ;) the ?var and auto completion is exactly what I was looking for! Nep From sjmachin at lexicon.net Sat Aug 11 17:34:43 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 11 Aug 2007 14:34:43 -0700 Subject: Who told str() to round my int()'s!!! In-Reply-To: <1186861056.323621.195570@e9g2000prf.googlegroups.com> References: <1186850402.192126.299840@w3g2000hsg.googlegroups.com> <1186861056.323621.195570@e9g2000prf.googlegroups.com> Message-ID: <1186868083.252032.187280@m37g2000prh.googlegroups.com> On Aug 12, 5:37 am, Zentrader wrote: > On Aug 11, 9:40 am, "Adam W." wrote: > > > After a fair amount of troubleshooting of why my lists were coming > > back a handful of digits short, and the last digit rounded off, I > > determined the str() function was to blame: > > > >>> foonum > > > 0.0071299720384678782 > > > >>> str(foonum) > > '0.00712997203847' > > > Why in the world does str() have any business rounding my numbers, and > > how do I get around this? > > If 15 digit precision is a concern, I would suggest that you us the > decimal class instead of floating points. Floating point problems on > X86 machines are well documented.http://docs.python.org/lib/module-decimal.htmlhttp://pydoc.org/2.4.1/decimal.htmlhttp://gmpy.sourceforge.net/ If you are concerned with precision of *communication*: The problem is not with floating "points" in general; floating point arithmetic can be done using a decimal representation for the numbers. The problem is not with "X86" machines in particular; just about all modern machines have floating point hardware which implements the IEEE 754 standard for binary flaoting point arithmetic. The problem is with trying to represent in one base (e.g. 10) a non-integer number that is expressed in a different base (e.g. 2) -- where the number can be represented exactly only in one base (e.g. 1./10.) or in neither (e.g. 1./3.) From almadhu at gmail.com Wed Aug 8 00:35:26 2007 From: almadhu at gmail.com (Madhu Alagu) Date: Wed, 08 Aug 2007 04:35:26 -0000 Subject: Web based Reporting tool for Python In-Reply-To: References: <1186460956.945148.162610@k79g2000hse.googlegroups.com> Message-ID: <1186547726.383996.291360@d55g2000hsg.googlegroups.com> Thanking so much for all the informations and links.I would like to use Mako Templates(www.makotemplates.org).I like to use simple and python default module... Thanks Madhu Alagu On Aug 8, 12:29 am, Jay Loden wrote: > Madhu Alagu wrote: > > I am looking template based report tools for python.It has the ability > > to deliver rich content onto the screen, to the printer or into PDF, > > HTML, XLS, CSV and XML files. > > As others have mentioned, I don't believe that all of the above is implemented > in a single package. However, Python can most definitely deal with all of the > above formats. > > For HTML templating I can highly recommend Clearsilver:http://www.clearsilver.net/it's written in C with Python (and other language) > wrappers, is very fast and is also extensible. > > For PDF: > ReportLab -http://www.reportlab.org/downloads.html > -http://www.ibm.com/developerworks/linux/library/l-sc6.html?loc=dwmain > > For XSLT: > 4Suite, libxml -http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/python-xslt > > For CSV and XML: > csv module, libxml, lxml, ElemenTree modules > > -Jay From martin at v.loewis.de Wed Aug 1 01:20:18 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 01 Aug 2007 07:20:18 +0200 Subject: Python end of file marker similar to perl's __END__ In-Reply-To: <1185940391.135261.130950@i38g2000prf.googlegroups.com> References: <1185940391.135261.130950@i38g2000prf.googlegroups.com> Message-ID: <46b01812$0$16618$9b622d9e@news.freenet.de> > In perl, I can write __END__ in a file and the perl interpreter will > ignore everything below that line. This is very handy when testing my > program. Does python have something similar? Sorry, no, it doesn't. Regards, Martin From gagsl-py2 at yahoo.com.ar Fri Aug 24 16:42:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 24 Aug 2007 17:42:23 -0300 Subject: Clipboard Monitor (tkinter,windows) References: <797532.82583.qm@web27210.mail.ukl.yahoo.com> Message-ID: En Fri, 24 Aug 2007 06:35:05 -0300, Peter Sutton escribi?: > Hi. I am an A-level student studying computer science. I have taken it > upon myself to learn python. It is now my weapon of choice. I have had a > problem trying to creating a clipboard monitor in Windows(XP,Vista) that > is linked to a tkinter GUI. I have a perfectly good code for clipboard > monitoring, but as soon as it is linked to a tkinter gui, the gui locks > when a WM.DRAWCLIPBOARD message is recieved. I am at the point of giving > up. If anyone can help or offer an alternative...that is not > polling....I would be very happy. Thanks. Peter Removing this line: self.l["text"] = "Lord be Praised" and it works fine. I'm not a Tk expert but I think it doesn't like sending another message from inside a message handler. I'd try to decouple both actions; inside OnDrawClipboard just save the clipboard contents in an instance attribute, and then invalidate the window; show the contents on response to wm_paint messages. -- Gabriel Genellina From alisonken1 at gmail.com Wed Aug 15 14:21:50 2007 From: alisonken1 at gmail.com (alisonken1) Date: Wed, 15 Aug 2007 18:21:50 -0000 Subject: Layer 2 socket connection Message-ID: <1187202110.958564.206770@l22g2000prc.googlegroups.com> Hello all - I'm looking at trying to write a python script to connect to a layer 2 bridge (no IP available). Looking at the sockets function, it's not clear if I can connect using only the mac address - it appears to want either a broadcast address or a specific IP address. Can anyone give me a clue on opening a layer 2 socket in Python? From pyth0nc0d3r at gmail.com Fri Aug 24 11:16:12 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Fri, 24 Aug 2007 10:16:12 -0500 Subject: I can't get value of entry box, Tinker Message-ID: I tried w/ my following code: from Tkinter import * master = Tk() Label(master, text="Username").grid(row=0, sticky=W) Label(master, text="Password").grid(row=1, sticky=W) e1 = Entry(master) e2 = Entry(master,show="*") def login(): global e2,e1 print e2 print e1 e3 = Button(master,text="Login",command=login).grid(row=3, sticky=W+E+S+N) e1.grid(row=0, column=1) e2.grid(row=1, column=1) master.mainloop() it outputted something like: .11972160 .11972080 What/should I, can I do? -------------- next part -------------- An HTML attachment was scrubbed... URL: From fonnesbeck at gmail.com Sun Aug 12 16:49:33 2007 From: fonnesbeck at gmail.com (Chris) Date: Sun, 12 Aug 2007 20:49:33 +0000 (UTC) Subject: Python not freeing memory (?) Message-ID: I have a Bayesian simulation package that keeps running into memory allocation problems. I have a feeling this has something to do with Python (2.5.1.1) not freeing memory. The program essentially iterates n times, each time proposing new arrays (numpy) of values that are evaluated using statistical likelihoods. All variables in the loop are re-assigned at each iteration, so there should not be a leak. Nevertheless, at approximately the same iteration every time, I run into malloc errors: Iteration 36200 at 5647.58165097 Iteration 36300 at 5664.8412981 Iteration 36400 at 5681.71009493 Python(28344,0xa000d000) malloc: *** vm_allocate(size=8421376) failed (error code=3) Python(28344,0xa000d000) malloc: *** error: can't allocate region Python(28344,0xa000d000) malloc: *** set a breakpoint in szone_error to debug Traceback (most recent call last): File "/Users/chris/EURING/detection/detection2.py", line 285, in run() File "/Users/chris/EURING/detection/detection2.py", line 268, in run results = sampler.sample(iterations=iterations, burn=burn, thin=thin) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- packages/PyMC/MCMC.py", line 3021, in sample parameter.propose(debug) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- packages/PyMC/MCMC.py", line 768, in propose if not self._sampler.test(): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- packages/PyMC/MCMC.py", line 2899, in test self() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- packages/PyMC/MCMC.py", line 2562, in __call__ return self.model() File "/Users/chris/EURING/detection/detection2.py", line 238, in model self.pd = invlogit(self.beta0 + self.beta1 * self.wind + self.beta2 * (self.cloud>0) + beta3[self.series- 1]) MemoryError Is there *any* way of getting around this? From duprez at hinet.net.au Fri Aug 24 03:03:05 2007 From: duprez at hinet.net.au (Mick Duprez) Date: Fri, 24 Aug 2007 00:03:05 -0700 Subject: Error with Simplemapi.py Message-ID: <1187938985.165186.300780@i38g2000prf.googlegroups.com> On Dec 24 2004, 4:56 pm, i... at kirbyfooty.com wrote: > I wish I new why google doesn't show nicely aligned python code when > you paste the script. > Anyways, in case this helps someone else you can download the script > fromhttp://www.kirbyfooty.com/simplemapi.py > > Ian First of all, thanks to all involved, this looks like what I need without re-inventing the wheel. Sorry to Ian if he just recieved 2 emails, my bad, I need to learn how to use this board better! I have a small problem. I get an error I don't know how to resolve, any help would be much appreciated. I'm using Python25 on winXP pro and the script from the link above. Here's the error - >>> mailtest.SendMail('noone at somewhere.net','test','test string','c:\dbs.txt') Traceback (most recent call last): File "", line 1, in mailtest.SendMail('noone at somewhere.net','test','test string','c: \dbs.txt') File "C:\Python25\mailtest.py", line 135, in SendMail cast(NULL, lpMapiRecipDesc), RecipCnt, recip, File "C:\Python25\lib\ctypes\__init__.py", line 478, in cast return _cast(obj, obj, typ) ArgumentError: argument 1: : wrong type >>> I have had a brief look at the C api for these structs and functions but I can't resolve it, it is probably something simple. The piece of code I don't understand though is this - MapiRecipDesc_A = MapiRecipDesc * len(RecipWork) #size of struct?? rda = MapiRecipDesc_A() # isn't it MapiRecipDesc as declared?? There's some new stuff going on here I don't understand. thanks for your help, Mick. From siona at chiark.greenend.org.uk Tue Aug 7 09:41:23 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 07 Aug 2007 14:41:23 +0100 (BST) Subject: is it possible to improve traceback messages ? References: <46B75F9E.5020309@mailbox.kun.nl> <1186429711.511166.140780@i38g2000prf.googlegroups.com> Message-ID: <3mp*G2HRr@news.chiark.greenend.org.uk> Zentrader wrote: >This is the "standard" way AFAIK >.try : >. some_process >.except : >. import trackback, sys >. et, ev, tb = sys.exc_info() >. while tb : >. co = tb.tb_frame.f_code >. print "Filename = " + str(co.co_filename) >. print "Error Line # = " + str(traceback.tb_lineno(tb)) >. tb = tb.tb_next >. print "error type = ", et >. print "error var name = ", ev Personally, I find: try: some_process except: import traceback traceback.print_exc() raise just as informative and much easier to write. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From BerndWill at googlemail.com Thu Aug 23 05:11:46 2007 From: BerndWill at googlemail.com (OpenPavilion) Date: Thu, 23 Aug 2007 09:11:46 -0000 Subject: Question: wxpython and 3d engine example with model load ? Message-ID: <1187860306.533382.248430@j4g2000prf.googlegroups.com> Hello, did anyone succeed in combining wxpython and a 3d engine (pyogre, crystalblend, panda3d, soya etc.) ? I would like to create an application, which uses wxpython tree, menu and grid elements and embedds a 3d view of some of the listed objects in an own detail window, so showing the object as a 3d model. I know there is PyOpenGL as well, but I need to load complete models (meshes done with cinema4d or blender) into the 3d view. So it would be very nice, if someone could post me a link to an example, where someone has successfully glued wxpython UI and a 3d engine view loading meshes into the 3d view. Regards Bernd From dborne at gmail.com Mon Aug 6 09:30:32 2007 From: dborne at gmail.com (Dave Borne) Date: Mon, 6 Aug 2007 08:30:32 -0500 Subject: Script that Navigates Page needs Javascript Functionality In-Reply-To: <1186192690.100410.260840@g12g2000prg.googlegroups.com> References: <1186192690.100410.260840@g12g2000prg.googlegroups.com> Message-ID: <6e42ec490708060630u35c72e13s93da8c2653b054a6@mail.gmail.com> > in order to view the results I need I need python to "navigate to" > this Javascript link: > javascript:__doPostBack('ctl00$cpMain$pagerTop','4') This basically > translates into "go to page 4." > I read the posts on this group, and from what I understand, the > functionality I need is with simplejson? If so, what is the syntax i > would use to execute that Javascript? > Or am I completely off base with using simplejson altogether? I've been meaning to look into this library for interfacing with Mozilla's spidermonkey javascript engine: http://wwwsearch.sourceforge.net/python-spidermonkey/ It sounds like it might do what you want, but I'm not sure how much work it would require. -Dave From arnodel at googlemail.com Fri Aug 31 16:55:22 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 31 Aug 2007 20:55:22 -0000 Subject: Is there a simple way to exit a while loop on keystroke? In-Reply-To: <1188583918.747640.300850@22g2000hsm.googlegroups.com> References: <1188578827.809840.90100@r29g2000hsg.googlegroups.com> <1188581623.588967.78050@z24g2000prh.googlegroups.com> <1188583918.747640.300850@22g2000hsm.googlegroups.com> Message-ID: <1188593722.696576.12390@y42g2000hsy.googlegroups.com> On Aug 31, 7:11 pm, gsxg wrote: > Thanks, > The curses library doesn't look to helpful to me. And yet it is. -- Arnaud From rbygscrsepda at gmail.com Sat Aug 4 00:03:38 2007 From: rbygscrsepda at gmail.com (rbygscrsepda at gmail.com) Date: Fri, 03 Aug 2007 21:03:38 -0700 Subject: Relative-importing * In-Reply-To: <46ae3894$0$19609$426a34cc@news.free.fr> References: <1185559874.299008.167010@x40g2000prg.googlegroups.com> <871weth2gg.fsf@benfinney.id.au> <46ae3894$0$19609$426a34cc@news.free.fr> Message-ID: <1186200218.666444.254200@q3g2000prf.googlegroups.com> Thanks to everybody for replying. (I apologize for the delayed response: my connection's been down for a week.) Yes, I'm importing * for a reason, a good one, I think. I have a set of modules (the number planned to reach about 400) that would be dynamically loaded by my program as needed, and they're somewhat similar to each other. I wish each of them to import * from a certain "parent" module, so that they'll receive whatever functions and variables I want all of them to share (using the parent module's __all__), which may be overrided by the "child" modules at their discretion. Sort of like class inheritance, but I'm not doing that because implementing that would be a lot more tedious and less elegant. But if this doesn't seem to be documented, and unintended...is it a bug? If so, how do I file it? Thanks again! From nicolasg at gmail.com Wed Aug 8 07:40:28 2007 From: nicolasg at gmail.com (NicolasG) Date: Wed, 08 Aug 2007 11:40:28 -0000 Subject: How to avoid reverse code engineering of a python executable Message-ID: <1186573228.419760.272240@k79g2000hse.googlegroups.com> Hi guy's, Couple of day's ago I asked for your help on how to create a single file of a python executable. Now I want to proceed a little bit further asking how can I avoid (or at least make it difficult) for some one to extract my code by using reverse code engineer techniques? I came on pyobfuscate but I would like more suggestions and guide to achieve the most possible security in this matter. Regards, Nicoals. From arne at vajhoej.dk Sun Aug 19 15:55:19 2007 From: arne at vajhoej.dk (=?ISO-8859-1?Q?Arne_Vajh=F8j?=) Date: Sun, 19 Aug 2007 15:55:19 -0400 Subject: Latest models of Gibson guitars In-Reply-To: <1187548916.909340.37420@k79g2000hse.googlegroups.com> References: <1187544898.289948.322160@22g2000hsm.googlegroups.com> <1187548916.909340.37420@k79g2000hse.googlegroups.com> Message-ID: <46c8a01f$0$90262$14726298@news.sunsite.dk> vedrandekovic at v-programs.com wrote: [some spam deleted] > This is a newsgroup of programming language Python, stop with this! Actually this was posted to a bunch of newsgroups of which one is about python. Arne From basilisk96 at gmail.com Fri Aug 24 23:26:05 2007 From: basilisk96 at gmail.com (Basilisk96) Date: Sat, 25 Aug 2007 03:26:05 -0000 Subject: py2exe/distutils: how to include a tree of files? In-Reply-To: <13cuhdr58m5one7@corp.supernews.com> References: <13cuhdr58m5one7@corp.supernews.com> Message-ID: <1188012365.509975.320500@e9g2000prf.googlegroups.com> On Aug 24, 4:55 pm, Grant Edwards wrote: > I'm packaging up a python program and need to include an entire > directory tree in the distribution. the data_files=[] option to > setup() is fine for individual files, but what do I do when I > need to include an entire directory tree? > > On a more general note, I'm having trouble finding much > documentation on py2exe at all. There's a wiki page at > py2exe.org, but it's pretty superficial. It mentions looking > at the distutils documentation for details, but I've no idea > how distutils relates to py2exe or where in the distutils > documentation to look for py2exe stuff (I don't see anything > that looks familiar in the distutils docs). > > There must be some py2exe documentation somewhere... > > [http://sourceforge.net/projects/py2exe/hasn't been updated in > 5 years, is there any reason why it's still around?] > > -- > Grant Edwards grante Yow! LBJ, LBJ, how many > at JOKES did you tell today??! > visi.com Grant, Any os.walk() loop that you can conceive which will generate a list of the kind [(dir1, pathList1), (dir2, pathList2), etc...] will work. Each subdir of your top-level tree has to be listed this way with the accompanying pathList of the subdir's files. I did this once for a 'samples' directory tree that I packaged with an app: #sample data files sampleDir = r'.\\samples' for root, dirs, files in os.walk(sampleDir): sampleList = [] if files: for filename in files: #ignore SVN dirs if ".svn" not in root: sampleList.append(os.path.join(root, filename)) if sampleList: dataFiles.append((root, sampleList)) On a side note, I've discovered that matplotlib since 0.90 or maybe earlier has specifically added a matplotlib.get_py2exe_datafiles() function to add its necessary data files in this way. Wouldn't it be nice if py2exe had something simple like that built in... Have you tried GUI2Exe? I've found its interface quite easy to use. It doesn't recurse into a dir tree (feature request?), but it makes the selection process at least half as painful. The py2exe docs leave something more to be desired. I found more tips and help via Google, ASPN, and on this list. Good luck, Basilisk96 From greg.kujawa at gmail.com Thu Aug 2 10:10:42 2007 From: greg.kujawa at gmail.com (gregarican) Date: Thu, 02 Aug 2007 14:10:42 -0000 Subject: i am new to python-Please somebody help In-Reply-To: References: <1186047103.673871.150460@z24g2000prh.googlegroups.com> Message-ID: <1186063842.827016.95030@q3g2000prf.googlegroups.com> On Aug 2, 8:51 am, Steven D'Aprano wrote: > On Thu, 02 Aug 2007 09:31:43 +0000, cool.vimalsmail wrote: > > [snip] > > You would be better off actually writing a sensible subject line instead > of grovelling. > > Subject: How to use gzip in Python? [beginner] > > Then, having written a good subject line, it might have suggested a good > search string for Google: "gzip python" > > http://www.google.com.au/search?&q=gzip+python > > The first two links found will answer your question. > > -- > Steven. This link answers my question --> http://www.google.com/search?hl=en&q=Python+list+rudeness. Honestly, I have developed in both Ruby and Python for years now and have consistently found that the Ruby community if more newbie- friendly than Python's. Your points are well-taken in how to properly post and how to do your own homework. Message correct. Delivery lacking... From theller at ctypes.org Wed Aug 15 15:57:03 2007 From: theller at ctypes.org (Thomas Heller) Date: Wed, 15 Aug 2007 21:57:03 +0200 Subject: Move files/directories to Recycle Bin using standard Python libs In-Reply-To: <1187199757.774573.48940@q4g2000prc.googlegroups.com> References: <1187199757.774573.48940@q4g2000prc.googlegroups.com> Message-ID: kyosohma at gmail.com schrieb: > On Aug 15, 11:39 am, Kevin D. Smith wrote: >> I would like to move files and directories to the Recycle Bin on >> Windows from Python. I have found some older articles describing how >> to do this, but they require additional packages to be installed. I'm >> working on a plugin for an existing project and only have the standard >> library to work with. Is there a way to use the Recycle Bin using >> standard Python? >> >> -- >> Kevin D. Smith > > Sounds like a Windows only thing to me, so you'll probably have to use > the win32 package regardless. See the following links: > > http://mail.python.org/pipermail/python-list/2004-October/287638.html > http://tgolden.sc.sabren.com/python/win32_how_do_i/copy-a-file.html Or access the win32 api directly with ctypes (included in Python 2.5). Thomas From petri.savolainen at iki.fi Mon Aug 20 04:46:04 2007 From: petri.savolainen at iki.fi (Petri Savolainen) Date: Mon, 20 Aug 2007 11:46:04 +0300 Subject: imaplib & Received: header(s)??? In-Reply-To: <13cgurcg663m003@corp.supernews.com> References: <13cgurcg663m003@corp.supernews.com> Message-ID: Donn Cave wrote: > | I need to get at the Received-for header to figure out at which address > | we received an email. We subscribe to a number of mailing lists using > | per-mailing-list addresses, and often, To: field contains something else > | than our address, thus the need for Received-for. > | > > "Anything recent"? If you're getting IMAP advice from comp.lang.python, > I think it's fair to say you will need to be more resourceful. The > RFC for IMAP4rev1 should be helpful. I don't know the IMAP to get a > single header field, but my guess is that your error is there. Can you > retrieve other fields that way? Does the one you're looking for appear > in the data if you get the whole header, for example with 'RFC822.HEADER'? > It certainly does in my Python IMAP client, and this would have at least > helped you refine your question. Thanks Donn, I had already checked everything relevant, including what you suggested. The only examples that I found including the Received header utilized the now-obsoleted rfc822 library in python from many years and versions back. Thus nothing recent. However, you mentioning "RFC822.HEADER" working for you prompted me to try another mail server... to my surprise, everything worked. It appears some imap servers do not allow programmatic fetching of Received: information. Should've done this check sooner :-( Thanks, Petri From wgwigw at gmail.com Sat Aug 4 03:49:47 2007 From: wgwigw at gmail.com (momobear) Date: Sat, 04 Aug 2007 00:49:47 -0700 Subject: Help: GIS In-Reply-To: <1186112804.718290.207580@z24g2000prh.googlegroups.com> References: <1186112804.718290.207580@z24g2000prh.googlegroups.com> Message-ID: <1186213787.212326.80320@i38g2000prf.googlegroups.com> On Aug 3, 11:46 am, zxo102 wrote: > Hi, > I am new in GIS area and need your suggestions for where I can > start from. I have a python based web application with a database. > Now I would like to add a GIS map into my application. When a user > clicks a certain area in the GIS map, it can grab the data from the > database via my python based application. Do I have to use MapServer > or Grass or some other backends for this purpose? > Thanks a lot. > > Ouyang another link, http://code.djangoproject.com/wiki/GeoDjango, talk about many python tools about GIS, hope help to u. From creechm at gmail.com Wed Aug 22 12:06:46 2007 From: creechm at gmail.com (Mark) Date: Wed, 22 Aug 2007 16:06:46 -0000 Subject: Eval and raw string ?? Message-ID: <1187798806.029598.264740@q3g2000prf.googlegroups.com> Eval() doesn't seem to recognize the r'string' format. Is there a way around this. Example: If I input: ---------> eval("r'C:\tklll\ndfd\bll'") I get the output: Traceback (most recent call last): File "", line 1, in eval("r'C:\tklll\ndfd\bll'") File "", line 1 r'C: klll ^ SyntaxError: EOL while scanning single-quoted string The same principle applies for exec. Thanks in advance, Mark From michele.simionato at gmail.com Fri Aug 31 01:26:20 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 31 Aug 2007 05:26:20 -0000 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188523096.427717.87380@x35g2000prf.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> <1188430887.481586.106760@l22g2000prc.googlegroups.com> <1188504811.019632.186580@x35g2000prf.googlegroups.com> <46d75116$0$401$426a74cc@news.free.fr> <1188517050.174081.265900@x40g2000prg.googlegroups.com> <46d75d33$0$6231$426a34cc@news.free.fr> <1188520454.996940.293030@m37g2000prh.googlegroups.com> <46d76790$0$410$426a74cc@news.free.fr> <1188523096.427717.87380@x35g2000prf.googlegroups.com> Message-ID: <1188537980.926587.201770@e9g2000prf.googlegroups.com> On Aug 31, 3:18 am, Russ wrote: > For the record, the guy I > criticized > made ridiculous assertions about DBC. And that would be me? Oh my! LOL! This is not nearly as fun as the guy who explained to Steve Holden how Python works, but still ... ;) > If you are upset about my criticism of one of your colleagues, please > tell him to quite making > outrageous assertions about something he obviously knows little about. For the record I read the design by contract book by Meyer years ago (the first edition) and I could not stomach it. The paper you mentioned is even worse. Programmers asserting that a given metodology can give 100% reliable software are incompetents or liars or both. Period. Of course there are methodologies which are better than others (for instance automatic tests are better than manual tests) and one should try various approaches on the field. However, IMNSHO, nowadays design by contract has been superseded by unit tests and it makes little sense to use it. Once you have automatic tests and once you make liberal use of assert statements in your code, you should not feel the need for more than that. You may think differently of course, but you should know that I am a ferocious opponent of heavyweight approaches, huge frameworks, and all that. Most people in the Python community are. This is why I think dBC will never enter in the core, and it would be extremely little used even as a third party library (BTW, it has already happened). Michele Simionato From nospam.themindstorm at gmail.com Fri Aug 3 14:45:14 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Fri, 3 Aug 2007 18:45:14 +0000 (UTC) Subject: File Handling & TRY/EXCEPT References: <33119.3366124809$1186129744@news.gmane.org> <13677.732498809$1186148538@news.gmane.org> Message-ID: "Robert Rawlins - Think Blue" wrote in news:13677.732498809$1186148538 at news.gmane.org: > Thanks for your ideas guys, > > I'm unfortunately tied to 2.4 so don't have the full try except > status, but I'm now working with the following code: > > def addApp(self, event): > try: > logfile = > open('/pblue/new/Logs/Application.csv','a') > > now = datetime.datetime.now() > logstring = '%s,%s \n' % (event, str(now)) > > try: > logfile.write(logstring) > finally: > logfile.close() > except: > self.addApp(event) > > I'm trying to slowly debug my app and get rid of all the memory leaks, > but its pain staking work, any help you can offer on that stuff would > be a god send, I'm a little reluctant about posting all my app code on > the lists as I'd like to keep some of it private. > > How does that new version look? A little tidier? > > Thanks guys, > Now, you are sure the file is always close. What I don't think is correct is to retry to re-write the event (cause if opening the file crashed ones there are very good chances that it will throw the 2nd time). ./alex -- .w( the_mindstorm )p. From tim at tdw.net Mon Aug 20 18:13:46 2007 From: tim at tdw.net (Tim Williams) Date: Mon, 20 Aug 2007 23:13:46 +0100 Subject: reading a line in file In-Reply-To: References: <93066C069973ED448DC2BCEA9C44A7383BE2B2@efmailx> <2dc0c81b0708201029k5909d919vcf0deebae74a79c7@mail.gmail.com> <93066C069973ED448DC2BCEA9C44A7383BE2B4@efmailx> <2dc0c81b0708201207p7f83f2e0l6de15fd70be252a5@mail.gmail.com> Message-ID: <9afea2ac0708201513u426cead0q6c2805e001d25bd1@mail.gmail.com> On 20/08/07, Brian McCann wrote: > > Shawn, Tim ,Jay > > many thanks, > > It looks like there are many ways this problem can be approached > > either by using regex or a tokens > > Tim I'm not familiar with your solution, but will learn about that method > also Hi Brian, > buildNum = open('input.txt').read().split('build.number=')[1].split()[0] Try this on its own: print open('input.txt').read().split('build.number=') See what is at the very beginning of the 2nd list item :) My example just splits the whole file at "build.number=", so you know the data you require is at the beginning of the 2nd list item returned from the slice [ie: a_list[1]. You also know that data is followed by a newline, so it will be the first item in the returned list [ie: b_list[0] when you split a_list[1]. No need to iterate each line individually looking for a match and then process the matching line to get at the data. You can just go straight to the data you require. If your requirement is for multiple items from a single file then another method would be required. :) From ghirai at ghirai.com Sun Aug 12 15:09:11 2007 From: ghirai at ghirai.com (Ghirai) Date: Sun, 12 Aug 2007 22:09:11 +0300 Subject: Drawing a graph Message-ID: <20070812220911.fd2948e1.ghirai@ghirai.com> Hello list, I need to draw a graph, 2 axes, 2D, nothing fancy. One of the axes is time, the other one is a series of integers. I don't care much about the output format. Are there any specialized libraries for this, or should i use PIL? Thanks. -- Regards, Ghirai. From mail at microcorp.co.za Fri Aug 3 02:26:30 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 3 Aug 2007 08:26:30 +0200 Subject: Memory Leak with Tkinter Canvas (Python 2.5 Win32) References: <1186068851.011344.322980@i13g2000prf.googlegroups.com> Message-ID: <00f901c7d59b$95c1c620$03000080@hendrik> "frikk" wrote: > 1. ....... Am I somehow leaving > objects laying around that aren't being deleted? Is create_rectangle > not the appropriate function to use?) Try calling the canvas's delete method with the old rectangle before making a new one. - Hendrik From sbassi at clubdelarazon.org Wed Aug 15 13:11:41 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Wed, 15 Aug 2007 14:11:41 -0300 Subject: Combinatorial of elements in Python? In-Reply-To: <46C32D6E.7070804@isy.liu.se> References: <9e2f512b0708142203m782b0e10s817fb4d061ba0e46@mail.gmail.com> <46C2F538.8000900@isy.liu.se> <9e2f512b0708150651g7a9834cdm2db874d84804e362@mail.gmail.com> <46C32D6E.7070804@isy.liu.se> Message-ID: <9e2f512b0708151011mc86ede7o68a92515c4cf3017@mail.gmail.com> On 8/15/07, Mikael Olofsson wrote: > What is unclear here is in what order the keys should be visited. The > following assumes that the keys should be considered in alphanumeric order. Yes, my fault. The orden should be given by a string, like: DCDBA Using this dictionay. A={'A':['1','2'],'B':['4','5'],'C':['6','7','8'],'D':['9']} Should return: '96941' '97941' '97942' '96942' '98941' '98942' '96951' '97951' '97952' '96952' '98951' '98952' -- Sebasti?n Bassi (???????) Diplomado en Ciencia y Tecnolog?a. GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D From carsten at uniqsys.com Sat Aug 4 12:27:23 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 04 Aug 2007 12:27:23 -0400 Subject: Problems with headers in email.message In-Reply-To: <9afea2ac0708040910q5de8b667n3c7b70818d920d29@mail.gmail.com> References: <9afea2ac0708040910q5de8b667n3c7b70818d920d29@mail.gmail.com> Message-ID: <1186244843.3385.18.camel@dot.uniqsys.com> On Sat, 2007-08-04 at 17:10 +0100, Tim Williams wrote: > Your script (as posted) works fine for me. > > I did need to change one import line to: from email.Message import > Message (note the capitalization) The modules inside the email package appear to have changed from capitalized names to lowercase names for Python 2.5. -- Carsten Haese http://informixdb.sourceforge.net From nadiapetrova20 at gmail.com Mon Aug 6 15:35:23 2007 From: nadiapetrova20 at gmail.com (Nadi Petrova) Date: Mon, 06 Aug 2007 12:35:23 -0700 Subject: =?utf-8?B?4peY4peY4pa6U2F0ZWxsaXRlIFRWIG9uIHlvdXIgUEMgLSBXYXRjaCBpdCBGUkVFIE5vd+KXhOKXmOKXmA==?= Message-ID: <1186428923.518917.246660@g4g2000hsf.googlegroups.com> Watch Satellite TV On Your Computer Without Paying Monthly Fees... ? Save 1000's of $$$ over many years on cable and satellite bills. ? Watch all your favorite shows on your Computer from anywhere in the World! ? Plus Get FREE Unlimited Downloads Movies, MP3s Music, etc !!! ? INSTANT DOWNLOAD Now!! For More Details: http://etvonpc.coz.in From hadronquark at googlemail.com Wed Aug 1 10:37:39 2007 From: hadronquark at googlemail.com (Hadron) Date: Wed, 01 Aug 2007 16:37:39 +0200 Subject: Emacs + python Message-ID: Could anyone put me on the right track to developing Python with emacs please : modes to consider, debugging etc hopefully all within emacs. Any help and shared experiences much appreciated. From manasd at gmail.com Sat Aug 11 12:43:19 2007 From: manasd at gmail.com (MD) Date: Sat, 11 Aug 2007 09:43:19 -0700 Subject: How to change a PyObject passed to the C extension Message-ID: <1186850599.738739.195410@b79g2000hse.googlegroups.com> Hi, I have a Python C extension which is passed a PyObject containing an integer value. Is it possible to change this same PyObject so that now the integer is of a different value? Thanks and Regards, -MD From bignose+hates-spam at benfinney.id.au Tue Aug 28 01:14:08 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 28 Aug 2007 15:14:08 +1000 Subject: "Try:" which only encompasses head of compound statement References: <1188250535.607963.42540@22g2000hsm.googlegroups.com> <87wsvgfszm.fsf@benfinney.id.au> <13d7898odj2g19b@corp.supernews.com> Message-ID: <87fy24fdgf.fsf@benfinney.id.au> Scott David Daniels writes: > Actually, this will be followed by some foolishness because > (1) [the "print" format argument was wrong] > and > (2) [the code attempts to loop over the failed input file anyway] You're right. Shame on me for posting untested code snippets, Thanks for the catch. -- \ "There was a point to this story, but it has temporarily | `\ escaped the chronicler's mind." -- Douglas Adams | _o__) | Ben Finney From deets at nospam.web.de Sat Aug 18 18:42:50 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 19 Aug 2007 00:42:50 +0200 Subject: Parser Generator? In-Reply-To: References: Message-ID: <5ipavkF3qq00oU1@mid.uni-berlin.de> Jack schrieb: > Hi all, I need to do syntax parsing of simple naturual languages, > for example, "weather of London" or "what is the time", simple > things like these, with Unicode support in the syntax. > > In Java, there are JavaCC, Antlr, etc. I wonder what people use > in Python? Antlr also has Python support but I'm not sure how good > it is. Comments/hints are welcome. There are several options. I personally like spark.py, the most common answer is pyparsing, and don't forget to check out NLTK, the natural language toolkit. Diez From johnmasters at oxtedonline.net Mon Aug 20 16:02:44 2007 From: johnmasters at oxtedonline.net (John K Masters) Date: Mon, 20 Aug 2007 21:02:44 +0100 Subject: Python equivalent of Perl's $/ In-Reply-To: <1187637588.073514.202930@x40g2000prg.googlegroups.com> References: <1187637588.073514.202930@x40g2000prg.googlegroups.com> Message-ID: <20070820200244.GB4424@spookie1.spookiegate> On 19:19 Mon 20 Aug , attn.steven.kuo at gmail.com wrote: > > import StringIO > > text = """\ > To mimic Perl's input record separator in > Python, you can use a generator. > And a substring test. > Perhaps something like the following > is what you wanted. > """ > > mockfile = StringIO.StringIO(text) > > def genrecords(mockfile, sep=".\n"): > buffer = "" > while True: > while sep in buffer: > idx = buffer.find(sep) + len(sep) > yield buffer[:idx] > buffer = buffer[idx:] > rl = mockfile.readline() > if rl == "": > break > else: > buffer = '%s%s' % (buffer, rl) > yield buffer > raise StopIteration > > for record in genrecords(mockfile): > print "READ:", record > > > -- > Hope this helps, > Steven Thanks, this also looks like a good way to go but ATM beyond my level of Python knowledge. I've not reached the generator chapter yet but I'll flag the message and return later. Regards, John -- War is God's way of teaching Americans geography Ambrose Bierce (1842 - 1914) From steve at holdenweb.com Wed Aug 15 19:38:56 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 15 Aug 2007 19:38:56 -0400 Subject: Module imports during object instantiation In-Reply-To: <1187206998.252482.300780@a39g2000hsc.googlegroups.com> References: <4c3vo4-u7k.ln1@learner.hq.netapp.com> <46c16ec9$0$405$426a34cc@news.free.fr> <1187205375.871837.254400@r34g2000hsd.googlegroups.com> <1187206998.252482.300780@a39g2000hsc.googlegroups.com> Message-ID: Ritesh Raj Sarraf wrote: > On Aug 16, 12:16 am, Ritesh Raj Sarraf wrote: >> On Aug 15, 11:42 pm, Neil Cerutti wrote: >> [...] > Oops!!! Looks like I completely missed this. It _did_ print the error > message. > Apologies to all for not keeping a close eye on the error message. > Quite. It was obvious to many readers that you were fooling yourself with a false hypothesis. The probability of something so fundamental being wrong is vanishingly small. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From aleax at mac.com Mon Aug 6 22:46:44 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 6 Aug 2007 19:46:44 -0700 Subject: boolean operations on sets References: <1186409631.147290.323400@22g2000hsm.googlegroups.com> <5hotveF3l5gmkU1@mid.uni-berlin.de> Message-ID: <1i2fw2i.w6f2eb19rgfjpN%aleax@mac.com> Michael J. Fromberger wrote: ... > Also, it is a common behaviour in many programming languages for logical > connectives to both short-circuit and yield their values, so I'd argue > that most programmers are proabably accustomed to it. The && and || > operators of C and its descendants also behave in this manner, as do the Untrue, alas...: brain:~ alex$ cat a.c #include int main() { printf("%d\n", 23 && 45); return 0; } brain:~ alex$ gcc a.c brain:~ alex$ ./a.out 1 In C, && and || _do_ "short circuit", BUT they always return 0 or 1, *NOT* "yield their values" (interpreted as "return the false or true value of either operand", as in Python). Alex From kyosohma at gmail.com Fri Aug 10 09:02:24 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 10 Aug 2007 06:02:24 -0700 Subject: Python MAPI In-Reply-To: <1186740316.816775.130500@m37g2000prh.googlegroups.com> References: <1184954229.222401.213380@k79g2000hse.googlegroups.com> <1184957337.367674.104760@i13g2000prf.googlegroups.com> <1184959701.447824.70890@q75g2000hsh.googlegroups.com> <1184960314.426690.238270@z28g2000prd.googlegroups.com> <1184965933.212060.214800@m3g2000hsh.googlegroups.com> <1185134453.934837.325310@w3g2000hsg.googlegroups.com> <1185196021.512126.93490@r34g2000hsd.googlegroups.com> <1186740316.816775.130500@m37g2000prh.googlegroups.com> Message-ID: <1186750944.787750.77010@i38g2000prf.googlegroups.com> On Aug 10, 5:05 am, vasudevram wrote: > On Jul 23, 6:07 pm, kyoso... at gmail.com wrote: > > >Well, I ran Process Monitor with some filters enabled to only watch > > Thunderbird and MS Word. Unfortunately, that didn't give me any of the > registry edits, so I disabled my filters and ran it without. Now I > have a log file with 28,000 entries. It's amazing to see all the stuff > that happens in just a few moments, but how am I supposed to parse > this mess? > > Explorer.exe and outlook express do thousands of the registry calls > and the paths they manipulate vary wildly. Oh well, I'll be off the > clock in about 15 minutes so it can wait until Monday. > > Thanks for your help. I'll post if I figure out anything...hopefully > you'll do the same. > > --- > > Sorry for not replying earlier ... I searched this list for the topic > (Python MAPI) a few times but couldn't find it - not sure why - maybe > Google Groups's indexing gets messed up sometimes ... > > Yes, so many entries would be a problem to parse manually ... > > That's why I suggested using a grep for Windows - or, preferably, an > egrep - which is a more powerful version of grep; e.g. basic grep only > allows you to use one regexp at a time - while egrep allows you to use > extended regular expressions, such as "pattern1|pattern2", also > "patt(e|u)rn(1|2)" which looks in parallel for pattern1, patturn1, > pattern2 and patturn2 - I used a made-up example where the spelling of > pattern could be wrong, but it works for any other cases of > alternative patterns and subpatterns as well. Not sure if there is any > egrep for Windows - try Googling. If not, and the problem is important > enough, you might want to install Cygwin (its a big download, so first > check if it _does_ have egrep in it). > > Vasudev There are some programs that do grep for Windows. I'll mess with them. Mike From thijs.braem at gmail.com Fri Aug 31 18:55:16 2007 From: thijs.braem at gmail.com (thijs.braem at gmail.com) Date: Fri, 31 Aug 2007 15:55:16 -0700 Subject: Python Unicode to String conversion Message-ID: <1188600916.528901.189680@d55g2000hsg.googlegroups.com> Hi everyone, I'm having quite some troubles trying to convert Unicode to String (for use in psycopg, which apparently doesn't know how to cope with unicode strings). The error I keep having is something like this: ERREUR: S?quence d'octets invalide pour le codage ?UTF8? : 0xe02063 (sorry, locale is french, it means "byte sequence invalid for encoding <>", the value is probably an e with one of the french accents) I've found lots of stuff about this googling the error, but I don't seem to be able to find a "works always"-function just to convert a unicode variable back to string... If someone could find me a solution, that'd really be a lifesaver. I've been losing hours and hours over this one :s thijs From bj_666 at gmx.net Fri Aug 24 09:11:56 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Aug 2007 13:11:56 GMT Subject: any problem with py's RC? References: Message-ID: <5j83osF3t3hraU4@mid.uni-berlin.de> On Fri, 24 Aug 2007 19:44:37 +0800, Yan Zhu wrote: > Here is 3 PYs, we found there is a big memory wasting, specially the program > c.py, we found the memory will increase very soon. > any body knows why? any RC's problem? thanks You are creating reference cycles and instantiate many in very short time. Objects with cyclic dependencies must be detected by the garbage collector which takes some time. Usually this is not a problem because generating lots of cycles in a tight and endless ``while``-loop is not *that* common. ;-) You may take a look into the `weakref` module to avoid the cycles. Ciao, Marc 'BlackJack' Rintsch From sullivanz.pku at gmail.com Wed Aug 8 02:23:40 2007 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: Wed, 08 Aug 2007 06:23:40 -0000 Subject: Seek the one billionth line in a file containing 3 billion lines. Message-ID: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> I have a huge log file which contains 3,453,299,000 lines with different lengths. It is not possible to calculate the absolute position of the beginning of the one billionth line. Are there efficient way to seek to the beginning of that line in python? This program: for i in range(1000000000): f.readline() is absolutely every slow.... Thank you so much for help. From petri.savolainen at iki.fi Sun Aug 19 04:26:21 2007 From: petri.savolainen at iki.fi (Petri Savolainen) Date: Sun, 19 Aug 2007 11:26:21 +0300 Subject: imaplib & Received: header(s)??? Message-ID: Hello, Is there a way to get at the "Received" header(s) or is there something in imaplib or imap server implementations that hides these? If not, what IMAP FETCH command should be used? I've used for example "BODY[HEADER.FIELDS (RECEIVED)]" and it always returns empty ("\r\n"). Despite the Received - header existing, as demonstrated by taking a look at message sources via desktop email clients. I need to get at the Received-for header to figure out at which address we received an email. We subscribe to a number of mailing lists using per-mailing-list addresses, and often, To: field contains something else than our address, thus the need for Received-for. Any help would be much appreciated - this is baffling me and I've not found anything recent that would help. Thanks, Petri From ldo at geek-central.gen.new_zealand Mon Aug 27 18:57:26 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 28 Aug 2007 10:57:26 +1200 Subject: "Try:" which only encompasses head of compound statement References: <1188250535.607963.42540@22g2000hsm.googlegroups.com> Message-ID: In message <1188250535.607963.42540 at 22g2000hsm.googlegroups.com>, Jameson.Quinn at gmail.com wrote: > try: > for line in open(myFileName): > count += 1 > except IOError: > print "Can't open myfile" > > (I know, this is bad, I never close the file, but its just for > illustration). No, that's fine. The file object returned by "open" is refcounted, so when the last reference to it disappears, it is closed. From aahz at pythoncraft.com Fri Aug 24 09:17:48 2007 From: aahz at pythoncraft.com (Aahz) Date: 24 Aug 2007 06:17:48 -0700 Subject: Regular expression use References: Message-ID: In article , Nick Maclaren wrote: > >For reasons that I won't explain, as they are too complicated >and not terribly relevant, I am interested in discovering what >people actually use regular expressions for. Not the subject >domain, but the construction of the regular expressions. Your question as phrased makes no sense to me. For that matter, it isn't even a question. ;-) Side note: please don't cross-post between c.l.py and c.l.perl.* -- the group cultures are different and it's too easy to start flamewars. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From wildemar at freakmail.de Wed Aug 22 18:13:56 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Thu, 23 Aug 2007 00:13:56 +0200 Subject: introspection and functions In-Reply-To: <1187819949.515982.15450@r23g2000prd.googlegroups.com> References: <1187819949.515982.15450@r23g2000prd.googlegroups.com> Message-ID: <46CCB524.3060608@freakmail.de> yagyala wrote: > Hi. I would like to be able to tell, at run time, how many parameters > a function requires. Ideally I would like to be able to tell which are > optional as well. I've tried looking at the functions attributes, but > haven't found one that helps in this. How can I do this? > I've never used it before, but there is the "inspect" module. . That any good? /W From richardjones at optushome.com.au Sat Aug 4 03:40:23 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Sat, 04 Aug 2007 17:40:23 +1000 Subject: Registration is open for the 5th Python game challenge! Message-ID: <46b42d65$0$14986$afc38c87@news.optusnet.com.au> The fifth PyWeek is only a month away. Come along and join the fun: write a video game in a week! There's some really interesting new libraries that have popped up recently. Have a gander on the pyweek message board for more info. REGISTRATION IS OPEN Visit the PyWeek website for more information: http://pyweek.org/ THE PYWEEK CHALLENGE: - Invites all Python programmers to write a game in one week from scratch either as an individual or in a team, - Is intended to be challenging and fun, - Will hopefully increase the public body of python game tools, code and expertise, - Will let a lot of people actually finish a game, and - May inspire new projects (with ready made teams!) Entries must be developed during the challenge, and must incorporate some theme decided at the start of the challenge. The rules for the challenge are at: http://media.pyweek.org/static/rules.html Richard -- Visit the PyWeek website: http://pyweek.org/ From jeffober at gmail.com Mon Aug 20 15:39:28 2007 From: jeffober at gmail.com (Jeff) Date: Mon, 20 Aug 2007 19:39:28 -0000 Subject: 'REPL' style IDE In-Reply-To: <1187633038.373751.244700@i38g2000prf.googlegroups.com> References: <1187632249.748945.158910@i13g2000prf.googlegroups.com> <1187633038.373751.244700@i38g2000prf.googlegroups.com> Message-ID: <1187638768.783508.327010@r34g2000hsd.googlegroups.com> python-mode in Emacs. From james-netnews at and.org Tue Aug 7 12:05:16 2007 From: james-netnews at and.org (James Antill) Date: Tue, 07 Aug 2007 16:05:16 -0000 Subject: All leading tabs or all leading spaces - why isn't that enforced? References: Message-ID: On Tue, 07 Aug 2007 02:53:18 +0000, John Nagle wrote: > One can argue over tab vs. space indentation, but mixing the two is just > wrong. Why not have CPython report an error if a file has both leading > tabs and leading spaces? I know that was proposed at some point, but I > don't think it ever went in. That would catch a common error introduced > during maintenance. While I agree it should be default, you can enable extra checking with -tt. Eg. % jhexdump /tmp/abcd.py 0x00000000: 2321 202F 7573 722F 6269 6E2F 7079 7468 #! /usr/bin/pyth 0x00000010: 6F6E 202D 7474 0A0A 6966 2054 7275 653A on -tt..if True: 0x00000020: 0A09 7072 696E 7420 2261 220A 2020 2020 ..print "a". 0x00000030: 2020 2020 7072 696E 7420 2262 220A print "b". % /tmp/abcd.py File "/tmp/abcd.py", line 5 print "b" ^ TabError: inconsistent use of tabs and spaces in indentation % python /tmp/abcd.py a b ...note that this doesn't require all spaces or all tabs, just that their usage has to be consistent. -- James Antill -- james at and.org C String APIs use too much memory? ustr: length, ref count, size and read-only/fixed. Ave. 44% overhead over strdup(), for 0-20B strings http://www.and.org/ustr/ From kaldrenon at gmail.com Tue Aug 21 08:52:38 2007 From: kaldrenon at gmail.com (kaldrenon) Date: Tue, 21 Aug 2007 12:52:38 -0000 Subject: Latest models of Gibson guitars In-Reply-To: <1187657694.106990.266830@z24g2000prh.googlegroups.com> References: <1187544898.289948.322160@22g2000hsm.googlegroups.com> <1187548916.909340.37420@k79g2000hse.googlegroups.com> <1187579396.285862.186860@e9g2000prf.googlegroups.com> <9K6dnY8HnIUNHlTbnZ2dnUVZ_gGdnZ2d@comcast.com> <1187657694.106990.266830@z24g2000prh.googlegroups.com> Message-ID: <1187700758.572516.186610@57g2000hsv.googlegroups.com> On Aug 20, 8:54 pm, Twisted wrote: > If the message then > says something absurd, like "this is a newsgroup about Python" when > I'm reading it in cljp, well, what do you expect? :P I think most would expect you to go, "WTF?" but then, like a rational person, click the helpful little "More options" link that GG provides (I'm assuming you use GG to read as well as to post, forgive me if I'm wrong) and double-check before harassing someone because you jumped to conclusions. > though nothing in the headers would indicate this. Newsgroups: comp.lang.java.programmer, microsoft.public.dotnet.framework.aspnet, comp.lang.python, rec.photo.digital, alt.home.repair From: mobile... at gmail.com Date: Sun, 19 Aug 2007 17:34:58 -0000 Local: Sun, Aug 19 2007 1:34 pm Subject: Latest models of Gibson guitars That's the header GG shows. Preeeetty clear. Just a tip for future reference - all's fair if you weren't aware of this feature of GG's interface. From nstjelja at gmail.com Thu Aug 2 02:51:50 2007 From: nstjelja at gmail.com (Nikola Stjelja) Date: Thu, 2 Aug 2007 08:51:50 +0200 Subject: Time object? In-Reply-To: <496954360708010918n22e525f8y1f453714a7d1155c@mail.gmail.com> References: <496954360708010918n22e525f8y1f453714a7d1155c@mail.gmail.com> Message-ID: <2d24984a0708012351w399eb70ev7d2e968725602f73@mail.gmail.com> On 8/1/07, Robert Dailey wrote: > > Hi, > > I'm well aware of the datetime module, however it is really inconsistent > and useless to me. In order to do any arithmetic on time objects, I have to > use the 'timedelta' class, which doesn't even allow me to do all the math I > want to do. > > For example, I want to do "1 / timeobj", where timeobj might represent a > time in the format of "00:00:00.000000". Do I have to code my own class > for this, or is there some other third party library out there that will > allow me to do this? > > Thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list > Convert each date you use to a timestamp, make all your calculations using those timestamps, and then when you need a date back just convert the desired timestamp to date time format of your choosing. -- Please visit this site and play my RPG! http://www.1km1kt.net/rpg/Marinci.php -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE.THIS.cybersource.com.au Sat Aug 4 00:56:19 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 04 Aug 2007 14:56:19 +1000 Subject: How to pass a reference to the current module References: <7xtzrg3vof.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 03 Aug 2007 21:06:23 -0700, James Stroud wrote: > Its very close. However, there is the possibiltiy that main.py and > UserDefined1.py are the same module. In such a case I'm guessing that I > need to resort to the gymnastics of frame inspection I mentioned > earlier. I suggest you're falling for the anti-pattern of "Big Design Up Front", and are overly complicating your system "just in case it's useful". Why not just _insist_ that main.py and UserDefined1.py must be different modules? You're the application developer, you're allowed to do that. > The problem is when this combination of possibilities exists: > > 1. main.py is named without the .py (e.g. `main`) as would be > the convention for "programs"), and is not a true python > module as a result--perhaps python has a mechanism for > importing such files? I don't believe it does. > 2. foo is defined in `main` Maybe you should just prohibit that? Do you really want to allow users to call arbitrary code in your main application at arbitrary times and places? Maybe you do. Okay, it's your gun and your foot. But in any case, it shouldn't matter. main is the program running -- it has to be, because you can't import it from another program -- so globals()['foo'] will work. > Possibility two (even when it is a properly named module) sets the stage > for a circular import, but I believe in python this is not entirely > worrisome. However, the combination above makes it difficult to pass a > reference to the `main` namespace without some sort of introspection. That's what globals() is for. > Ideally, I would prefer to not require the user to provide some mapping > as it detracts from the convenience of the API. For example: > > from UserDefined1 import some_function > def foo(): [etc.] > def doit(): [etc.] > mapping = { > 'foo' : foo, > 'doit' : doit, > 'some_function' : some_function > } > > The idea would be that the above mapping would be specified in the > configuration file: > > [foo] > param1 = float > param2 = 4 > > [option1] > __module__ = 'UserDefined1' > __function__ = 'doit' I'm not sure why you need the quotation marks around the module and function names. What else could UserDefined1 be, other than a string? -- Steven. From jjl at pobox.com Wed Aug 1 15:38:23 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 01 Aug 2007 19:38:23 GMT Subject: UK Ordnance survey coordinates and Geocoding anyone ? References: Message-ID: <87ps2759lc.fsf@pobox.com> Ken Starks writes: [...] > http://www.magic.gov.uk/ [snip rest of URL...] Cool, I had no idea we still had a department of magic! I'll keep my eyes peeled for Mr. Norrell... John From kyosohma at gmail.com Thu Aug 2 15:27:27 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 02 Aug 2007 19:27:27 -0000 Subject: problems playing with dates from any month. In-Reply-To: References: Message-ID: <1186082847.821344.171560@e16g2000pri.googlegroups.com> On Aug 2, 1:16 pm, "krishnakant Mane" wrote: > On 02/08/07, Ian Clark wrote: > > > > >http://docs.python.org/lib/node85.html > > I looked there even before. > but could not figure out what the code did. > I know in that variable called s there was a string in a valid date format. > but when datetime.strptime was used, I did not understand the place > where a date object say d was created. > I would expect some thing like d = and the function. but I did not fine that. > only reference was the datetime module and the documentation is not as good. > another question I am getting is that where is the list of all > formatting characters. like for example Y is 4 digit year M is month > MM is month in 2 digits etc. > I am trying to locate a list of all these denoters. > can you provide me the place? > > > Then it's just: > > > if date_obj.day == 5: > > print 'It's the fifth day of the month' > > this was much better than the documentation, thanks, > regards, > Krishnakant. The various flags for the strftime() are here, near the middle of the page: http://docs.python.org/lib/module-time.html Not sure why the docs don't point to this page when talking about the datetime's almost identical method. Mike From markacy at gmail.com Sat Aug 4 09:53:43 2007 From: markacy at gmail.com (markacy) Date: Sat, 04 Aug 2007 13:53:43 -0000 Subject: the one python book In-Reply-To: References: Message-ID: <1186235623.585135.42630@l70g2000hse.googlegroups.com> On 4 Sie, 15:23, "dhr" wrote: > newbie question: > > Is there a 'K&R" type of Python book? The book that you'd better have on > your shelf if you are going into Python? There are actually two of them: "How to Think Like a Computer Scientist: Learning with Python" by Allen B. Downey, Jeffrey Elkner and Chris Meyers http://www.ibiblio.org/obp/thinkCSpy/ and "Dive Into Python" by Mark Pilgrim http://diveintopython.org/toc/index.html Hope this helps :-) Cheers and good luck, Marek From max at alcyone.com Sun Aug 12 22:28:19 2007 From: max at alcyone.com (Erik Max Francis) Date: Sun, 12 Aug 2007 19:28:19 -0700 Subject: Fatest standard way to sum bytes (and their squares)? In-Reply-To: References: Message-ID: Peter Otten wrote: > from itertools import imap > > def summit_array(data=data, lookup=lookup): > a = array.array("B") > a.fromstring(data) > return sum(a), sum(imap(lookup.__getitem__, a)) > > $ python -m timeit -s'from summit import summit_array as summit' 'summit()' > 100 loops, best of 3: 9.15 msec per loop > > I think I'll stop here... Yes, this was the fastest approach of all the alternatives I tried. Plugging the algorithm in the tool, it makes it about twice as fast as the generator-sum method I was using before, and about _five_ time as fast as a naive for loop. The use of an array is particularly clever; I never would have thought of that. Thanks to everyone for their ideas. Amusingly I posted it late last night (well, this morning I guess), not expecting much, at least until the next day, but got a factor of two speedup within half an hour! -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis It is morale that wins the victory. -- Gen. George C. Marshall From mkent at acm.org Sun Aug 5 23:54:09 2007 From: mkent at acm.org (Mike Kent) Date: Sun, 05 Aug 2007 23:54:09 -0400 Subject: (Re)announcing APL 2007 Message-ID: <5hnkb3F3hus4jU1@mid.individual.net> APL 2007 conference on Array Programming co-located with OOPSLA 2007 Sponsor: ACM SIGAPL Where: Montreal When: October 21 (tutorials) October 22/23 (main conference program) Keynote Guy Steele speaker: Sun Microsystems Laboratories Links: Info: http://www.sigapl.org/apl2007.html Registration: http://www.regmaster.com/conf/OOP07/oop07.pdf OOPSLA: http://www.OOPSLA.org/oopsla2007 From laelahaellallah5 at gmail.com Sun Aug 12 21:17:03 2007 From: laelahaellallah5 at gmail.com (laelahaellallah5 at gmail.com) Date: Sun, 12 Aug 2007 18:17:03 -0700 Subject: The Truth Message-ID: <1186967823.072801.260580@d55g2000hsg.googlegroups.com> Explore & discover & be convinced that ISLAM is the truth! ... Please Visit: http://www.beconvinced.com From llasram at gmail.com Fri Aug 17 17:48:19 2007 From: llasram at gmail.com (Marshall T. Vandegrift) Date: Fri, 17 Aug 2007 17:48:19 -0400 Subject: Encryption and hashing References: <1187377630.017794.36510@50g2000hsm.googlegroups.com> Message-ID: <87wsvtn87w.fsf@seneca.iss.local> Kless writes: > For who knows any of criptography I comment that you can use > algorithms as secure as Rijndael, Twofish, or Serpent with the CFB > cipher mode. And for hash you can use RIPEMD, SHA-2 or WHIRLPOOL. PyCrypto does includes the AES version of Rijndael as Crypto.Cipher.AES and the 256-bit version of SHA-2 as Crypto.Hash.SHA256. -Marshall From tleeuwenburg at gmail.com Fri Aug 31 11:30:16 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: Fri, 31 Aug 2007 15:30:16 -0000 Subject: Setting a read-only attribute In-Reply-To: <1188548061.663133.273160@q5g2000prf.googlegroups.com> References: <1188509700.915517.178440@z24g2000prh.googlegroups.com> <1188548061.663133.273160@q5g2000prf.googlegroups.com> Message-ID: <1188574216.529447.140390@i38g2000prf.googlegroups.com> On Aug 31, 6:14 pm, Alexandre Badez wrote: > On Aug 30, 11:35 pm, "tleeuwenb... at gmail.com" > wrote: > > > I have an object and wish to set an attribute on it which, > > unfortunately for me, is read-only. > > > How can I go about this? > > > Cheers. > > -T > > Could you show the object you want to set his attribute? > Until that, it's difficult to answer to you. > > PS: If the attribut is on read only, their must a good reason for > that ;) Hi all, Thanks for all the responses. What I'm trying to do is kludge around something. sys.settrace takes a method whose arguments are (frame, event, arg). I want to have a tracer class which can be instantiated and listen in on these trace calls. Another way to go about it *might* be to have a module-level list of registered Tracer objects which a module-level trace method informs of events. It would probably be easier. In fact, I'll go do that. *That said*, I still think it makes sense to be able to have objects register with sys.settrace. So what I did then was declare a static method with the same pattern expected by sys.settrace. I then want to use something like __dict__ or __setattr__ to give that method a reference to the owning object. And this is what I'm trying to do -- declare a static method, then "un- static it" by adding a reference to the callable object... Here's some code: ------------------------------------------------------------ import sys class Tracer: ''' Instantiate this in order to access program trace information. ''' def _getcallback(self): @staticmethod def callback(frame, event, arg): print "tracing ...", tracerReference #print "line ", frame.f_lineno, frame.f_locals return callback def startTrace(self): callback = self._getcallback() callback.__dict__['tracerReference'] = self sys.settrace(callback) def foo(dict): for i in range(2): pass if __name__ == "__main__": t = Tracer() t.startTrace() foo({1 : 5}) From semanticist at gmail.com Fri Aug 31 02:10:45 2007 From: semanticist at gmail.com (Miles) Date: Fri, 31 Aug 2007 02:10:45 -0400 Subject: fcntl problems In-Reply-To: <1188512377.441241.107900@q4g2000prc.googlegroups.com> References: <1188512377.441241.107900@q4g2000prc.googlegroups.com> Message-ID: On 8/30/07, mhearne808 wrote: > I'm having a number of problems with the fcntl module. Read this first: http://linux.die.net/man/2/flock > First of all, if I try this: > file = open("counter.txt","w+") > fcntl.flock(file.fileno(), fcntl.LOCK_NB) > > I get this: > --------------------------------------------------------------------------- > Traceback (most recent call > last) > /Users/mhearne/src/python/ in () > : [Errno 9] Bad file descriptor That should be: >>> fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) > Proceeding forward with the locked file, let's say I do the above in > Python interactive Process A. Then in python interactive Process B, I > repeat the "open" function on the same file with the same > permissions. Then, in each process, I write some text to the file > using the write() method. After closing the file in both processes, > the only text I see in the file is from Process B! This is due to two issues: caching and file position. When you open the file in both processes as 'w+', they are both positioned at the *current* EOF, but from that point on the offset is not externally influenced. The correct sequence of events should be: - open file in mode w+ - obtain exclusive lock - f.seek(0, 2) # (to end of file) - write to file - f.flush() # or f.close() - release lock > Is this my lack of understanding, or have I discovered a bug? If you find yourself asking this question, it's too often the former :) -Miles From franz.steinhaeusler at gmx.at Sun Aug 5 08:44:55 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhäusler) Date: Sun, 05 Aug 2007 14:44:55 +0200 Subject: Best programs written completly in Python References: Message-ID: <0ahbb3hpgici70roicu47fpnob21bteh5c@4ax.com> On Sun, 05 Aug 2007 12:14:38 +0200, Franz Steinh?usler wrote: >Hello NG, > >wWhat are the best programs in your opinion, written entirly >in pyhton, divided into categories like: Many thanks, The restriction, I want, is to comply the programs written in pygame, pygtk, wxPython, tkinter or console programs. There are really "high sophisticated" programs, if you don't mind my naming it so, as: XPN newsreader, Boa Constructor, many pygame programs, gtkrawgallery, cornice graphics viewer, ... I'm only interested to have a list, or even help to extend an existing one. On wxPython, there also exist such a list: http://wiki.wxpython.org/wxPythonPit_Apps -- Franz Steinhaeusler From paddy3118 at googlemail.com Fri Aug 17 14:54:07 2007 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 17 Aug 2007 18:54:07 -0000 Subject: Naming dictionaries recursively In-Reply-To: <1187361791.979162.46330@22g2000hsm.googlegroups.com> References: <1187354296.177606.273300@22g2000hsm.googlegroups.com> <5ilkebF3oltfoU2@mid.uni-berlin.de> <1187361791.979162.46330@22g2000hsm.googlegroups.com> Message-ID: <1187376847.158312.234560@w3g2000hsg.googlegroups.com> On Aug 17, 3:43 pm, TYR wrote: > > So the tougher problem seems to be parsing those lines. That is not a > > valid Python dictionary unless the names `Bob`, `Humboldt`, `red`, and > > `predatory` are not already defined. So you can't just ``eval`` it. > > In what way? {'key': val}, right? > > Anyway, I can always change the format they go into the file in. If you control the file format then you could create a valid python list of dictionaries as the intermediate file format. Something like: data = [ {'name' : 'Bob', 'species' : 'Humboldt', 'colour' : 'red', 'habits' : 'predatory'}, { ... }, ... } You can then name the file with a .py ending and import it as a list of dictionaries that you can then process to form a dict of dicts: datadict = dict( (data2name(d), d) for d in modulename.data ) - Paddy. From bdesth.quelquechose at free.quelquepart.fr Wed Aug 1 16:38:31 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 01 Aug 2007 22:38:31 +0200 Subject: access the name of my method inside it In-Reply-To: <1186000119_6209@sp12lax.superfeed.net> References: <1185959202.302467.276080@x35g2000prf.googlegroups.com> <5hb1ebF3inuf2U6@mid.uni-berlin.de> <1185973639.234450.305690@g12g2000prg.googlegroups.com> <1186000119_6209@sp12lax.superfeed.net> Message-ID: <46b0ef7b$0$8216$426a34cc@news.free.fr> Cousin Stanley a ?crit : >>>>def my_method(): >>>> >>>> # do something >>> >>>> # how do I get the name of this method >>>> # which is my_method here? >>> >>>Why do you need this? There are ways but those >>>are not really good for production code. >>> >> >>I am going to use this in Django. I am trying to implement >>a permission here, where in the database store the methods >>that the user are allowed to execute. >> >>for example if the method is def create_event() : >>the method will look for create_event in the database >>to see if it allow to be execute. > > > james .... > > Perhaps a simple-minded hard-coded solution > might work .... > > def permission_check( name ) : > > permission = DB.permission_check( name ) > > if not permission : > > print 'No Execute Permission for %s ' % name > > sys.exit( -1 ) An exception would be better here. > def my_method() : > > permission_check( "my_method" ) > > .... > May I suggest ? class Unauthorized(Exception): pass def check_permission(permission): if not DB.check_permission(permission): raise Unauthorized(permission) def requires_perm(func): def with_check(*args, **kw): check_permission(func.__name__) return func(*args, **kw) return with_check @requires_perm def my_method(): # do something useful here From aleax at mac.com Thu Aug 30 22:26:58 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 30 Aug 2007 19:26:58 -0700 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188495863.242815.236900@o80g2000hse.googlegroups.com> Message-ID: <1i3ob5k.dm3jmoqx1z68N%aleax@mac.com> wrote: ... > In my case of have done os.listdir() on two directories. I want to see > what files are in directory A that are not in directory B. So why would you care about WHERE, in the listdir of B, are to be found the files that are in A but not B?! You should call .index only if you CARE about the position. def inAnotB(A, B): inA = os.listdir(A) inBs = set(os.listdir(B)) return [f for f in inA if f not in inBs] is the "one obvious way to do it" (the set(...) is just a simple and powerful optimization -- checking membership in a set is roughly O(1), while checking membership in a list of N items is O(N)...). Alex From slippy.lane at googlemail.com Sat Aug 4 11:38:23 2007 From: slippy.lane at googlemail.com (Slippy) Date: Sat, 04 Aug 2007 15:38:23 -0000 Subject: Problems with headers in email.message Message-ID: <1186241903.509471.26460@d55g2000hsg.googlegroups.com> Hi, python newbie, struggling to learn here. I'm trying to write a simple program which posts messages to my google group (via email). I'm using smtplib, email and email.message to build and send a message, but all the header attributes are appearing in the message body, so my messages are arriving with loads of junk in the body, no subject line and only the skinniest of headers. I know I'm doing something wrong, but I don't know what... Here's a simplification of what I'm doing....essentially, I've taken from what I've learned at http://codeidol.com/python/python3/Client-Side-Scripting/pymail-A-Console-Based-Email-Client/ -------------Snip Here-------------Snip Here-------------Snip Here------------- import smtplib, email from email.message import Message m = Message( ) m['From'] = 'Slippy ' m['To'] = 'mygroup at googlegroups.com' m['Subject'] = 'A Test Message' m.set_payload('This is a test email. Please ignore') s = smtplib.SMTP('smtp.myemail.com') failed = s.sendmail('user at myemail.com','mygroup at googlegroups.com',str(m)) if failed: print 'Message sending failed.' else: print 'Message sent.' print 'Bye.' -------------Snip Here-------------Snip Here-------------Snip Here------------- Now, I get all the right responses, and the message sends ok. I go and check my inbox, and the message is there, but the From, To and Subject lines I created (as well as a preceding blank line and a "From nobody" line) are in the message body, followed by the body text. How do I assign values to the header? I'd appreciate any help anyone can give me with this. From SMERSH009X at gmail.com Sun Aug 5 05:06:54 2007 From: SMERSH009X at gmail.com (SMERSH009) Date: Sun, 05 Aug 2007 09:06:54 -0000 Subject: Formatting Results so that They Can be Nicely Imported into a Spreadsheet. In-Reply-To: <1186284359.668342.5880@d30g2000prg.googlegroups.com> References: <1186270555.514649.311280@d30g2000prg.googlegroups.com> <1186278638.931477.39760@z24g2000prh.googlegroups.com> <1186284359.668342.5880@d30g2000prg.googlegroups.com> Message-ID: <1186304814.129279.207100@j4g2000prf.googlegroups.com> On Aug 4, 8:25 pm, "mensana... at aol.com" wrote: > On Aug 4, 9:21?pm, "Jim Langston" wrote: > > > > > wrote in message > > >news:1186278638.931477.39760 at z24g2000prh.googlegroups.com... > > > > On Aug 4, 6:35?pm, SMERSH009 wrote: > > >> Hi All. > > >> Let's say I have some badly formatted text called doc: > > > >> doc= > > >> """ > > >> friendid > > >> Female > > > >> 23 years old > > > >> Los Gatos > > > >> United States > > >> friendid > > >> Male > > > >> 24 years old > > > >> San Francisco, California > > > >> United States > > >> """ > > > >> How would I get these results to be displayed in a format similar to: > > >> friendid;Female;23 years old;Los Gatos;United States > > >> friendid;Male; 24 years old;San Francisco, California;United States > > > >> The latter is a lot easier to organize and can be quickly imported > > >> into Excel's column format. > > > >> Thanks Much, > > >> Sam > > > > d = doc.split('\n') > > > > f = [i.split() for i in d if i] > > > > g = [' '.join(i) for i in f] > > > > rec = [] > > > temprec = [] > > > for i in g: > > > if i: > > > if i == 'friendid': > > > rec.append(temprec) > > > temprec = [i] > > > else: > > > temprec.append(i) > > > rec.append(temprec) > > > > output = [';'.join(i) for i in rec if i] > > > > for i in output: print i > > > > ## friendid;Female;23 years old;Los Gatos;United States > > > ## friendid;Male;24 years old;San Francisco, California;United States > > > also, I would suggest you use CSV format. > > Well, the OP asked for a specific format. One is not > always at liberty to change it. > > > CSV stands for "Comma Seperated > > Variable" and Excel can load such a sheet directly. > > And Excel can load the shown format directly also, > just specify the delimiter. > > > > > Instead of seperating using ; seperate using , Of course, this provides a > > problem when there is a , in a string. > > Which explains the popularity of using tabs as delimiters. > The data deliverable specification I use at work > uses the pipe character | which never appears as data > in this particular application. > > > Resolution is to quote the string. > > Which makes the file bigger and isn't necessary > when tabs and pipes are used as delimiters. > > > Being such, you can just go ahead and quote all strings. So you would want > > the output to be: > > > "friendid","Female","23 years old","Los Gatos","United States" > > "friendid","Male","24 years old","San Francisco, California","United States" > > Which I would do if I had a specification that > demanded it or was making files for others. For my > own use, I wouldn't bother as it's unnecessary work. > > > > > Numbers should not be quoted if you wish to treat them as numeric and not > > text. > > A good reason not to use quotes at all. Besides which, > Excel can handle that also. Thanks for all your posts guys. mensanator's was the most helpful, and I only ended up needing to use a few lines from that code. The only question that remains for me--and this is just for my knowledge-- what does the "if i" mean in this code snippet? f = [i.split() for i in d if i] How is it helpful to leave a dangling "if i"? Why not just f = [i.split() for i in d]? And yes John, this was indeed a "homework question." It was for my daughter's preschool. You are going to help her ace her beginner Python class! (No, this was not a homework question). From aleax at mac.com Fri Aug 10 11:56:22 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 10 Aug 2007 08:56:22 -0700 Subject: Ipc mechanisms and designs. References: <1186760055.658942.116300@x40g2000prg.googlegroups.com> Message-ID: <1i2mgp3.18efp2c12w20wpN%aleax@mac.com> king kikapu wrote: > Hi, > > inspired of the topic "The Future of Python Threading", i started to > realize that the only way to utilize the power of multiple cores using > Python, is spawn processes and "communicate" with them. > > If we have the scenario: > > 1. Windows (mainly) development > 2. Processes are running in the same machine > 3. We just want to "pass" info from one process to another. Info may > be simple data types or user defined Python objects. > > what is the best solution (besides sockets) that someone can implement > so to have 2 actually processes that interchanged data between them ? > I looked at Pyro and it looks really good but i wanted to experiment > with a simpler solution. Check out Alex From steven.bethard at gmail.com Sun Aug 12 22:56:16 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 12 Aug 2007 20:56:16 -0600 Subject: A dumb question about a class In-Reply-To: References: <1186965321.741540.108820@k79g2000hse.googlegroups.com> <1186966648.867722.185770@19g2000hsx.googlegroups.com> Message-ID: Steven Bethard wrote: > Dustan wrote: >> On Aug 12, 7:35 pm, Dustan wrote: >>> On Aug 12, 5:09 pm, Steven Bethard wrote: >>> >>>> def iter_primes(): >>>> # an iterator of all numbers between 2 and +infinity >>>> numbers = itertools.count(2) >>>> # generate primes forever >>>> while True: >>>> # get the first number from the iterator (always a prime) >>>> prime = numbers.next() >>>> yield prime >>>> # remove all numbers from the (infinite) iterator that are >>>> # divisible by the prime we just generated >>>> numbers = itertools.ifilter(prime.__rmod__, numbers) >>> This is kind of OT (from the thread), but in this iter_primes >>> function, numbers is becoming an ifilter of an ifilter of an ifilter >>> of an ifilter of an ifilter of an ifilter of... Is that really at all >>> efficient for larger numbers (millions or billions, or even bigger)? >> >> To word my question better: >> >> How does this algorithm compare and contrast to maintaining a >> dictionary or set and iterating through those structures to find out >> if a number is divisible? All of those algorithms I've described are >> O(n^2), if I'm not mistaken, but as far as memory-efficiency and the >> likes, how do they compare/contrast? > > I don't have the answer off hand, but if anyone wants to report some > timeit results or memory consumption here, I'd be interested. Ok, I played around with it myself. Here are the two implementations I tested:: def iter_primes_recursive(): # an iterator of all numbers between 2 and +infinity numbers = itertools.count(2) # generate primes forever while True: # get the first number from the iterator (always a prime) prime = numbers.next() yield prime # remove all numbers from the (infinite) iterator that are # divisible by the prime we just generated numbers = itertools.ifilter(prime.__rmod__, numbers) def iter_primes_mapping(): # mapping from composite number to first prime that revealed # that number as a composite composite_to_factor_map = {} # generate primes forever for i in itertools.count(2): # find a factor of the number factor = composite_to_factor_map.pop(i, None) # if no factor is found, the number is prime if factor is None: yield i composite_to_factor_map[i * i] = i # add the factor to the number until we find a new # composite number else: composite = i + factor while composite in composite_to_factor_map: composite += factor composite_to_factor_map[composite] = factor And here are some timeit results:: $ python -m timeit -s "from script import iter_primes_recursive as iter_primes" "for i in iter_primes():" " if i >= 100:" " break" 10000 loops, best of 3: 102 usec per loop $ python -m timeit -s "from script import iter_primes_mapping as iter_primes" "for i in iter_primes():" " if i >= 100:" " break" 10000 loops, best of 3: 75.2 usec per loop $ python -m timeit -s "from script import iter_primes_recursive as iter_primes" "for i in iter_primes():" " if i >= 10000:" " break" 10 loops, best of 3: 111 msec per loop $ python -m timeit -s "from script import iter_primes_mapping as iter_primes" "for i in iter_primes():" " if i >= 10000:" " break" 100 loops, best of 3: 8.4 msec per loop So, somewhat unsurprisingly, the non-recursive version is much faster for larger primes. (Someone should check that both my implementations are right -- I only did a couple of spot checks on the output.) STeVe From Brian.McCann at viziant.net Thu Aug 23 23:27:33 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Thu, 23 Aug 2007 23:27:33 -0400 Subject: creating a tar file with python References: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> <93066C069973ED448DC2BCEA9C44A7383BE2ED@efmailx> <46CE4D3D.7020106@holdenweb.com> Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE2EE@efmailx> Steve, I ran the code as you suggested, didn't work, tried variations of it didn't work, If you don't know the answer don't pretend you do! Apology not accepted, please don't wake up! Future correspondence on any python questions from you go to trash. May your pillow not have pity on your head! --Brian ________________________________ From: Steve Holden [mailto:steve at holdenweb.com] Sent: Thu 8/23/2007 11:15 PM To: Brian McCann Cc: python-list at python.org Subject: Re: creating a tar file with python Brian McCann wrote: > > Hi, > > I'm now getting this error > any ideas? > Thanks, > Brian > > > Traceback (most recent call last): > File "./tarup.py", line 25, in ? > tar = tarfile.open("test.xml","sample.tar.gz", 'w:gz') > File "/usr/lib64/python2.4/tarfile.py", line 929, in open > raise ValueError, "undiscernible mode" > ValueError: undiscernible mode > ############################################################ > #!/usr/bin/python > import string > import os > import sys > import time > import errno > import shutil > import tarfile > > tar = tarfile.open(test.xml","sample.tar.gz", 'w:gz') > Well, my first idea is that you took the time to think beyond the mistake exhibited in your first response. But since a soft mattress is currently looking about a hundred times more attractive than actually trying to debug your code I am sorry to tell you I am going to punt on this one and trust that some other c.l.py netizen will take pity on you and probably help you with less crabby comments than me. Good luck! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From zyzhu2000 at gmail.com Sat Aug 18 21:43:43 2007 From: zyzhu2000 at gmail.com (beginner) Date: Sun, 19 Aug 2007 01:43:43 -0000 Subject: "constructor" or initialization function for module In-Reply-To: References: <1187484559.935316.125050@j4g2000prf.googlegroups.com> Message-ID: <1187487823.316772.234780@j4g2000prf.googlegroups.com> On Aug 18, 8:25 pm, Steve Holden wrote: > beginner wrote: > > Hi Everyone, > > > An extended module (.pyd) written in C have an init function that is > > called when the module is imported. Does anyone know if there is a way > > to provide an init function for a module written in python? > > The body of a Python module is executed the first time it is imported > (that's how the functions and classes get defined: class and def > statements are executable), so just put your initialization code inline. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- I see. That works. From martin at v.loewis.de Sun Aug 5 13:50:56 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 05 Aug 2007 19:50:56 +0200 Subject: Semantics of thread.error In-Reply-To: <1186333306.599950.139160@e16g2000pri.googlegroups.com> References: <1186333306.599950.139160@e16g2000pri.googlegroups.com> Message-ID: <46b60e00$0$18044$9b622d9e@news.freenet.de> Paul Miller schrieb: > In the language documentation, all that is said about thread.error is > that it's raised "on thread-specific errors." Is there anywhere a > list of conditions which will cause thread.error to be raised? I don't think so. However, it is fairly easy to extract such a list from the source: "grep ThreadError */*.c" reveals these causes PyErr_SetString(ThreadError, "release unlocked lock"); PyErr_SetString(ThreadError, "can't allocate lock"); PyErr_SetString(ThreadError, "can't start new thread"); PyErr_SetString(ThreadError, "no current thread ident"); PyErr_SetString(ThreadError, "setting stack size not supported"); Regards, Martin From lasses_weil at klapptsowieso.net Fri Aug 31 18:52:23 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sat, 01 Sep 2007 00:52:23 +0200 Subject: So what exactly is a complex number? In-Reply-To: <451mq4-les.ln1@ozzie.tundraware.com> References: <451mq4-les.ln1@ozzie.tundraware.com> Message-ID: <46d89ba9$0$30380$9b4e6d93@newsspool4.arcor-online.net> Tim Daneliuk wrote: > A number by itself is called a "scalar". For example, when I say, > "I have 23 apples", the "23" is a scalar that just represents an > amount in this case. > > One of the most common uses for Complex Numbers is in what are > called "vectors". In a vector, you have both an amount and > a *direction*. For example, I can say, "I threw 23 apples in the air > at a 45 degree angle". Complex Numbers let us encode both > the magnitude (23) and the direction (45 degrees) as a "number". > 1. Thats the most creative use for complex numbers I've ever seen. Or put differently: That's not what you would normally use complex numbers for. 2. Just to confuse the issue: While complex numbers can be represented as 2-dimensional vectors, they are usually considered scalars as well (since they form a field just as real numbers do). > There are actually two ways to represent Complex Numbers. > One is called the "rectangular" form, the other the "polar" > form, but both do the same thing - they encode a vector. > Again, that is just one way to interpret them. Complex numbers are not vectors (at least no moe than real numbers are). /W From silfheed at gmail.com Tue Aug 21 00:54:45 2007 From: silfheed at gmail.com (Silfheed) Date: Tue, 21 Aug 2007 04:54:45 -0000 Subject: Adjusting the names of custom exceptions (since raising strings is deprecated) Message-ID: <1187672085.263963.157470@z24g2000prh.googlegroups.com> Heyas So this probably highlights my lack of understanding of how naming works in python, but I'm currently using FailUnlessRaises in a unit test and raising exceptions with a string exception. It's working pretty well, except that I get the deprecation warning that raising a string exception is going to go away. So my question is, how do I mangle the name of my exception class enough that it doesnt stick the name of the module before the name of the exception? Namely I'd like to get the following *** Traceback (most recent call last): File "", line 1, in ? MyError: 'oops!' instead of *** Traceback (most recent call last): File "", line 1, in ? __main__.MyError: 'oops!' (or even test_thingie.MyError as is usually the case). Creating a class in a separate file and then doing *** from module import MyError raise MyError still gives *** Traceback (most recent call last): File "", line 1, in module.MyError Anyway, any help appreciated. From nicoblodow at gmx.net Fri Aug 17 17:54:08 2007 From: nicoblodow at gmx.net (Nico Blodow) Date: Fri, 17 Aug 2007 21:54:08 +0000 Subject: Problems with threading in embedded Python Message-ID: <46C61900.2030500@gmx.net> Hi all, I hope this hasn't been brought up before, but if it did i missed it, so bear with me please :) anyway, i'm trying to embed Python into a C program. A sample python syript i want to run is as follows: ---SNIP--- import time import threading go_on = 1 t = 0 def ProcessMessage(): print "... ProcessMessage" def Main(): global go_on print "... Main" while go_on: ProcessMessage () print "... ... ", time.sleep (0.2) def Setup(): global t print "... Setup" t = threading.Thread (None, Main) t.start () # t.join (0) # print t.isAlive() def Shutdown(): global go_on, t go_on = 0 t.join () print "... Shutdown" ---SNIP--- I call "Setup" from C, which should create a new thread which should enter the loop in Main. well, it doesn't :) It prints "... Setup" and does nothing. when i call Shutdown from C, it prints "... Main" , followed by "... Shutdown", and exits... So it seems to me the python interpreter wants to run the seperate thread, but doesn't get time from the scheduler (is that the thing about 100 opcodes?) How can i handle this problem? Do I need to wrap all the Py_Stuff() into its own thread? do i need artificial python code that only serves the purpose of piling up enough opcodes so that the Main() thread gets eventually called? I hope you can help me, if you need more code (f.ex. the C-code ), i will post more :) (basically I modified the run_func.cc file from the docs, added PyEval_InitThreads() and monkeyed around with GIL and Acquire/ReleaseLock, but so far i had no luck :) Cheers, Nico From nyamatongwe+thunder at gmail.com Tue Aug 21 08:52:31 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 21 Aug 2007 12:52:31 GMT Subject: File Read Cache - How to purge? In-Reply-To: <1187669203.698637.81990@i38g2000prf.googlegroups.com> References: <1187669203.698637.81990@i38g2000prf.googlegroups.com> Message-ID: Signal: > So it seems the file is being cached, however on my system only ~2MB > of additional memory is used when the program is run. This 2MB of > memory is released when the script exits. You are not measuring the memory used by the cache. This may help: http://www.microsoft.com/technet/archive/ntwrkstn/reskit/07cache.mspx?mfr=true > 2. Is there anyway to somehow to take advantage of this "caching" by > initializing it without reading through the entire file first? The Win32 API provides FILE_FLAG_SEQUENTIAL_SCAN (don't know how effective this will be for your application) although its probably simpler to use a read-ahead thread or overlapped I/O. > 3. If the answer to #2 is No, then is there a way to purge this > "cache" in order to get a more accurate result in my routine? That is > without having to read another large file first? http://www.microsoft.com/technet/sysinternals/FileAndDisk/CacheSet.mspx Neil From newsgroups at debain.org Sun Aug 19 09:15:33 2007 From: newsgroups at debain.org (Samuel) Date: Sun, 19 Aug 2007 13:15:33 +0000 (UTC) Subject: Hot subject: a good python editor and/or IDE? References: Message-ID: On Sun, 19 Aug 2007 13:08:35 +0000, Samuel wrote: > $ sudo apt-get install vim I just realized, this should be $ sudo apt-get install vim-python or $ sudo apt-get install vim-full -Samuel From rdm at rcblue.com Tue Aug 14 08:05:07 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 14 Aug 2007 05:05:07 -0700 Subject: Opinions about this new Python book? Message-ID: <20070814120526.3196A1E4013@bag.python.org> I'd appreciate opinions about this new Python book. Title: Python Power!: The Comprehensive Guide Author: Matt Telles Publisher: Course Technology Pub. Date: Jul 27, 2007 Edition: 1st edition Binding: Paperback Pages: 508 ISBN: 1598631586 List Price: 34.99 USD The book on the publisher's website: And at BestBookDeal.com: < http://www.bestbookdeal.com/book/compare/1598631586> Thanks, Dick Moores From kw at codebykevin.com Fri Aug 24 14:11:29 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Fri, 24 Aug 2007 14:11:29 -0400 Subject: GUI and distrubution In-Reply-To: <1187974418.175783.50860@i38g2000prf.googlegroups.com> References: <1187974418.175783.50860@i38g2000prf.googlegroups.com> Message-ID: <92ab7$46cf1f51$4275d90a$11544@FUSE.NET> anders wrote: > So how is the preferably way to distribute software written i Python > My next question is witch is the best GUI to use, also consider > the delivery question above. > These are two of the most-often-asked questions on this list (along with "What's the best Python IDE?"). Search the list archives via Google, or do a general Google search. Some helpful terms to get you started include pyinstaller, py2exe, py2app, Tkinter, wxPython, PyQt, and pyGTK. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From hniksic at xemacs.org Tue Aug 21 15:56:18 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 21 Aug 2007 21:56:18 +0200 Subject: How to optimise this code? References: <46CB3635.7050705@biotec.tu-dresden.de> Message-ID: <87mywk1x25.fsf@mulj.homelinux.net> Christof Winter writes: > To get rid of the if statements, replace __init__ function with: > > def __init__(self, tc): > functionToCall = eval("self.testCase%s" % tc) Or functionToCall = getattr(self, "testCase" + tc) eval can introduce unwanted side effects. From carsten at uniqsys.com Thu Aug 30 14:34:42 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 30 Aug 2007 14:34:42 -0400 Subject: list index() In-Reply-To: <1188498073.997168.282420@q5g2000prf.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <46d674c2$0$417$426a34cc@news.free.fr> <1188496588.750629.208100@g4g2000hsf.googlegroups.com> <1188498073.997168.282420@q5g2000prf.googlegroups.com> Message-ID: <1188498882.3468.66.camel@dot.uniqsys.com> On Thu, 2007-08-30 at 11:21 -0700, zzbbaadd at aol.com wrote: > I wish they were not > getting rid of dict.has_key() in Python 3, which I prefer to IN. That wish will only come true if you maintain your own fork of Python 3. has_key() will go away, period. It has been made obsolete by "in", which is faster and more concise. -- Carsten Haese http://informixdb.sourceforge.net From aahz at pythoncraft.com Fri Aug 10 12:12:53 2007 From: aahz at pythoncraft.com (Aahz) Date: 10 Aug 2007 09:12:53 -0700 Subject: The Future of Python Threading References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <5i329uF3muir4U1@mid.individual.net> Message-ID: In article , Nick Craig-Wood wrote: > >This would of course make C extensions more complicated... It's even worse than that. One of the goals for Python is to make it easy to call into random libraries, and there are still plenty around that aren't thread-safe (not even talking about thread-hot). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "And if that makes me an elitist...I couldn't be happier." --JMS From duncan.booth at invalid.invalid Tue Aug 7 09:54:21 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Aug 2007 13:54:21 GMT Subject: Importing * From a Package References: <20070806143253.4947.1097304571.divmod.quotient.19513@ohm> Message-ID: "Patrick Doyle" wrote: > Why does Python include the submodules that were explicitly loaded by > previous imports? Does it go out of it's way to do so? If so, why? > What purpose does it serve? Or, is it a natural fallout of the manner > in which imports are processed? If so, could somebody guide my > intuition as to why this would be such a natural fallout? > It is a natural fallout of the manner in which imports are processed. When you explicitly load a submodule a reference to the submodule is stored in the parent module. When you do 'from module import *' and the imported module doesn't define __all__, you create a reference in the current module to everything referenced by the imported module (except for variables beginning with '_'). Python makes no distinction at all between the objects named in the imported module: they all get imported, i.e. assigned into the current scope no matter how they got there. If you use your example: >>> import SDRGen >>> dir(SDRGen) ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] >>> from SDRGen.TFGenerator import * >>> dir(SDRGen) ['TFGenerator', '__builtins__', '__doc__', '__file__', '__name__', '__path__'] >>> The line 'from SDRGen.TFGenerator import *' always creates the name TFGenerator in the SDRGen module (and it will create the SDRGen module if it has to). A subsequent 'from SDRGen import *' is simply doing the equivalent of: for name in dir(SDRGen): if not name.startswith('_'): setattr(current_module, getattr(SDRGen, name)) except of course the variables name and current_module don't exist. From mhearne808 at gmail.com Wed Aug 8 12:46:25 2007 From: mhearne808 at gmail.com (mhearne808[insert-at-sign-here]gmail[insert-dot-here]com) Date: Wed, 08 Aug 2007 16:46:25 -0000 Subject: accessing parts of large files with File.seek() Message-ID: <1186591585.175399.139850@x40g2000prg.googlegroups.com> I'm having a problem with the File object's seek() method. Specifically, I cannot use it to seek to a location in a binary file that is greater than 2^31 (2147483648). This seems unnecessarily limiting, as it is common these days to have files larger than 2 GB. Is there some LargeFile object out there that I can use to read my file, which is approximately 3.3 GB in size? Python version (freshly built from source this morning): Python 2.5.1 (r251:54863, Aug 8 2007, 09:23:05) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Thanks, Mike From bdesth.quelquechose at free.quelquepart.fr Thu Aug 2 10:33:13 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 02 Aug 2007 16:33:13 +0200 Subject: __call__ considered harmful or indispensable? In-Reply-To: <7xfy31smuq.fsf@ruckus.brouhaha.com> References: <7xfy31smuq.fsf@ruckus.brouhaha.com> Message-ID: <46b2428b$0$19638$426a74cc@news.free.fr> Paul Rubin a ?crit : > skip at pobox.com writes: > >>In this particular case it was clearly unnecessary and just obfuscated the >>code. I'm wondering, are there some general cases where __call__ methods of >>a user-defined class are simply indispensable? > > > I don't know about "indispensable" but __call__ is convenient sometimes > and I do use it. I've wished that modules supported call, so I could > say > > import foo > x = foo(3) > > instead of having to say x=foo.foo(3) or something like that. from foo import foo x = foo(3) Or did I miss the point ??? From lasses_weil at klapptsowieso.net Fri Aug 31 09:18:00 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Fri, 31 Aug 2007 15:18:00 +0200 Subject: Let's Unite Against Jews and Mongrels! In-Reply-To: <023fd3dhtmb5j0hl2uvdc4f25d5s6vogkp@4ax.com> References: <1188198797.772672.60840@r29g2000hsg.googlegroups.com> <1188300284.507909.126770@57g2000hsv.googlegroups.com> <46D40BFE.2020301@comcast.net> <023fd3dhtmb5j0hl2uvdc4f25d5s6vogkp@4ax.com> Message-ID: <46d81508$0$4536$9b4e6d93@newsspool3.arcor-online.net> Barry OGrady wrote: > He has some wrong ideas. The blacks are victims of the jews as well. > And Jews are the victims of "Christians". And Christians are the victims of "Muslims". Anybody not a victim of anyone else, please raise your hand! /W From gagsl-py2 at yahoo.com.ar Wed Aug 1 23:38:28 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 02 Aug 2007 00:38:28 -0300 Subject: frequency analysis of a DB column References: <1186021313.413443.184060@i38g2000prf.googlegroups.com> Message-ID: En Wed, 01 Aug 2007 23:21:53 -0300, goldtech escribi?: > In Python 2.1 are there any tools to take a column from a DB and do a > frequency analysis - a breakdown of the values for this column? > > Possibly a histogram or a table saying out of 500 records I have one > hundred and two "301" ninety-eight "212" values and three-hundred > "410"? > Is SQL the way to for this? I'd start with: select column, count(column), min(column), max(column) from table group by column order by count(column) desc and then build an histogram from that (using PyChart for instance). Based on this distribution curve, one can refine the analysis in a lot of ways... > Of course there'd be 1000's of values.... Should not be a problem for today's DBMS and hardware... -- Gabriel Genellina From rschroev_nospam_ml at fastmail.fm Sat Aug 11 10:19:51 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 11 Aug 2007 14:19:51 GMT Subject: Augmented assignment (was Re: Something in the function tutorial confused me.) In-Reply-To: References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> Message-ID: Aahz schreef: > In article , > Neil Cerutti wrote: >> On 2007-08-11, Alex Martelli wrote: >>> Neil Cerutti wrote: >>> ... >>>> The Python Language Reference seems a little confused about the >>>> terminology. >>>> >>>> 3.4.7 Emulating numeric types >>>> 6.3.1 Augmented assignment statements >>>> >>>> The former refers to "augmented arithmetic operations", which I >>>> think is a nice terminology, since assignment is not necessarily >>>> taking place. Then the latter muddies the waters. >>> Assignment *IS* "necessarily taking place"; if you try the augmented >>> assignment on something that DOESN'T support assignment, you'll get an >>> exception. Consider: >>> >>>>>> tup=([],) >>>>>> tup[0] += ['zap'] >>> Traceback (most recent call last): >>> File "", line 1, in >>> TypeError: 'tuple' object does not support item assignment >>> >>> Tuples don't support item ASSIGNMENT, and += is an ASSIGNMENT, >>> so tuples don't allow a += on any of their items. >>> >>> If you thought that += wasn't an assignment, this behavior and >>> error message would be very problematic; since the language >>> reference ISN'T confused and has things quite right, this >>> behavior and error message are perfectly consistent and clear. >> Thanks for the correction. I was under the illusion that sometimes >> augmented assignment would instead mutate the object. > > Although Alex is essentially correct, the situation is a bit more complex > and you are correct that augmented assignment allows the object to decide > whether to mutate in place. However, the critical part of Alex's point > is what you need to focus on: it's the *tuple* in Alex's example that > intercepts the assignment call, not the list contained in the tuple. > > Obviously, you can easily work around it: > >>>> t = ([],) >>>> l = t[0] >>>> l += ['foo'] >>>> t > (['foo'],) I'm missing something here, I think. As far as I can tell, the language reference says that the target is evaluated before the augmented assignment is performed. If that's the case, I don't see how the tuple in Alex' example has anything to with it: the assignment is to the list, not the tuple. And watch this (Python 2.4.2): >>> tup = ([],) >>> tup[0] += ['zap'] Traceback (most recent call last): File "", line 1, in -toplevel- tup[0] += ['zap'] TypeError: object does not support item assignment So far that's the same as Alex' example, but look at the value of the tuple now: >>> tup (['zap'],) Despite the TypeError, the list *has* changed. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From oliver.andrich at gmail.com Thu Aug 23 13:59:43 2007 From: oliver.andrich at gmail.com (oliver.andrich at gmail.com) Date: Thu, 23 Aug 2007 17:59:43 -0000 Subject: ctypes and unsigned char* In-Reply-To: References: <1187545486.797017.308720@a39g2000hsc.googlegroups.com> <1187548845.674582.69630@w3g2000hsg.googlegroups.com> <1187609450.542644.50430@w3g2000hsg.googlegroups.com> Message-ID: <1187891983.131947.128030@l22g2000prc.googlegroups.com> On 23 Aug., 05:46, "Gabriel Genellina" wrote: > If the result can contain nul bytes, you have to specify its size > explicitely (else it will be truncated at the first zero). Use the > string_at utility function: > > result_str = string_at(result, length) > > (That should work fine, I presume...) Thank a lot, that does exactly what I expected it to do. Best regards, Oliver From istvan.albert at gmail.com Wed Aug 8 10:26:08 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Wed, 08 Aug 2007 14:26:08 -0000 Subject: Misleading wikipedia article on Python 3? In-Reply-To: <7xzm15q8fy.fsf@ruckus.brouhaha.com> References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <7xzm15q8fy.fsf@ruckus.brouhaha.com> Message-ID: <1186583168.447608.114040@d55g2000hsg.googlegroups.com> On Aug 6, 6:11 am, Paul Rubin wrote: > Why on earth did they make this change? It just seems gratuitous. Having print a function (with parameters) makes is very easy to modify where the output goes. Say you want to have some prints go to one particular file, today you cannot easily do it, you have to either do a regex based search/ replace or fiddle with the sys.stdout etc. both have substantial drawbacks. A solution would be writing the code with a logging function to begin with, alas many times that is out of one's hand. I wished print was a function great many times. I bet Guido has had similar experiences, note that attempt to keep print in the current form but have it print to a file ... with that crazy syntax, print >>f, ... alas that did not solve anything It is time to fix it for good. i. From ladynikon at gmail.com Fri Aug 3 12:11:35 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Fri, 3 Aug 2007 12:11:35 -0400 Subject: Eclipse/PyDev question. In-Reply-To: <59f9c5160708030846j5bb2e275u8db95474519b00fe@mail.gmail.com> References: <1186153119.391091.275860@r34g2000hsd.googlegroups.com> <1186153259.372809.230110@d30g2000prg.googlegroups.com> <1186153503.806195.225560@g4g2000hsf.googlegroups.com> <59f9c5160708030846j5bb2e275u8db95474519b00fe@mail.gmail.com> Message-ID: <59f9c5160708030911x3ec2d132oba0fe18c6b2eedc4@mail.gmail.com> I just found this: http://www.easyeclipse.org/site/distributions/python.html From daniels at dsl-only.net Sat Aug 18 00:55:46 2007 From: daniels at dsl-only.net (Scott David Daniels) Date: Fri, 17 Aug 2007 21:55:46 -0700 Subject: help on object programing In-Reply-To: <1187370429.041002.205500@d55g2000hsg.googlegroups.com> References: <1187370429.041002.205500@d55g2000hsg.googlegroups.com> Message-ID: <13ccuu4e01vj864@corp.supernews.com> yadin wrote: > class big(self): > ... > how can i define my variables so that there are valid outside the > class??? Although you did not describe the issue all that well, I _think_ you are referring to the fact that the following two pieces of code behave less like each other than one might suspect. The previous responders have missed the confusing part of python in your attempt to present your confusion. def big(): abc = 7 print abc class small(object): print '...' print abc def __init__(self): print abc return small() big() class Big(object): Abc = 13 print Abc class Small(object): print '...' print Abc def __init__(self): print Abc cell = Small() big() The explanation is unfortunately a little technical. The class-in-a-function (small) is not defined until the function (big) is actually _called_, not when big is being defined. The class-in-a-class (Small) in the second instance is actually defined _before_ Big is being defined, and the temporary namespace that contains Abc is hidden while Small is being defined. -Scott David Daniels Scott.Daniels at Acm.Org From helloizomi at gmail.com Wed Aug 29 03:26:06 2007 From: helloizomi at gmail.com (helloizomi at gmail.com) Date: Wed, 29 Aug 2007 07:26:06 -0000 Subject: Running daemon with zdaemon ... example help? In-Reply-To: <46cfe403$0$21147$7a628cd7@news.club-internet.fr> References: <1188011052.347321.211890@r23g2000prd.googlegroups.com> <46cfe403$0$21147$7a628cd7@news.club-internet.fr> Message-ID: <1188372366.955787.143600@r23g2000prd.googlegroups.com> Thank you, I got it now ^.^ On Aug 25, 3:10 pm, asrenzo wrote: > Hi, > > This could also be a good starting point:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 > > Regards, > > Laurent > > Genie T a ?crit : > > > Hi all, > > > I'm looking atzdaemonto run my python scripts as a daemon but it > > seems to have few example that guide me how to follow. It would be > > great if you can give me a simple example of how to use. I'm newbie > > here :) > > > Thanks From deets at nospam.web.de Sun Aug 19 14:37:20 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 19 Aug 2007 20:37:20 +0200 Subject: Python on Computation, Math and Statistics In-Reply-To: References: Message-ID: <5irgvaF3oi5dpU2@mid.uni-berlin.de> W. Watson schrieb: > I would hope Python is doing a lot of standard computations beyond > arithmetic. Trig functions and more. Comments? Bad google day? http://docs.python.org/lib/numeric.html Additionally, there are several scientific extensions, like SciPy, Numeric/Numpy and so forth. Diez From nick at craig-wood.com Wed Aug 29 06:30:08 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 29 Aug 2007 05:30:08 -0500 Subject: tempfile.mkstemp and os.fdopen References: <1188323759.955043.317630@19g2000hsx.googlegroups.com> Message-ID: Lawrence D'Oliveiro wrote: > In message , Michael > J. Fromberger wrote: > > > ... since os.fdopen() only has access to the file descriptor, it > > does not have a convenient way to obtain the file's name. > > You can do this under Linux as follows: > > os.readlink("/proc/%d/fd/%d" % (os.getpid(), fileno)) A good idea! You can write this slightly more succinctly as os.readlink("/proc/self/fd/%d" % fileno) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From ldo at geek-central.gen.new_zealand Sat Aug 25 08:41:12 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 26 Aug 2007 00:41:12 +1200 Subject: accessing keys in dict References: <1187143106.021325.104690@l22g2000prc.googlegroups.com> Message-ID: In message <1187143106.021325.104690 at l22g2000prc.googlegroups.com>, james_027 wrote: > is there any difference between .. > > for key in a_dict: > > from > > for key in a_dict.keys(): I'm assuming the former is equivalent to for key in a_dict.iterkeys() : From gagsl-py2 at yahoo.com.ar Tue Aug 21 22:56:18 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 21 Aug 2007 19:56:18 -0700 Subject: Chaining programs with pipe In-Reply-To: <1187743235.124030.321200@l22g2000prc.googlegroups.com> References: <1187734166.384152.178040@o80g2000hse.googlegroups.com> <1187743235.124030.321200@l22g2000prc.googlegroups.com> Message-ID: <1187751378.122706.211880@q3g2000prf.googlegroups.com> On 21 ago, 21:40, Karthik Gurusamy wrote: > On Aug 21, 3:09 pm, avishay wrote: > > > I'm trying to chain two programs with a pipe (the output of one > > feeding the input of the other). I managed to capture the output and > > feeding the input of each program independently with popen, but how do > > I tie them together? Is there a solution that works equally on all > > platforms? > > Not sure on non-unix platforms, but in unix like platforms it's best > to reuse shell's power. > > >>> import commands > >>> commands.getoutput('ls | wc') Using the shell is OK but I think the subprocess module is more portable. This example is on Windows: import subprocess subprocess.call("dir /b | sort", shell=True) ~DFDADD.tmp ~DFF71E.tmp 1.bak 1.cmd 1.csv 1.py 1.txt 2.py 2A0B17.dmp [...] -- Gabriel Genellina From v.Abazarov at comAcast.net Fri Aug 17 09:45:18 2007 From: v.Abazarov at comAcast.net (Victor Bazarov) Date: Fri, 17 Aug 2007 09:45:18 -0400 Subject: best GUI library for vector drawing program References: <1187357244.883516.79840@j4g2000prf.googlegroups.com> Message-ID: chewie54 wrote: > What would be the best cross-platform GUI library to use for a vector > based CAD program ( something like Visio on Windows ) WxWidgets, > Tk, PyQt, Java Swing, Java SWT,???? I need the capibility to > draw and edit in a window that looks like a page of paper so WYSIWYG > is very important, and I need to save the drawings in vector based > file formats like PS, EPS, SVG, as well as image formats like jpg, > png, and gif. Also, the images need to be high resolution so that > they can be pasted into various other programs in Windows OS, and > Linux OS, and the Mac OS. You might actually consider asking in the 'comp.graphics' hierarchy instead of the language newsgroups. V -- Please remove capital 'A's when replying by e-mail I do not respond to top-posted replies, please don't ask From aleax at mac.com Sun Aug 5 18:24:38 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 5 Aug 2007 15:24:38 -0700 Subject: Formatting Results so that They Can be Nicely Imported into a Spreadsheet. References: <1186270555.514649.311280@d30g2000prg.googlegroups.com> <1186278638.931477.39760@z24g2000prh.googlegroups.com> <1186284359.668342.5880@d30g2000prg.googlegroups.com> <1186304814.129279.207100@j4g2000prf.googlegroups.com> <1186335656.977681.284240@z24g2000prh.googlegroups.com> Message-ID: <1i2dpfm.12ys1n8pj8hejN%aleax@mac.com> mensanator at aol.com wrote: ... > Even with the "if i" included, we end up with an > empty list at the start. This because the first "blank" > line wasn't blank, it was a space, so it passes the > "if i" test. ...and you can fix that by changing the test to [... if i.split()]. Alex From countblabula at yahoo.com Mon Aug 6 13:17:22 2007 From: countblabula at yahoo.com (Lee Fleming) Date: Mon, 06 Aug 2007 10:17:22 -0700 Subject: Something in the function tutorial confused me. In-Reply-To: References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> Message-ID: <1186420642.112170.78940@w3g2000hsg.googlegroups.com> On Aug 6, 6:25 am, Neil Cerutti wrote: Because when the function is called, the line > if y is None: y = [] is executed, binding a brand new empty list to y. This "rebinding" happens every time the function is called, unless you provide an argument for y that is not None. Thanks for the prompt replies. But I am still confused. This is what confuses me.... The first time you call the function, say with f(23), after the function ends, y no longer equals None. Therefore, calling f again, this time like this f(24), should make y equal [23,24], because the 'if y == None' test fails, or at least I think it fails, because y.append(x) added something that was not equal to None during the previous call. Please help me! From mensanator at aol.com Sat Aug 4 23:25:59 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sat, 04 Aug 2007 20:25:59 -0700 Subject: Formatting Results so that They Can be Nicely Imported into a Spreadsheet. In-Reply-To: References: <1186270555.514649.311280@d30g2000prg.googlegroups.com> <1186278638.931477.39760@z24g2000prh.googlegroups.com> Message-ID: <1186284359.668342.5880@d30g2000prg.googlegroups.com> On Aug 4, 9:21?pm, "Jim Langston" wrote: > wrote in message > > news:1186278638.931477.39760 at z24g2000prh.googlegroups.com... > > > > > > > On Aug 4, 6:35?pm, SMERSH009 wrote: > >> Hi All. > >> Let's say I have some badly formatted text called doc: > > >> doc= > >> """ > >> friendid > >> Female > > >> 23 years old > > >> Los Gatos > > >> United States > >> friendid > >> Male > > >> 24 years old > > >> San Francisco, California > > >> United States > >> """ > > >> How would I get these results to be displayed in a format similar to: > >> friendid;Female;23 years old;Los Gatos;United States > >> friendid;Male; 24 years old;San Francisco, California;United States > > >> The latter is a lot easier to organize and can be quickly imported > >> into Excel's column format. > > >> Thanks Much, > >> Sam > > > d = doc.split('\n') > > > f = [i.split() for i in d if i] > > > g = [' '.join(i) for i in f] > > > rec = [] > > temprec = [] > > for i in g: > > if i: > > if i == 'friendid': > > rec.append(temprec) > > temprec = [i] > > else: > > temprec.append(i) > > rec.append(temprec) > > > output = [';'.join(i) for i in rec if i] > > > for i in output: print i > > > ## friendid;Female;23 years old;Los Gatos;United States > > ## friendid;Male;24 years old;San Francisco, California;United States > > also, I would suggest you use CSV format. Well, the OP asked for a specific format. One is not always at liberty to change it. > CSV stands for "Comma Seperated > Variable" and Excel can load such a sheet directly. And Excel can load the shown format directly also, just specify the delimiter. > > Instead of seperating using ; seperate using , Of course, this provides a > problem when there is a , in a string. Which explains the popularity of using tabs as delimiters. The data deliverable specification I use at work uses the pipe character | which never appears as data in this particular application. > Resolution is to quote the string. Which makes the file bigger and isn't necessary when tabs and pipes are used as delimiters. > Being such, you can just go ahead and quote all strings. So you would want > the output to be: > > "friendid","Female","23 years old","Los Gatos","United States" > "friendid","Male","24 years old","San Francisco, California","United States" Which I would do if I had a specification that demanded it or was making files for others. For my own use, I wouldn't bother as it's unnecessary work. > > Numbers should not be quoted if you wish to treat them as numeric and not > text. A good reason not to use quotes at all. Besides which, Excel can handle that also. From http Thu Aug 16 04:16:20 2007 From: http (Paul Rubin) Date: 16 Aug 2007 01:16:20 -0700 Subject: python socket usage References: Message-ID: <7xvebfvqqz.fsf@ruckus.brouhaha.com> O?uz Yar?mtepe writes: > Is it possible to send a data object like a tuple or a list in socket > programming? If so how? It seems with socket module it is only possible to > send strings. Look into something like pyro or JSON. Whatever you do, don't use eval. From flyzone at technologist.com Mon Aug 13 09:43:51 2007 From: flyzone at technologist.com (Flyzone) Date: Mon, 13 Aug 2007 06:43:51 -0700 Subject: strftime in python 2.2 Message-ID: <1187012631.102571.94210@w3g2000hsg.googlegroups.com> I'm trying to make work this code in python 2.2.3: check=datetime.datetime.today().strftime("%H%M") but datetime is not supported in that version but just in the later. I can't upgrade python, too many dependencies in a critical system. How can i convert that string to have the same result? Hope someone can help me, Thanks in advance From andre.roberge at gmail.com Thu Aug 2 15:48:39 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Thu, 02 Aug 2007 19:48:39 -0000 Subject: Determining if file is valid image file In-Reply-To: References: <1186064098.587590.91210@g4g2000hsf.googlegroups.com> <1186064275.652416.250540@d55g2000hsg.googlegroups.com> <1186065645.879720.27720@q75g2000hsh.googlegroups.com> Message-ID: <1186084119.574473.153120@d30g2000prg.googlegroups.com> On Aug 2, 4:25 pm, Jarek Zgoda wrote: > Andr? napisa?(a): > > >>>> Other than installing PIL, is there a "simple" way using Python only > >>>> to determine if a file is a valid image file? > >>>> I'd be happy if I could at least identify valid images files for gif, > >>>> jpeg and png. Pointers to existing modules or examples would be > >>>> appreciated. > >>>> The reason why I'd prefer not using PIL is that I'd like to bundle > >>>> such a function/module in my app. > >>>> Andr? > >>> I should have added: I'm interesting in validating the file *content* > >>> - not the filename :-) > >> Is the module imghdr enough for your needs? > > > Yes, thanks. > > Be aware that broken images (i.e. partially downloaded) in many cases > pass the imghdr.what() test. This function checks for patterns in files, > just like "file" utility. > That's all I need; I'm not concerned about broken images. I am writing a web app and need to prevent someone using redirection to send malicious content when I'm supposedly loading an image file. So, what I plan to do is open the file using urlopen, preload the image and see if it is valid; if so, I pass it on to the browser. To find out more, look for "redirect" on the following page (it is the first occurence of that word) http://ha.ckers.org/xss.html > -- > Jarek Zgodahttp://jpa.berlios.de/ From ehsan.khoddam at gmail.com Sat Aug 4 01:45:17 2007 From: ehsan.khoddam at gmail.com (Ehsan) Date: Fri, 03 Aug 2007 22:45:17 -0700 Subject: regexp problem in Python In-Reply-To: <1186180565.489968.310340@j4g2000prf.googlegroups.com> References: <1186177312.117581.129910@d55g2000hsg.googlegroups.com> <1186180565.489968.310340@j4g2000prf.googlegroups.com> Message-ID: <1186206317.800338.215960@i38g2000prf.googlegroups.com> On Aug 4, 1:36 am, Dave Hansen wrote: > On Aug 3, 4:41 pm, Ehsan wrote: > > > I want to find "http://www.2shared.com/download/1716611/e2000f22/ > [...] > > I use this pattern : > > "http.*?\.(wmv|3gp).*"" > > > but it returns only 'wmv' and '3gp' instead of "http://www.2shared.com/ > > download/1716611/e2000f22/Jadeed_Mlak14.wmv? > > tsid=20070803-164051-9d637d11" > > > what can I do? what's wrong whit this pattern? thanx for your comments > > Just a guess, based on too little information: Try "(http.*?\.(wmv| > 3gp).*)" > > Regards, > > -=Dave no, it doesn't work From tamim.shahriar at gmail.com Tue Aug 21 14:33:01 2007 From: tamim.shahriar at gmail.com (subeen) Date: Tue, 21 Aug 2007 18:33:01 -0000 Subject: C# and Python In-Reply-To: References: <1187690505.903506.79690@d55g2000hsg.googlegroups.com> <1187699710.839869.32810@57g2000hsv.googlegroups.com> Message-ID: <1187721181.391208.145540@g4g2000hsf.googlegroups.com> On Aug 21, 7:24 pm, "Chris Mellon" wrote: > On 8/21/07, Ant wrote: > > > On Aug 21, 11:01 am, subeen wrote: > > > Hi, > > ... > > > But I want to write the GUI and number generation program in C#.net. > > > When the user clicks Quick Sort button, the quicksort.py will be > > > called and it will sort the numbers. > > > Probably worth looking at IronPython, the Python implementation for > > the .Net platform. > > > -- > > Also Pythonnet (see the recent announce on this ML), which is a > .NET/CPython bridge and supports embedding CPython as well as calling > .NET code from CPython. Thanks everyone for your valuable suggestions. I shall let you know my status. Regards, Subeen. From ocollioud at gmail.com Fri Aug 24 07:00:31 2007 From: ocollioud at gmail.com (olive) Date: Fri, 24 Aug 2007 11:00:31 -0000 Subject: Co-developers wanted: document markup language In-Reply-To: <87absh6wn6.fsf@wilson.homeunix.com> References: <87odgyyx9u.fsf@wilson.homeunix.com> <87tzqpew22.fsf@wilson.homeunix.com> <87tzqp77my.fsf@wilson.homeunix.com> <7xy7g1if24.fsf@ruckus.brouhaha.com> <87mywh717i.fsf@wilson.homeunix.com> <1187947900.676122.144490@e9g2000prf.googlegroups.com> <87absh6wn6.fsf@wilson.homeunix.com> Message-ID: <1187953231.106631.174870@q4g2000prc.googlegroups.com> On 24 ao?t, 12:43, Torsten Bronger wrote: > Hall?chen! > > olive writes: > > What about ODF ? (http://www.odfalliance.org/) Isn't it a good > > competitor ? > > I'd be a nice further backend but I doubt that people want to enter > XML. > Why not if the schema is designed toward data entry. You could then use XSLT to convert to ODF for publishing. What you need is good structured text editor which hides as much as possible the underlying XML (or other) format. Olive. From michele.simionato at gmail.com Fri Aug 10 03:36:09 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 10 Aug 2007 07:36:09 -0000 Subject: is there anybody using __del__ correctly?? Message-ID: <1186731369.073644.158490@z24g2000prh.googlegroups.com> The title is provocative, of course ;) However, I was browsing through our codebase here at work and I noticed a few usages of __del__ as a resource finalizer (i.e. __del__ just calls a close method). I consider this practice an error, since with __del__ you are never sure that the resource will be released (http://docs.python.org/ref/customization.html#l2h-175) and anyway this should be done with try .. finally or the 'with' statement. So I got into thinking: "yes, using __del__ as a resource finalizer is wrong, but then what are good use cases for it? Let's look at the standard library and see what people use __del__ for". So I did, and to my dismay 95% of the __del__ methods in the standard library are just calling a close method!! In particular this happens in the following modules: (Python 2.5 on Ubuntu): zipfile, wave, urllib, close, tarfile, sunau, shelve, httplib, gzip, fileinput, dumbdbm, audiodev, aifc, bsddb.dbshelve, tempfile, socket, platform, ... (I got tired after this point) I see one good use case for __del__ in wsgiref.validate: here __del__ prints a warning if the resource is *not* closed explicitely. Something similar happens in subprocess and popen2, where __del__ updates the list of active processes. So I am beginning to wonder if there exists good use cases for __del__, apart for debugging/checking purposes. Can you provide some? Yes, you may take that as a challenge ;) Michele Simionato P.S. BTW, I should mention that if you search comp.lang.python for __del__ you will find hundreds of people who were bitten by __del__, so I usually give advices such as "you should never __del__ in your code". If I am wrong in giving this advice, please let me know! P.P.S. Here and there I hear rumors about deprecating __del__ and nothing happens, are there any news about that? Expecially concerning Py3k? From wildemar at freakmail.de Mon Aug 27 06:30:29 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 27 Aug 2007 12:30:29 +0200 Subject: Lists In-Reply-To: References: Message-ID: <46D2A7C5.6030400@freakmail.de> Lamonte Harris wrote: > Ok > a = ['spam', 'eggs', 100, 1234] > > > So basically when I do > print a[1:-1] > > that will display all the choices in the array besides 0,3 > > Slicing was kinda weird, just making sure. > And your question is? /W From fakeaddress at nowhere.org Sat Aug 11 04:21:18 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 11 Aug 2007 08:21:18 GMT Subject: The Future of Python Threading In-Reply-To: <1186764743.225475.241870@q3g2000prf.googlegroups.com> References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <1186764743.225475.241870@q3g2000prf.googlegroups.com> Message-ID: <2kevi.1578$3x.691@newssvr25.news.prodigy.net> Justin T. wrote: > True, but Python seems to be the *best* place to tackle this problem, > at least to me. It has a large pool of developers, a large standard > library, it's evolving, and it's a language I like :). Languages that > seamlessly support multi-threaded programming are coming, as are > extensions that make it easier on every existent platform. Python has > the opportunity to lead that change. I have to disagree. A dynamic scripting language, even a great one such as Python, is not the vehicle to lead an advance of pervasive threading. The features that draw people to Python do not play nicely with optimizing multi-core efficiency; they didn't play all that well with single-core efficiency either. Python is about making good use of our time, not our machines' time. Finer-grain locking sounds good, but realize how many items need concurrency control. Python offers excellent facilities for abstracting away complexity, so we programmers do not mentally track all the possible object interactions at once. In a real application, objects are more intertwingled than we realize. Whatever mistakes a Python programmer makes, the interpreter must protect its own data structures against all possible race errors. Run-time flexibility is a key Python feature, and it necessarily implies that most bindings are subject to change. Looking at a Python function, we tend to focus on the named data objects, and forget how many names Python is looking up at run time. How often do we take and release locks on all the name-spaces that might effect execution? The GIL both sucks and rocks. Obviously cores are becoming plentiful and the GIL limits how we can exploit them. On the other hand, correctness must dominate efficiency. We lack exact reasoning on what we must lock; with the GIL, we err on the side of caution and correctness. Instead of trying to figure out what we need to lock, we default to locking everything, and try to figure out what we can safely release. [Steve Holden:] >> Be my guest, if it's so simple. >> > I knew somebody was going to say that! I'm pretty busy, but I'll see > if I can find some time to look into it. If you want to lead fixing Python's threading, consider first delivering a not-so-grand but definite improvement. Have you seen how the 'threading' module in Python's standard library implements timeouts? -- --Bryan From osiris43 at gmail.com Mon Aug 13 14:45:22 2007 From: osiris43 at gmail.com (osiris43 at gmail.com) Date: Mon, 13 Aug 2007 18:45:22 -0000 Subject: programmatically define a new variable on the fly In-Reply-To: <1186744111.800625.232730@x40g2000prg.googlegroups.com> References: <1186697500.024593.303820@x35g2000prf.googlegroups.com> <1186744111.800625.232730@x40g2000prg.googlegroups.com> Message-ID: <1187030722.395857.122190@e9g2000prf.googlegroups.com> > Anyway, I don?t see the point in this. Why don?t you just use > something like X['g'] instead? While it's not what the original author is intending, it seems to me that dynamically adding fields could be useful when something like a database schema changed frequently. For example, a row in a database might contain data related to a customer and I would think it might be useful to do something like this (where data is a dictionary created from the column names and row data): class Customer: def __init__(self, data): for col_name, value in data.iteritems(): setattr(self, col_name, value) Alternatively, you could just assign the original dictionary to a field on Customer called data and then access it by key: class Customer: def __init__(self, data): self.customerData = data I'm pretty new to Python so it's entirely possible I'm doing things the hard way but if you had behavior on a class, I can see where dynamically creating fields on it would be useful. From aleax at mac.com Sun Aug 19 14:09:42 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 19 Aug 2007 11:09:42 -0700 Subject: Sorting a list of Unicode strings? References: <1187542237.139346.6910@o80g2000hse.googlegroups.com> <46C87772.2010603@web.de> <1187543116.941243.200960@r34g2000hsd.googlegroups.com> Message-ID: <1i338vd.1kisqttkij0d9N%aleax@mac.com> oliver at obeattie.com wrote: ... > > > Maybe I'm missing something fundamental here, but if I have a list of > > > Unicode strings, and I want to sort these alphabetically, then it > > > places those that begin with unicode characters at the bottom. ... > Anyway, I know _why_ it does this, but I really do need it to sort > them correctly based on how humans would look at it. Depending on the nationality of those humans, you may need very different sorting criteria; indeed, in some countries, different sorting criteria apply to different use cases (such as sorting surnames versus sorting book titles, etc; sorry, I don't recall specific examples, but if you delve on sites about i18n issues you'll find some). In both Swedish and Danish, I believe, A-with-ring sorts AFTER the letter Z in the alphabet; so, having ?aland (where I'm using Aa for A-with-ring, since this newsreader has some problem in letting me enter non-ascii characters;-) sort "right at the bottom", while it "doesn't look right" to YOU (maybe an English-speaker?) may look right to the inhabitants of that locality (be they Danes or Swedes -- but I believe Norwegian may also work similarly in terms of sorting). The Unicode consortium does define a standard collation algorithm (UCA) and table (DUCET) to use when you need a locale-independent ordering; at you'll be able to obtain James Tauber's Python implementation of UCA, to work with the DUCET found at . I suspect you won't like the collation order you obtain this way, but you might start from there, subsetting and tweaking the DUCET into an OUCET (Oliver Unicode Collation Element Table;-) that suits you better. A simpler, rougher approach, if you think the "right" collation is obtained by ignoring accents, diacritics, etc (even though the speakers of many languages that include diacritics, &c, disagree;-) is to use the key=coll argument in your sorting call, passing a function coll that maps any Unicode string to what you _think_ it should be like for sorting purposes. The .translate method of Unicode string objects may help there: it takes a dict mapping Unicode ordinals to ordinals or string (or None for characters you want to delete as part of the translation). For example, suppose that what we want is the following somewhat silly collation: we only care about ISO-8859-1 characters, and want to ignore for sorting purposes any accent (be it grave, acute or circumflex), umlauts, slashes through letters, tildes, cedillas. htmlentitydefs has a useful dict called codepoint2name that helps us identify those "weirdy decorated foreign characters". def make_transdict(): import htmlentitydefs cp2n = htmlentitydefs.codepoint2name suffixes = 'acute crave circ uml slash tilde cedil'.split() td = {} for x in range(128, 256): if x not in cp2n: continue n = cp2n[x] for s in suffixes: if n.endswith(s): td[x] = unicode(n[-len(s)]) break return td def coll(us, td=make_transdict()): return us.translate(td) listofus.sort(key=coll) I haven't tested this code, but it should be reasonably easy to fix any problems it might have, as well as making make_transdict "richer" to meet your goals. Just be aware that the resulting collation (e.g., sorting a-ring just as if it was a plain a) will be ABSOLUTELY WEIRD to anybody who knows something about Scandinavian languages...!!!-) Alex From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Aug 12 19:04:34 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 13 Aug 2007 01:04:34 +0200 Subject: wxPython - drawing without paint event References: <1186710391.148396.113490@d30g2000prg.googlegroups.com> <1186738813.373909.96230@x35g2000prf.googlegroups.com> <1186796567.331348.42450@q3g2000prf.googlegroups.com> <5i5l0dF2lortaU1@mid.individual.net> <1186883988.585048.16590@m37g2000prh.googlegroups.com> <5i8befF3o5no1U1@mid.individual.net> <1186928595.014008.61950@b79g2000hse.googlegroups.com> <5i98bsF3nmbavU1@mid.individual.net> <1186951326.218981.17820@b79g2000hse.googlegroups.com> Message-ID: <5i9i02F3m55igU1@mid.individual.net> 7stud wrote: > On Aug 12, 2:20 pm, Bjoern Schliessmann > But any suggestions what's >> better for a beginner? The (incomplete) tutorial surely not. > Another GUI toolkit. So it seems your dislike is not for the book, but for the toolkit. Regards, Bj?rn -- BOFH excuse #414: tachyon emissions overloading the system From bj_666 at gmx.net Sat Aug 11 05:59:57 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Aug 2007 09:59:57 GMT Subject: python 2.5 bug References: <1186825286.493878.80380@l70g2000hse.googlegroups.com> Message-ID: <5i5fktF3ml00gU1@mid.uni-berlin.de> On Sat, 11 Aug 2007 02:41:26 -0700, vedrandekovic wrote: > I was install Python 2.5 and uninstall Python 2.4 now I cannot run my > scripts, only from idle > > What should I do? Install 2.4 again. Both can be installed in parallel. Ciao, Marc 'BlackJack' Rintsch From codemania at gmail.com Fri Aug 31 08:49:49 2007 From: codemania at gmail.com (codemania) Date: Fri, 31 Aug 2007 05:49:49 -0700 Subject: How to use "Resource Editor" in wxPython ? Message-ID: <1188564589.573864.86980@x40g2000prg.googlegroups.com> Disappointing me extremely, with the "generate python" function within Resource Editor, I only get a segment of python code which load xrc(xml format) file, rather than real python code in which I could append my own code. Does that mean RE(Resource Editor) is of little use? I hope not, maybe the way I use it is wrong? Tell me please. From pablo.yabo at gmail.com Mon Aug 13 13:42:09 2007 From: pablo.yabo at gmail.com (Pablo Yabo) Date: Mon, 13 Aug 2007 14:42:09 -0300 Subject: C++ Binding with Threads Message-ID: Hello, I want to embed Python in an application and use an API of the application from Python. The application uses a library that creates several threads and I the users of the application will write Python scripts handling this events. The problem is that I having problems with threads. I saw that I have to PyEval_InitThreads and then PyThreadState_New and PyThreadState_Swap from the new thread but this way to solve the problem doesn't work for me because I need to let 2 or more threads run at the SAME time. The interpreter lock doesn't let them run at the same time so I'm looking for another solution. I saw Py_NewInterpreter and I tried to use it but it doesn't work if I don't keep the lock. Can anyone help me to solve this issue or tell me 'Forget it!'? Thanks on advance, Pablo Yabo -------------- next part -------------- An HTML attachment was scrubbed... URL: From arkanes at gmail.com Tue Aug 7 09:42:43 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 7 Aug 2007 08:42:43 -0500 Subject: Tkinter or wxpython? In-Reply-To: <7xy7gopafk.fsf@ruckus.brouhaha.com> References: <7xps204tin.fsf@ruckus.brouhaha.com> <7xlkcopu4r.fsf@ruckus.brouhaha.com> <7x3aywr4tc.fsf@ruckus.brouhaha.com> <7x8x8oqy17.fsf@ruckus.brouhaha.com> <7xy7gopafk.fsf@ruckus.brouhaha.com> Message-ID: <4866bea60708070642t755e8a0do27ab4f66ca4724dc@mail.gmail.com> On 06 Aug 2007 15:25:51 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > "Chris Mellon" writes: > > You repeatedly have used the word "slickness" as a pejorative. I find > > that offensive and it's insulting to users. When I write applications, > > I want the interface to be as smooth and trouble free as possible, > > It's a perjorative when it's done for its own sake and doesn't really > help the user. This happens a lot. When it helps the user, as it > sometimes does, then it's not perjorative. > To me, "slick" means well lubricated and smooth. It means that there are no rough spots in your interaction. I use the term "flash" for cosmetic features. > > As a matter of time spent in development, I do not find that > > non-trivial UIs are significantly easier to develop using web > > interfaces. > > That's possibly true, but a lot of the time, trivial interfaces are > enough. Look at Google search, one of the most complex apps ever > built (tens or hundreds of MLOC, massive distributed crawler > infrastructure, 100's of PhD's figuring out the algorithms, etc.) but > its interface is simple HTML that you would probably call trivial. It > is quite possibly the most popular application in the world. > When you start talking about trivializing the interface, what you're actually talking about is trivializing the *process*. The UI is just a mechanism for interaction. If you have complex interactions, then you need complex UI (or your users have to do a lot of manual steps). Search is a good example of trivial interaction. It's not really the common case, though - in a regular web browser there's a half dozen minimal points of interaction, and some of them are fairly complicated. In terms of man-hours spent, raw data entry is one of the largest cases of human-computer interaction and it's a significantly more complex interface than search. As you point out, the complexity of the interaction is only loosely coupled to the complexity of the application itself, and the art of designing simple interactions with complex systems is one of the hallmarks of good design. Apple is generally quite good at this. Note even so that simple interactions can have or require rather complicated UI metaphors. Drag and drop is a very visceral, intuitive interface (it's the second thing my 4 year old figured out how to do, button clicking was the first) but it's quite complicated to implement. I rather suspect that Google has rather more complicated internal administrative and reporting interfaces for the search engine, too. > > As a matter of respect for the user, I'm not going to tell them to use > > a trivial UI if a non-trivial one will save them time, learning > > effort, or frustration. In order to make this decision, I like to work > > with the people actually using it and watch them at work. To see what > > kind of extra steps they have to take and where I can save them time > > or inaccuracy or frustration. > > Right. Obviously this has to be decided according to the specific > needs of the application. A lot of times, trivial interfaces are > easier to learn than nontrivial ones, precisely because they are > trivial so there is less to learn. Again look at Google search for an > example. > > Also, at least for in-house applications, while the user's time counts > (since their time costs your customer money), your development time > and deployment effort also costs money that comes from exactly the > same place, so you have to take into consideration the number of > users, amount of time they will spend using the program, just how much > of that time (if any) a fancier interface will save, etc. Business constraints are always there in software development. You don't get enough testing, you don't have access to representative test data, you don't have direct user feedback. And of course the guy signing the checks, who often isn't the guy using the application, may decide that an hour of your time isn't worth 100 hours aggravation from his minimum wage data entry folks. But *I* care about that 100 hours and to the greatest extent possible within my ability and contract, I will minimize that burden on them. From larry.bates at websafe.com Wed Aug 15 14:58:34 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 15 Aug 2007 13:58:34 -0500 Subject: encrypting files + filestreams? In-Reply-To: <1187186797.579680.206820@19g2000hsx.googlegroups.com> References: <1187186797.579680.206820@19g2000hsx.googlegroups.com> Message-ID: per9000 wrote: > Hi python people, > > I am trying to figure out the best way to encrypt files in python. > > I've build a small script (see below) that encrypts the ubuntu 7.04 > iso file in 2 minutes (I like python :) ). > > But I have some thoughts about it. By pure luck (?) this file happened > to be N*512 bytes long so I do not have to add crap at the end - but > on files of the size N*512 + M (M != 521) I will add some crap to make > it fit in the algorithm. When I later decrypt I will have the stuff I > do not want. How do people solve this? (By writing the number of > relevant bytes in readable text in the beginning of the file?) > > Also I wonder if this can be solved with filestreams (Are there > streams in python? The only python file streams I found in the evil > search engine was stuff in other forums.) > > > Other comments are of course also welcome, > Per > > > # crypto_hardcoded.py starts here > > from Crypto.Cipher import AES > > def encrypt2(cryptor, infile, outfile): > """enly encrypt a few bytes at a time""" > > size = 512 > bytes = infile.read(size) > > seek = 0 > interval = 97 > ctr = 0 > > while len(bytes) == size: > seek += size > if ctr % interval == 0: > print '\r%15d bytes completed' % (seek), > ctr += 1 > > outfile.write(cryptor.encrypt(bytes)) > # change to this to decrypt > # outfile.write(cryptor.decrypt(bytes)) > bytes = infile.read(size) > > if len(bytes) != 0: > bytes += "#" * (size - len(bytes)) > outfile.write(cryptor.encrypt(bytes)) > seek += len(bytes) > > print '\r%15d bytes completed' % (seek) > > if __name__ == "__main__": > crptz = AES.new("my-secret_passwd") > ifile = file('/tmp/ubuntu-7.04-desktop-i386.iso','r') > ofile = file('/tmp/ubuntu-7.04-desktop-i386.iso.out','w') > > encrypt2(crptz, ifile, ofile) > ifile.close() > ofile.close() > > # crypto_hardcoded.py ends here > Padding and keeping information in a header is how I solved the problem. -Larry From not at given.net Thu Aug 30 04:30:50 2007 From: not at given.net (mr_gadget) Date: Thu, 30 Aug 2007 04:30:50 -0400 Subject: Python doesn't see the directories I create Message-ID: When I create a subfolder, python is not seeing it. Can someone please explain this behaviour ? I just started with python, read the tutorial over the weekend and am writing my very first script. So I may not be seeing something. Both os.path and glob.glob seem not to see a folder I created. Other sibling folders seem to work fine. On a whim I tried paths with \\ double slashes and that worked. But why should single slashes work for some folders and not for others ?? What I need is to match a bunch of files in a folder with glob.glob(C:\enhancement\rawfiles\*.bin.gz) and send them to a function that unzips them. But I always get []. Yes the folder does have my files, and I checked all permissions etc, everything looks identical to the other folders which python IS seeing. Same problem on my vista pc too. Behaviour reproduced below. C:\Enhancement>dir /ad Volume in drive C has no label. Volume Serial Number is 8056-41E7 Directory of C:\Enhancement 08/28/2007 06:15 PM

. 08/28/2007 06:15 PM .. 08/28/2007 06:07 PM BSA Documentation 08/28/2007 05:56 PM output 08/29/2007 07:08 PM rawfiles 08/23/2007 04:38 PM SnapCell2.3.2 08/28/2007 06:15 PM test 0 File(s) 0 bytes 7 Dir(s) 35,703,283,712 bytes free C:\>python -V Python 2.5.1 C:\>python -c "import os; print os.path.exists('C:\enhancement\output')" True C:\>python -c "import os; print os.path.exists('C:\enhancement\rawfiles')" False C:\>python -c "import os; print os.path.exists('C:\\enhancement\\rawfiles')" True C:\>python -c "import glob; print glob.glob('C:\enhancement\rawfiles\*')" [] C:\>python -c "import os; print os.path.exists('C:\enhancement\test')" False C:\>python -c "import os; print os.path.exists('C:\enhancement\snapcell2.3.2')" True From rodrigo.cr at gmail.com Mon Aug 20 21:03:22 2007 From: rodrigo.cr at gmail.com (rodrigo) Date: Tue, 21 Aug 2007 01:03:22 -0000 Subject: Retrieving a variable's name. Message-ID: <1187658202.236626.93600@50g2000hsm.googlegroups.com> How would I go about retrieving a variable's name (not its value)? I want to write a function that, given a list of variables, returns a string with each variable's name and its value, like: a: 100 b: 200 I get the feeling this is trivial, but I have been unable to find an answer on my own. Thanks, Rodrigo From gnewsg at gmail.com Thu Aug 23 17:57:25 2007 From: gnewsg at gmail.com (billiejoex) Date: Thu, 23 Aug 2007 14:57:25 -0700 Subject: Impersonate another user temporarily (Unix and Windows) In-Reply-To: References: <1187809798.274511.230240@z24g2000prh.googlegroups.com> <1187866104.967297.324650@j4g2000prf.googlegroups.com> <1187895663.991360.224830@x40g2000prg.googlegroups.com> Message-ID: <1187906245.063301.15980@z24g2000prh.googlegroups.com> On 23 Ago, 23:20, Steve Holden wrote: > billiejoex wrote: > > On 23 Ago, 13:13, "Chris Mellon" wrote: > [...] > >> Note that running your process as a user with enough priviledges to > >> impersonate another user pretty much eliminates all the benefits of > >> running as a low-priviledged user in the first place. Consider > >> re-thinking your application model and having an "ftp" user instead.- Nascondi testo tra virgolette - > > >> - Mostra testo tra virgolette - > > > Could you be more precise? > > Why it's not a good idea? > > I was thinking of starting ftpd as limited user ('nobody'/'ftp' on > > unix, 'Guest' on Windows), then temporary switching to another user > > when I got to perform actions on file system. > > Maybe you're saying that as limited user I can't do such switching? > > That's exactly what he's saying. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading -------------- Nascondi testo tra virgolette - > > - Mostra testo tra virgolette - Uhm... I'm confused. Which kind of aproach is generally adopted in such cases? From tenax.raccoon at gmail.com Wed Aug 8 12:47:52 2007 From: tenax.raccoon at gmail.com (Jason) Date: Wed, 08 Aug 2007 16:47:52 -0000 Subject: 'Advanced' list comprehension? query In-Reply-To: <1186588812.006107.185570@o61g2000hsh.googlegroups.com> References: <1186588812.006107.185570@o61g2000hsh.googlegroups.com> Message-ID: <1186591672.972638.220740@b79g2000hse.googlegroups.com> On Aug 8, 10:00 am, pyscottish... at hotmail.com wrote: > Hi, > > I'm playing around with list comprehension, and I'm trying to find the > most aesthetic way to do the following: > > I have two lists: > > noShowList = ['one', 'two', 'three'] > > myList = ['item one', 'item four', 'three item'] > > I want to show all the items from 'myList' that do not contain any of > the strings in 'noShowList'. > > i.e. 'item four' > > I can do it like this: > > def inItem(noShowList, listitem): > return [x for x in noShowList if x in listitem] > > print [x for x in myList if not inItem(noShowList, x)] > > and I can do it (horribly) with: > > print [x for x in myList if not (lambda y, z:[i for i in y if i in z]) > (noShowList, x)] > > I can also print out the items that DO contain the 'noShowList' > strings with: > > print [x for x in myList for y in noShowList if y in x] > > but I can't get the 'not' bit to work in the above line. > > Any ideas? > Thanks! Here's how I would do it: >>> noShowList ['one', 'two', 'four'] >>> myList ['item one', 'item two', 'item three', 'item four', 'item five'] >>> [x for x in myList if not any(y in x for y in noShowList)] ['item three', 'item five'] >>> --Jason From ldo at geek-central.gen.new_zealand Mon Aug 27 07:40:19 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 27 Aug 2007 23:40:19 +1200 Subject: non-blocking communication with imaplib References: Message-ID: In message , Igor V. Rafienko wrote: > I would like to talk to an IMAP-server, imaplib being the tool of > choice, of course. Unfortunately it may happen that the IMAP-server > fails to respond to certain commands, and I would like to be able to > detect that within a given time period (on the scale of 5-10 seconds). > > Initially, I thought about playing with setsockblocking() for the > communication socket in the imaplib.IMAP4 object. However, the IMAP4 > object uses a file object ("created from" the said socket), and the > underlying socket must be blocking according to [1]. > > [1] According to the documentation , you can override the "read" and "readline" methods. How about replacing them with routines that use select.select on the socket() object to implement a timeout? From rdmoores at gmail.com Sun Aug 12 09:26:09 2007 From: rdmoores at gmail.com (Dick Moores) Date: Sun, 12 Aug 2007 06:26:09 -0700 Subject: Puzzled by "is" In-Reply-To: <87ir7l5bv4.fsf@benfinney.id.au> References: <20070809194105.39BD11E400A@bag.python.org> <87zm1042f0.fsf@benfinney.id.au> <87ir7l5bv4.fsf@benfinney.id.au> Message-ID: On 8/12/07, Ben Finney wrote: > > Dick Moores writes: > > > At 06:13 PM 8/9/2007, Ben Finney wrote: > > >it's entirely left to the language implementation which > > >optimisation trade-offs to make, and the language user (that's you > > >and I) should *not* expect any particular behaviour to hold between > > >different implementations. > > > > I'm not clear on the meaning of "implementations" here. Would 2.5 > > for Windows, Mac, Linux all be different implementations? Would Iron > > Python be another? ActivePython? > > For the purpose of the above statement, you should consider even the > same Python on two different machines to be "different > implementations". As a programmer writing Python code, you should not > expect any "implementation-dependent" behaviour to operate in any > particular way. So would a programmer EVER use "is" in a script? Dick -------------- next part -------------- An HTML attachment was scrubbed... URL: From listserver at tdw.net Sat Aug 18 11:37:42 2007 From: listserver at tdw.net (Tim Williams) Date: Sat, 18 Aug 2007 16:37:42 +0100 Subject: clarification In-Reply-To: References: Message-ID: <9afea2ac0708180837q28fa3197je4d19874d9ae9aa5@mail.gmail.com> On 17/08/07, Beema shafreen wrote: > hi everybody, > i have a file with data separated by tab > mydata: > fhl1 fkh2 > dfp1 chk1 > mal3 alp14 > mal3 moe1 > mal3 spi1 > mal3 bub1 > mal3 bub3 > mal3 mph1 > mal3 mad3 > hob1 nak1 > hob1 wsp1 > hob1 rad3 > cdr2 cdc13 > cdr2 cdc2 > shows these two are separated by tab represented as columns > i have to check the common data between these two coloumn1 an coloumn2 > my code: > data = [] > data1 = [] > result = [] > fh = open('sheet1','r') > for line in fh.readlines(): > splitted = line.strip().split('\t') > data.append(splitted[0]) > data1.append(splitted[1]) > for k in data: > if k in data1: > result.append(k) > print result > fh.close() > > can you tell me problem with my script and what should is do for this For a start, you are iterating k in data *everytime* you iterate a line in fh which will give you a speed issue and give you duplicates in the result. The following is probably what you intended to do > for line in fh.readlines(): > do stuff > for k in data: > do stuff .split() splits by spaces, newlines AND tabs so you just need > splitted = line.split() eg >>> ln = 'fhl1\tfkh2\r\n' >>> ln.split() ['fhl1', 'fkh2'] I think I would have done something like this (not tested) Input = open('sheet1').read().split() data = set(Input[::2]) data1 = set (Input[1::2]) result = data.intersection(data1) or even this (if you don't need data and data1 later in the code) Input = open('sheet1').read().split() result = set(Input[::2]).intersection(set (Input[1::2])) HTH :) From rjp at ca.inter.net Fri Aug 10 12:40:41 2007 From: rjp at ca.inter.net (rjp at ca.inter.net) Date: Fri, 10 Aug 2007 09:40:41 -0700 Subject: (Re)announcing APL 2007 In-Reply-To: <1186406430.744134.298400@x35g2000prf.googlegroups.com> References: <5hnkb3F3hus4jU1@mid.individual.net> <1186406430.744134.298400@x35g2000prf.googlegroups.com> Message-ID: <1186764041.534462.156660@e9g2000prf.googlegroups.com> On Aug 6, 9:20 am, Paul Mansour wrote: > APL2007 Roll Call: Is anyone going to this? > > I'm thinking about going, but I don't want to the only one to show up, > as in San Diego. Here here. Sorry to mention the elephant in the room, but this discussion begs the obvious question: what is the rationale for putting on this conference? Perhaps I missed that discussion, and if so, please excuse me. As we know, there are already two well-attended APL vendor conferences in the world each year, plus several other more local gatherings. Speaking as an APL consultant and product distributor, this puts people in a tough spot, since we now have at least three events to consider travelling to and attending (assuming APL2000 is hosting its usual Florida event this year?). I suppose I should be happy for another opportunity to meet and network with potential APL colleagues and customers, but if it's mainly the same small audience at each event, the costs are hard to justify more than once per year. I don't have any answers to this dilemma yet, but I think it requires a lot more discussion. Just putting on a conference and hoping people attend may, at this point I think, be somewhat counterproductive. ...richard From jzgoda at o2.usun.pl Thu Aug 2 17:20:36 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 02 Aug 2007 23:20:36 +0200 Subject: Determining if file is valid image file In-Reply-To: References: <1186064098.587590.91210@g4g2000hsf.googlegroups.com><1186064275.652416.250540@d55g2000hsg.googlegroups.com><1186065645.879720.27720@q75g2000hsh.googlegroups.com> Message-ID: Terry Reedy napisa?(a): >>>>> Other than installing PIL, is there a "simple" way using Python only >>>>> to determine if a file is a valid image file? > [...] >> Be aware that broken images (i.e. partially downloaded) in many cases >> pass the imghdr.what() test. > > To put it another way, the only way to determine whether a coded file is > valid may be to decode it. And even then, it may be corrupted in the sense > that the decoded version may have artifacts not in the original. I have > seen the latter both in jpeg images and movie DVDs. That's what I mean, images that cann't be read using PIL sometimes are recognized by imghdr.what(), as it happens with "file" too - both of these tools are the identification (not validation) utilities. To be sure the image is "really valid", you have to use some image manipulation program (or library), like ImageMagick (or PIL). Sometimes imghdr.what() is enough, sometimes you need more. ;) -- Jarek Zgoda http://jpa.berlios.de/ From arkanes at gmail.com Wed Aug 8 11:26:51 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 8 Aug 2007 10:26:51 -0500 Subject: Seek the one billionth line in a file containing 3 billion lines. In-Reply-To: <46B9DFCE.7000505@holdenweb.com> References: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> <7xzm12o7o7.fsf@ruckus.brouhaha.com> <1186555297.877273.40540@o61g2000hsh.googlegroups.com> <874pja70p5.fsf@benfinney.id.au> <4866bea60708080658l170bd9eevd86cf58dbc1eddd8@mail.gmail.com> <46B9DFCE.7000505@holdenweb.com> Message-ID: <4866bea60708080826q11889e41need605dc2ac2a0c4@mail.gmail.com> On 8/8/07, Steve Holden wrote: > Chris Mellon wrote: > > On 8/8/07, Ben Finney wrote: > >> Sullivan WxPyQtKinter writes: > >> > >>> On Aug 8, 2:35 am, Paul Rubin wrote: > >>>> Sullivan WxPyQtKinter writes: > >>>>> This program: > >>>>> for i in range(1000000000): > >>>>> f.readline() > >>>>> is absolutely every slow.... > >>>> There are two problems: > >>>> > >>>> 1) range(1000000000) builds a list of a billion elements in memory > >> [...] > >>>> 2) f.readline() reads an entire line of input > >> [...] > >>> Thank you for pointing out these two problem. I wrote this program > >>> just to say that how inefficient it is to use a seemingly NATIVE way > >>> to seek a such a big file. No other intention........ > >> The native way isn't iterating over 'range(hugenum)', it's to use an > >> iterator. Python file objects are iterable, only reading eaach line as > >> needed and not creating a companion list. > >> > >> logfile = open("foo.log", 'r') > >> for line in logfile: > >> do_stuff(line) > >> > >> This at least avoids the 'range' issue. > >> > >> To know when we've reached a particular line, use 'enumerate' to > >> number each item as it comes out of the iterator. > >> > >> logfile = open("foo.log", 'r') > >> target_line_num = 10**9 > >> for (line_num, line) in enumerate(file): > >> if line_num < target_line_num: > >> continue > >> else: > >> do_stuff(line) > >> break > >> > >> As for reading each line: that's unavoidable if you want a specific > >> line from a stream of variable-length lines. > >> > > > > The minimum bounds for a line is at least one byte (the newline) and > > maybe more, depending on your data. You can seek() forward the minimum > > amount of bytes that (1 billion -1) lines will consume and save > > yourself some wasted IO. > > Except that you will have to count the number of lines in that first > billion characters in order to determine when to stop. > True. Perhaps you can tell from the data itself what line you want. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Aug 9 06:16:56 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 09 Aug 2007 12:16:56 +0200 Subject: wxPython before MainLoop References: <13bl9a75laqcm70@corp.supernews.com> Message-ID: <5i07soF3mg0r8U2@mid.individual.net> [david] wrote: > I'd like to refresh the display before I start the main loop. > [...] > I'd like to just make app.Show() finish correctly before running > long_slow_init. IMHO, this will bring no gain. If you see an inresponsive user interface or not is quite meaningless. > Or is there a better idea? As suggested, a solution using threads is feasible. Regards, Bj?rn -- BOFH excuse #422: Someone else stole your IP address, call the Internet detectives! From jantod at gmail.com Tue Aug 14 10:09:34 2007 From: jantod at gmail.com (Janto Dreijer) Date: Tue, 14 Aug 2007 14:09:34 -0000 Subject: Fast kNN from python In-Reply-To: References: <1187086584.076990.260680@r34g2000hsd.googlegroups.com> Message-ID: <1187100574.898103.308060@l70g2000hse.googlegroups.com> On Aug 14, 3:11 pm, Tim Churches wrote: > Janto Dreijer wrote: > > I am looking for a Python implementation or bindings to a library that > > can quickly find k-Nearest Neighbors given an arbitrary distance > > metric between objects. Specifically, I have an "edit distance" > > between objects that is written in Python. > > Orange? Seehttp://www.ailab.si/orange/- not sure about speed, but > quite a few parts of it are written in C, and it does kNN. > > Tim C Thanks, but I'm actually thinking of "fast" as in computer science terms. e.g. O(log(n)) lookup time. I'll probably have tens of thousands of objects to search and the distance calculation is relatively slow. >From the documentation it looks like Orange does a brute force search for the nearest k items. From rainwatching at gmail.com Thu Aug 30 20:45:43 2007 From: rainwatching at gmail.com (=?iso-8859-9?q?S=F6nmez_Kartal?=) Date: Fri, 31 Aug 2007 00:45:43 -0000 Subject: reload(sys) Message-ID: <1188521143.421431.119100@l22g2000prc.googlegroups.com> Hello, I've had an encoding issue and solved it by "sys.setdefaultencoding('utf-8')"... My first try wasn't successful since setdefaultencoding is not named when I imported sys module. After, I import sys module, I needed to write "reload(sys)" also. I wonder why we need to call "reload(sys)" to get setdefaultencoding named? Happy coding From grflanagan at yahoo.co.uk Wed Aug 29 03:37:15 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: Wed, 29 Aug 2007 00:37:15 -0700 Subject: tempfile.mkstemp and os.fdopen In-Reply-To: <1188323759.955043.317630@19g2000hsx.googlegroups.com> References: <1188323759.955043.317630@19g2000hsx.googlegroups.com> Message-ID: <1188373035.437896.179590@o80g2000hse.googlegroups.com> On Aug 28, 7:55 pm, billiejoex wrote: > Hi there. > I'm trying to generate a brand new file with a unique name by using > tempfile.mkstemp(). > In conjunction I used os.fdopen() to get a wrapper around file > properties (write & read methods, and so on...) but 'name' attribute > does not contain the correct file name. Why? > import tempfile, os class TempFile(object): def __init__(self, fd, fname): self._fileobj = os.fdopen(fd, 'w+b') self.name = fname def __getattr__(self, attr): return getattr(self._fileobj, attr) def mktempfile(dir=None, suffix='.tmp'): return TempFile(*tempfile.mkstemp(dir=dir, suffix=suffix)) From antroy at gmail.com Wed Aug 1 11:16:11 2007 From: antroy at gmail.com (Ant) Date: Wed, 01 Aug 2007 08:16:11 -0700 Subject: Where do they tech Python officialy ? In-Reply-To: References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> <1185265091.276958.239910@r34g2000hsd.googlegroups.com> <1i23wyk.avc945i4dwsiN%aleax@mac.com> Message-ID: <1185981371.536594.316890@b79g2000hse.googlegroups.com> On Aug 1, 9:40 am, Alex Popescu wrote: ... > It depends :-). In my experience I met employers being concerned by my > implication in the oss world :-). I have the opposite experience. It was predominantly the fact that I was involved in several open source projects that got me into professional development 3 years ago. The employers in the market at the time required 2 years+ of commercial experience - the fact that I was involved in OSS helped on two counts, firstly that it showed that I actually have an interest in development (rather than being another Comp Sci graduate just after a wage), and secondly that I have experience in good development practice (the open source projects I worked on had better infrastructure in place than two of the three companies I've worked for since!) -- Ant... http://antroy.blogspot.com/ From nytrokiss at gmail.com Wed Aug 1 18:46:54 2007 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 1 Aug 2007 15:46:54 -0700 Subject: Wing IDE for Python v. 3.0 beta1 released In-Reply-To: References: <46AF8ED7.2070206@wingware.com> <20070801212840.GA25065@spookie1.spookiegate> <496954360708011453h2a68dee4x48dcb15bb25ea717@mail.gmail.com> Message-ID: <8a6b8e350708011546u348c293co9131da887f9f08f5@mail.gmail.com> I am very happy with there support i concur with what Joshua wrote! I have yet to see a full paying consumer not happy with wingide On 8/1/07, Steve Holden wrote: > > Joshua J. Kugler wrote: > > On Wednesday 01 August 2007 13:53, Robert Dailey wrote: > >> He's secretly an employee of Wing IDE in disguise!!! > > > > Sorry to destroy your conspiracy theories, but no, I've never been > employed > > by Wing IDE in any fashion, nor have I ever received any monetary > > compensation from them in any form. Just a satisfied user. That's all. > > > > j > > > Me too, and I have to say the response I have had to all my technical > support requests has been first-class. Maybe they are busy because > they're in beta? I know they aren't the largest company, but they can > stand comparison with most when it comes to support. > > I can't think of any other products I use where you can contact the > support team from right inside the software. And get answers without > paying per-incident support fees! > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Thu Aug 9 21:13:39 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 10 Aug 2007 11:13:39 +1000 Subject: Puzzled by "is" References: <20070809194105.39BD11E400A@bag.python.org> Message-ID: <87zm1042f0.fsf@benfinney.id.au> Grzegorz S?odkowicz writes: > That's just theorisation but I'd rather expect the interpreter > simply not to create a second tuple while there already is an > identical one. Others have already said that it's an implementation optimisation, which seems to partly answer your question. It's important to also realise that the language is *deliberately* non-committal on whether any given value will have this behaviour; that is, it's entirely left to the language implementation which optimisation trade-offs to make, and the language user (that's you and I) should *not* expect any particular behaviour to hold between different implementations. -- \ "Holy priceless collection of Etruscan snoods, Batman!" -- | `\ Robin | _o__) | Ben Finney From steve at holdenweb.com Fri Aug 17 19:03:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 17 Aug 2007 19:03:33 -0400 Subject: advice about `correct' use of decorator In-Reply-To: <46C5C9AE.5020508@fmed.uba.ar> References: <46C4B097.4080309@fmed.uba.ar> <740c3aec0708170529s6f7e7fe2l8c92771c2d0a51d4@mail.gmail.com> <46C5C9AE.5020508@fmed.uba.ar> Message-ID: Gerardo Herzig wrote: [...] > As far as i know (by the way, AFAK is the shortcut? [...] That's "AFAIK", AFAIK :-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From larry.bates at websafe.com Thu Aug 9 15:02:14 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 09 Aug 2007 14:02:14 -0500 Subject: how to get output. In-Reply-To: <1186646135.742185.5280@x35g2000prf.googlegroups.com> References: <5hvrhhF3m15c7U1@mid.uni-berlin.de> <1186645852.687961.323420@x35g2000prf.googlegroups.com> <1186646135.742185.5280@x35g2000prf.googlegroups.com> Message-ID: <46BB64B6.1000303@websafe.com> indu_shreenath at yahoo.co.in wrote: > I corrected a typ below. > > On Aug 9, 12:50 pm, indu_shreen... at yahoo.co.in wrote: >> Hey, >> >> I did write the following: >> but it does not work. >> >> import subprocess as sp >> try: >> p = sp.Popen("DIR . /AD /B", stdout=sp.PIPE) >> result = p.communicate()[0] >> print result >> except: >> print "error" >> >> This throws error. >> DIR . /AD /B will list out only directories in the current directory. >> >> Thanks, >> Indu >> >> On Aug 9, 11:46 am, "Diez B. Roggisch" wrote: >> >> >> >>> indu_shreenath schrieb: >>>> Hey, >>>> I want to get the output of "DIR /AD /B" command to a varriable using >>>> python. How can I do this? >>> Using the subprocess-module. >>> However, I'm not sure what DIR /AD /B does - but there are many >>> functions in module os that might deliver what you want without invoking >>> an external command. >>> Diez- Hide quoted text - >> - Show quoted text - > > That is better done in python with: import os dirs=[d for d in os.listdir(os.curdir) if os.path.isdir(d)] or dirs=filter(os.path.isdir, os.listdir(os.curdir)) -Larry From danmcleran at yahoo.com Wed Aug 15 15:38:32 2007 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: Wed, 15 Aug 2007 12:38:32 -0700 Subject: threads, mutual exclusion, and lists In-Reply-To: <1187206583.255588.57920@e9g2000prf.googlegroups.com> References: <1187206583.255588.57920@e9g2000prf.googlegroups.com> Message-ID: <1187206712.725247.14650@x35g2000prf.googlegroups.com> On Aug 15, 1:36 pm, Scott wrote: > I have two threads that share a python list. One thread adds to the > list with append(), the other thread removes items with pop(). > > My question is -- are python list operations atomic? If they are not, > then I assume I need to put some mutual exclusion around the append() > and pop() calls ? > > Thanks, > Scott You might want to consider using a Queue instead. It is designed to be thread-safe. From arkanes at gmail.com Wed Aug 22 12:31:32 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 22 Aug 2007 11:31:32 -0500 Subject: IDE for Python In-Reply-To: <46CBBCB1.9060604@chem.byu.edu> References: <1187698999.545439.322600@k79g2000hse.googlegroups.com> <46CB81FD.5070101@bigfoot.com> <46CBBCB1.9060604@chem.byu.edu> Message-ID: <4866bea60708220931s6b424cd1u6c3f3d9df9dec800@mail.gmail.com> On 8/21/07, Michael L Torrie wrote: > Ricardo Ar?oz wrote: > > Hi, > > Do you know if for in-house development a GPL license applies? (Qt4 > > and/or Eric4). > > If your programs are used in-house and never released, then you don't > have to abide by the terms of the GPL. Slight clarification. You have to abide by the terms of the GPL no matter what, but the terms of the GPL (might) not cover in-house distribution. The idea that "in-house" distribution isn't distribution and doesn't invoke copyright claims is purely the opinion of the FSF, isn't explicitly stated in the GPL, (maybe in GPL 3? I haven't been keeping up) and isn't supported by case law. This means that people who distribute under the GPL but do not agree with the FSFs definition of "distribute" may have a problem with in-house development that doesn't obey the GPL. As a final note, *using* Eric or any other application written in Qt/PyQt doesn't have any effect on you - this only matters if you are writing your own applications using Qt. As a doubly final note, this isn't legal advice, I'm not a lawyer, ask lawyers, not the internet, for legal advice, etc, etc. From stefan at 3niemann.de Wed Aug 29 16:53:16 2007 From: stefan at 3niemann.de (Stefan Niemann) Date: Wed, 29 Aug 2007 22:53:16 +0200 Subject: Haskell like (c:cs) syntax References: <1188349012.502720.296440@x40g2000prg.googlegroups.com> Message-ID: Thanks for all the good answers. In fact the `Extended Iterable Unpacking' is exactly what I was looking for. Ok, my main aspect of writing head, *tail = seq instead of head, tail = seq[0], seq[1:] is the syntactic sugar. As mentioned in the PEP this may also be faster when iterables are involved. Stefan "Matimus" schrieb im Newsbeitrag news:1188349012.502720.296440 at x40g2000prg.googlegroups.com... >> Is there a pattern matching construct in Python like (head : tail), >> meaning >> 'head' matches the first element of a list and 'tail' matches the rest? I >> could not find this in the Python documentation. > > Not really, but you could do something like this: > > [code] > def foo(head, *tail): > #do stuff with head and tail > > foo(*seq) > [/code] > > Also, Python 3.0 will have `Extended Iterable Unpacking' > http://www.python.org/dev/peps/pep-3132/ > > This isn't quite the same as Haskell's type matching, but would enable > similar behavior in some cases. > > example: > [code] > head, *tail = seq > [/code] > > Which would assign the first element of seq to head, and the remainder > to tail. > > Matt > From steve.morin at gmail.com Thu Aug 9 20:26:54 2007 From: steve.morin at gmail.com (Steve) Date: Fri, 10 Aug 2007 00:26:54 -0000 Subject: High performance binary data Message-ID: <1186705614.728812.284460@j4g2000prf.googlegroups.com> I want to ready binary data from a udp socket effeciently as possible in python. I know of the struct package but do people have any tips when dealing with binary data in python? Is there a library or api that is faster when dealing with binary data. I am looking for a any one with experience or ideas on the subject. Pointers any one? Thanks Steve From michael at jedimindworks.com Wed Aug 15 04:55:50 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Wed, 15 Aug 2007 01:55:50 -0700 Subject: curses library In-Reply-To: <20070814211043.286b8aa6.ghirai@ghirai.com> References: <20070814211043.286b8aa6.ghirai@ghirai.com> Message-ID: <0850B9D2-307D-46A7-B5DD-16B4491B9A98@jedimindworks.com> On Aug 14, 2007, at 11:10 AM, Ghirai wrote: > I need to write a console application. > > Are there any wrappers around curses/ncurses? > Or any other similar libraries? It looks like Curses Tk still exists: http://www.schwartzcomputer.com/ tcl-tk/tcl-tk.html It probably requires a recompile of Tk and maybe Python but may allow for the same code to work as console and gui? If it works that way, that's a plus for Tkinter... regards, Michael --- Simplicity is the ultimate sophistication. -Leonardo da Vinci From arnau at ehas.org Thu Aug 23 03:33:57 2007 From: arnau at ehas.org (Arnau Sanchez) Date: Thu, 23 Aug 2007 09:33:57 +0200 Subject: How do I get the current path of my python file that is currently running. In-Reply-To: References: Message-ID: <46CD3865.9060403@ehas.org> Lamonte Harris escribi?: > Say I start i click on a python file on my desktop, how could I return > the path of the current python file thats running? http://docs.python.org/lib/module-sys.html From amccabe at hawkeyerec.com Tue Aug 14 08:30:25 2007 From: amccabe at hawkeyerec.com (Tony) Date: Tue, 14 Aug 2007 07:30:25 -0500 Subject: Script to copy database Message-ID: I'm new at this and would like to know how set up a script to copy a database from a local computer to a network at a certain time everyday. Should be simple enough, but, as of now I am unfamiliar with how to do this. Would this be done by writing a script and setting up a scheduled task to run the script? Can anyone help me with the script? Just need it to copy an Access database from the local C: drive to a network F: drive. Thanks, Tony From richardjones at optushome.com.au Thu Aug 9 18:06:46 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Fri, 10 Aug 2007 08:06:46 +1000 Subject: Querying Graphics Card Name References: <1186686984.160312.175270@i13g2000prf.googlegroups.com> Message-ID: <46bb8ff6$0$25982$afc38c87@news.optusnet.com.au> Benjamin Goldenberg wrote: > I would like to find out the name of the graphics card of the machine > my program is running on. I have looked into the pyopengl module, and > using them to query the card, but it seems like there ought to be a > simpler way to find this out without setting up a glcontext. Does > anyone have any ideas? You need a context if you're going to ask OpenGL to tell you what the card is. To find out any other way would be highly platform-specific, possibly though looking in the /proc directory on Linux, and who-knows-where-else on other platforms. Also, have a look at tools/info.py in the pyglet project Richard From arnau at ehas.org Sat Aug 18 15:18:29 2007 From: arnau at ehas.org (Arnau Sanchez) Date: Sat, 18 Aug 2007 21:18:29 +0200 Subject: sort dictionary by specific values In-Reply-To: References: Message-ID: <46C74605.6060200@ehas.org> dorje tarap escribi?: > 2. > {8: (99, 99), 9: [(55, 67), (77, 66), (67, 88)], 4: [(45, 78), > (56, 78), (99, 78)], 5: (67, 77)} > > > I want to sort the entire dictionary based on the last values in each > line. First for [-1][0] and then[-1][0] Each "line" means each value in the dictionary? Did you mean ordering [-1][0] and then [-1][1]? Dictionaries cannot be ordered, but you can work with its items (as a list). Your data is not homogeneous (values in the dictionary are both tuples and list of tuples). If you can build it that way: d = {8: [(99, 99)], 9: [(55, 67), (77, 66), (67, 88)], 4: [(45, 78), (56, 78), (99, 78)], 5: [(67, 77)] It would be easy to sort: import operator cmplast = lambda x, y: cmp(x[-1], y[-1]) sorted(d.items(), key=operator.itemgetter(1), cmp=cmplast, reverse=True) or cmplast1 = lambda x, y: cmp(x[1][-1], y[1][-1]) sorted(d.items(), cmp=cmplast1, reverse=True) [(8, [(99, 99)]), (4, [(45, 78), (56, 78), (99, 78)]), (9, [(55, 67), (77, 66), (67, 88)]), (5, [(67, 77)])] From mensanator at aol.com Mon Aug 27 14:38:24 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 27 Aug 2007 11:38:24 -0700 Subject: convert non-delimited to delimited In-Reply-To: <13d66b6b0fnke49@corp.supernews.com> References: <1188237563.889663.228970@o80g2000hse.googlegroups.com> <13d66b6b0fnke49@corp.supernews.com> Message-ID: <1188239904.282306.90690@k79g2000hse.googlegroups.com> On Aug 27, 1:35 pm, Mark Elston wrote: > * RyanL wrote (on 8/27/2007 10:59 AM): > > > > > > > I'm a newbie! I have a non-delimited data file that I'd like to > > convert to delimited. > > > Example... > > Line in non-delimited file: > > 0139725635999992000010100534+42050-102800FM-15+1198KAIA > > > Should be: > > 0139,725635,99999,2000,01,01,00,53,4,+42050,-102800,FM-15,+1198,KAIA > > > What is the best way to go about this? I've looked all over for > > examples, help, suggestions, but have not found much. CSV module > > doesn't seem to do exactly what I want. Maybe I'm just missing > > something or not using the correct terminology in my searches. Any > > assistance is greatly appreaciated! Using Python 2.4 > > Since you have to know, a priori, how to break the input string I > assume that these fields are of fixed length. You can use the following > to do what you want: > > >>> a="0139725635999992000010100534+42050-102800FM-15+1198KAIA" > >>> print "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s" % > (a[0:4],a[4:10],a[10:15],a[15:19],a[19:21],a[21:23],a[23:25], > a[25:27],a[27],a[28:34],a[34:41],a[41:46],a[46:51],a[51:]) > > which results in the following output: > > 0139,725635,99999,2000,01,01,00,53,4,+42050,-102800,FM-15,+1198,KAIA > > Mark Or try this: import struct test = '0139725635999992000010100534+42050-102800FM-15+1198KAIA' template = '4s6s5s4s2s2s2s2s1s6s7s5s5s4s' the_line = struct.unpack(template,test) print the_line print ','.join(the_line) ## ('0139', '725635', '99999', '2000', '01', '01', '00', '53', '4', '+42050', '-102800', 'FM-15', '+1198', 'KAIA') ## ## 0139,725635,99999,2000,01,01,00,53,4,+42050,-102800,FM-15,+1198,KAIA From pyth0nc0d3r at gmail.com Tue Aug 28 11:47:49 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Tue, 28 Aug 2007 09:47:49 -0600 Subject: Asking all python programmers. In-Reply-To: <2dc0c81b0708280822t70bf0528s4f80fe926cbb91bf@mail.gmail.com> References: <2dc0c81b0708280822t70bf0528s4f80fe926cbb91bf@mail.gmail.com> Message-ID: I completely understand, I've sent this email when I was tired sorry for the misunderstanding, yes I completely understand what you mean how professionals won't take me serious in situations like this. How about I readdress my question for you? Hello everyone on python mailing list. I would like your input on what information about python programming language that I should study the most. Some tutorials are good, but the manual is main resource even if it isn't well documented J. On a friendly note I would like to hear what you guys would have to recommend if that is ok. From a python starter, I don't like the word noob because it sounds very unprofessional. -Lamonte On 8/28/07, Shawn Milochik wrote: > > On 8/27/07, Lamonte Harris wrote: > > Okay, I know you've guys told me millions of times to read the manual > I've > > read a lot of it. What do you recommend studying the most? Python is my > > goal for the next year in the half. :) > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > Some notes on your question: > > "You've guys" is nonsensical. > Your first sentence is a run-on sentence. > Your e-mail address identifies you as an immature script-kiddie. > "Year in the half" is nonsensical. > > Okay, so why am I "picking on you"? Because I want to help. Present > yourself in this way, and you're not going to get as much help from > intelligent people as you would if they saw you were worth their time. > > You are either going to get angry at me or you're going to think about > this. If you're angry then I can't help you. If you actually care how > people see you, you will get further in life in general. > > To answer the question I think you were trying to ask, a combination > of "The Python Cookbook" and "Dive Into Python" should get you started > in doing amazing things with Python. The latter is available for free > online. > > Take some pride in the way you write. It will pay off. > > Shawn > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Mon Aug 6 14:39:59 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 06 Aug 2007 18:39:59 -0000 Subject: wxWindows - incorrect path on installation? In-Reply-To: <1186422861.132899.50060@g4g2000hsf.googlegroups.com> References: <1186422861.132899.50060@g4g2000hsf.googlegroups.com> Message-ID: <1186425599.377867.156410@g12g2000prg.googlegroups.com> On Aug 6, 12:54 pm, frikk wrote: > This should be a very simple one, sorry! > > I installed wxWindows on my OS X box but I am unable to get my python > install to recognize the module. Unfortunately I don't know a whole > lot about where modules install to or how to configure python to see > them. IE: 'import wx' does not work - it says unknown module wx. > > Do I need to tweak a path variable or something? > > I have MacPython installed and the binary of wxWindows (wxPython) from > wxpython.com > > Thanks guys, > Blaine Check you version of Python. Update if needed and then go here for your specific version: http://pythonmac.org/packages/ The wxPython website also talks about how to install wxPython on Macs. See http://www.wxpython.org/download.php Mike From carsten at uniqsys.com Sat Aug 4 15:23:48 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 04 Aug 2007 15:23:48 -0400 Subject: Encoding DeprecationWarning In-Reply-To: <1186254427.792114.173170@q75g2000hsh.googlegroups.com> References: <1186254427.792114.173170@q75g2000hsh.googlegroups.com> Message-ID: <1186255428.3385.26.camel@dot.uniqsys.com> On Sat, 2007-08-04 at 12:07 -0700, oliver at obeattie.com wrote: > Hey There, > > Sorry if I am missing something here, but I get a DeprecationWarning > when importing a list which has some unicode characters in it Please copy and paste the full text of the warning. -- Carsten Haese http://informixdb.sourceforge.net From cjw at sympatico.ca Thu Aug 16 17:33:43 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 16 Aug 2007 17:33:43 -0400 Subject: sub-classing the types in the builtin module datetime In-Reply-To: <1187294329.082872.230800@l22g2000prc.googlegroups.com> References: <1187294329.082872.230800@l22g2000prc.googlegroups.com> Message-ID: <46C4C2B7.6000701@sympatico.ca> attn.steven.kuo at gmail.com wrote: > On Aug 15, 5:54 pm, "Colin J. Williams" wrote: >> I posted this about 5 hours ago, but it seems to have gone astray. > > > (snipped) > >> > >> >> I wish to sub-class (if that's the right word) datetime and to use a >> >> different signature for the constructor. >> >> >> >> The second part has gone smoothly, but it is difficult to access the >> >> type's methods from the sub-class instance. >> >> >> >> I'm beginning to wonder whether it might might be simpler to write my >> >> own Date class. >> >> >> >> Does anyone have any comments please? >> >> >> >> Colin W. > > (snipped) > > >> Yes, I should have posted an example, but I thought that others might >> have experienced the problem. >> >> It is illustrated at the bottom of this script: >> >> # subClassing.py >> >> import datetime >> import new >> import sys >> import types >> >> class Date(datetime.datetime): >> ''' Date(s) -> a date object.__class__ >> where s is an 8 digit string''' >> >> def __new__(cls, YYmmdd): >> ''' YYmmdd is a string, in the form yyyymmdd i.e. 8 digits. >> or a 3-tuple of integers in the form (y, m, d) >> or a 6-tuple of integers in the form (y, m, d, h, m, >> s) ''' > > > (snipped) > >> a= datetime.datetime(2007, 7, 31) >> d= Date('20070731') >> tm= datetime.time(1, 2) >> try: >> print a.today() >> # print d.today() # grief >> print a.now() >> # print d.now() # grief >> print a.combine(a, tm) # OK, but why not a.combine(tm)? >> # e= d.combine(d, tm) # grief >> print a.utcnow() >> # print d.utcnow() # grief >> print a.ctime() >> print d.ctime() >> except: >> print 'Grief' >> print sys.exc_info() >> >> Colin W. > > > > > > This problem arises when you change the function signature of __new__. > I'm a little unclear as to why but it seems for the classmethods > (thosed marked with the METH_CLASS flag in the C source code), you > need to arrange to bypass the normal method resolution (I used a > metaclass > to do this): > > > > import datetime > > class Date(datetime.datetime): > pass > > class FixClassMethods(type): > def __init__(cls, classname, bases, classdict): > # add strptime if using Python 2.5 > flagged_as_meth_class = ('today', 'now', 'fromtimestamp', > 'fromordinal', 'now', 'utcnow', 'utcfromtimestamp', 'combine') > for meth in flagged_as_meth_class: > setattr(cls, meth, getattr(datetime.datetime, meth)) > > class DateChangesNewSignature(datetime.datetime): > @staticmethod > def str2ymd(strval): > yyyy, mm, dd = (int(substr) for substr in (strval[:4], > strval[4:6], strval[6:])) > return yyyy, mm, dd > > def __new__(cls, strval): > yyyy, mm, dd = DateChangesNewSignature.str2ymd(strval) > return super(DateChangesNewSignature,cls).__new__(cls, yyyy, > mm, > dd) > def __init__(self, strval): > yyyy, mm, dd = DateChangesNewSignature.str2ymd(strval) > super(DateChangesNewSignature, self).__init__(yyyy, mm, > dd) > > class DLast(DateChangesNewSignature): > __metaclass__ = FixClassMethods > > f = Date(2007,07,07) > print f > print f.today() > > f2 = DateChangesNewSignature("20070707") > print f2 > try: > print f2.today() > except TypeError, e: > print str(e) > print "Uh?" > > > f3 = DLast("20070707") > print f3 > print f3.today() > > > I get: > > 2007-07-07 00:00:00 > 2007-08-16 12:57:41.480679 > 2007-07-07 00:00:00 > __new__() takes exactly 2 arguments (9 given) > Uh? > 2007-07-07 00:00:00 > 2007-08-16 12:57:41.483104 > > > -- > Hope this helps, > Steven > Steven, Many thanks, I'll try this out tomorrow. Colin W From max at alcyone.com Sun Aug 12 20:15:41 2007 From: max at alcyone.com (Erik Max Francis) Date: Sun, 12 Aug 2007 17:15:41 -0700 Subject: Fatest standard way to sum bytes (and their squares)? In-Reply-To: <87r6m8egee.fsf@mulj.homelinux.net> References: <87r6m8egee.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: > For ordinalSum, using imap is almost twice as fast: > > $ python -m timeit -s 'data=[chr(x) for x in xrange(256)]' 'sum(ord(x) for x in data)' > 10000 loops, best of 3: 92.4 usec per loop > $ python -m timeit -s 'data=[chr(x) for x in xrange(256)]; from itertools import imap' 'sum(imap(ord, data))' > 10000 loops, best of 3: 55.4 usec per loop You're using data which is a list of chars (strings), rather than a string itself, which is what the format is in. The imap optimization doesn't appear to work quite as dramatically well for me with strings instead of lists, but it certainly is an improvement. > Of course, that optimization doesn't work for the squared sum; using a > lambda only pessimizes it. Right. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis Experience is the name everyone gives to their mistakes. -- Oscar Wilde From jstroud at mbi.ucla.edu Tue Aug 21 04:42:09 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 21 Aug 2007 01:42:09 -0700 Subject: searching dict key with reqex In-Reply-To: <1187684878.123427.42230@x35g2000prf.googlegroups.com> References: <1187684878.123427.42230@x35g2000prf.googlegroups.com> Message-ID: <9uxyi.4416$i75.564@newssvr19.news.prodigy.net> james_027 wrote: > hi, > > can I use regex instead of a plain string with this kind of syntax ... > > 'name' in a_dictionary > > something like > > r'name_\D+' in a_dictionary? > > Thanks > james > This makes it a one-liner: import re def rgxindict(rgx, adict): return any(re.match(rgx,k) for k in adict) James From jjl at pobox.com Tue Aug 21 17:36:53 2007 From: jjl at pobox.com (John J. Lee) Date: Tue, 21 Aug 2007 21:36:53 GMT Subject: urllib2.urlopen(url) pulling something other than HTML References: <1187635452.841155.88720@a39g2000hsc.googlegroups.com> <1187641080.516885.122350@g4g2000hsf.googlegroups.com> Message-ID: <87ejhwr2mi.fsf@pobox.com> Gabriel Genellina writes: [...] > Don't even try to understand it - it's a mess. Use the HTMLParser > module instead. [...] Module sgmllib (and therefore module htmllib also) is more tolerant of bad HTML than module HTMLParser. John From pavlovevidence at gmail.com Fri Aug 31 03:03:24 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 31 Aug 2007 03:03:24 -0400 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> <1188534061.243009.89640@m37g2000prh.googlegroups.com> Message-ID: <46d7c06c$0$19633$4c368faf@roadrunner.com> On Fri, 31 Aug 2007 01:15:04 -0400, Roy Smith wrote: > Carl Banks wrote: >> Python really isn't suitable for in-flight controls for various >> reasons, and mission critical concerns is a minor one (systems with >> less underlying complexity tend to have fewer failure modes). But >> mostly it's raw throughput: Python is just too slow. Flight control >> computers have to be powerful enough make a ton of mathematical >> calculations in a matter of milliseconds, and under strict weight and >> power constraints. The cost of running 100 times slower than optimal >> is just too high. > > I'm not convinced that's true for all avionics uses. Of course it's not. I was talking about flight control, not avionics in general. (Perhaps when single-engine Cessnas go digital we'll even see flight controllers in Python.) Carl Banks From bill.scherer at verizonwireless.com Thu Aug 9 13:46:53 2007 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Thu, 09 Aug 2007 13:46:53 -0400 Subject: Puzzled by "is" In-Reply-To: References: Message-ID: <46BB530D.8080308@verizonwireless.com> Dick Moores wrote: > >>> () is () > True > >>> (1,) is (1,) > False > > Why? > >>> a = () >>> b = () >>> c = (1,) >>> d = (1,) >>> a is b True >>> c is d False >>> id(a) 3086553132 >>> id(b) 3086553132 >>> id(c) 3086411340 >>> id(d) 3086390892 There is only one empty tuple. Does that clear it up for you? > Thanks, > > Dick Moores > > From carsten at uniqsys.com Thu Aug 30 15:08:08 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 30 Aug 2007 15:08:08 -0400 Subject: list index() In-Reply-To: <1188499525.827573.128170@x35g2000prf.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <46d674c2$0$417$426a34cc@news.free.fr> <1188496588.750629.208100@g4g2000hsf.googlegroups.com> <1188498073.997168.282420@q5g2000prf.googlegroups.com> <1188499525.827573.128170@x35g2000prf.googlegroups.com> Message-ID: <1188500888.11738.4.camel@dot.uniqsys.com> On Thu, 2007-08-30 at 11:45 -0700, zzbbaadd at aol.com wrote: > > That wish will only come true if you maintain your own fork of Python 3. > > has_key() will go away, period. It has been made obsolete by "in", which > > is faster and more concise. > > Is there really some reason "key" IN dict can be implemented faster > than dict.has_key("key")??? Yes, see e.g. http://groups.google.com/group/comp.lang.python/msg/03e9b4276846b9c0 -- Carsten Haese http://informixdb.sourceforge.net From cjw at sympatico.ca Fri Aug 17 17:32:09 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 17 Aug 2007 17:32:09 -0400 Subject: sub-classing the types in the builtin module datetime In-Reply-To: <1187294329.082872.230800@l22g2000prc.googlegroups.com> References: <1187294329.082872.230800@l22g2000prc.googlegroups.com> Message-ID: <46C613D9.5070009@sympatico.ca> attn.steven.kuo at gmail.com wrote: [My question snipped] > > > > This problem arises when you change the function signature of __new__. > I'm a little unclear as to why but it seems for the classmethods > (thosed marked with the METH_CLASS flag in the C source code), you > need to arrange to bypass the normal method resolution (I used a > metaclass > to do this): > > > > import datetime > > class Date(datetime.datetime): > pass > > class FixClassMethods(type): > def __init__(cls, classname, bases, classdict): > # add strptime if using Python 2.5 > flagged_as_meth_class = ('today', 'now', 'fromtimestamp', > 'fromordinal', 'now', 'utcnow', 'utcfromtimestamp', 'combine') > for meth in flagged_as_meth_class: > setattr(cls, meth, getattr(datetime.datetime, meth)) > > class DateChangesNewSignature(datetime.datetime): > @staticmethod > def str2ymd(strval): > yyyy, mm, dd = (int(substr) for substr in (strval[:4], > strval[4:6], strval[6:])) > return yyyy, mm, dd > > def __new__(cls, strval): > yyyy, mm, dd = DateChangesNewSignature.str2ymd(strval) > return super(DateChangesNewSignature,cls).__new__(cls, yyyy, > mm, > dd) > def __init__(self, strval): > yyyy, mm, dd = DateChangesNewSignature.str2ymd(strval) > super(DateChangesNewSignature, self).__init__(yyyy, mm, > dd) > > class DLast(DateChangesNewSignature): > __metaclass__ = FixClassMethods > > f = Date(2007,07,07) > print f > print f.today() > > f2 = DateChangesNewSignature("20070707") > print f2 > try: > print f2.today() > except TypeError, e: > print str(e) > print "Uh?" > > > f3 = DLast("20070707") > print f3 > print f3.today() > > > I get: > > 2007-07-07 00:00:00 > 2007-08-16 12:57:41.480679 > 2007-07-07 00:00:00 > __new__() takes exactly 2 arguments (9 given) > Uh? > 2007-07-07 00:00:00 > 2007-08-16 12:57:41.483104 > > > -- > Hope this helps, > Steven > Steven, Thanks, you provide an elegant solution to the datetime problem I raised. I like the illustration of metaclass usage you have have given, it's something I have had trouble grasping. You handle the examples I gave. However, on reflection,I feel that ('today', 'now', 'fromtimestamp', 'fromordinal', 'now', 'utcnow', 'utcfromtimestamp', 'combine') are completely inappropriate as methods and that they should have been set up as functions of datetime and not as methods of datetime.datetime. The difficulty I have in adopting your approach is that it would be difficult for the reader to comprehend the code. My feeling is that it should be possible to change a signature using simple Python approaches. I'll puzzle some more. Thanks again. Colin W. From sentientholon at gmail.com Thu Aug 23 10:05:56 2007 From: sentientholon at gmail.com (Frederick Polgardy) Date: Thu, 23 Aug 2007 14:05:56 -0000 Subject: simple spider in python In-Reply-To: <1187876014.845912.236690@e9g2000prf.googlegroups.com> References: <1187876014.845912.236690@e9g2000prf.googlegroups.com> Message-ID: <1187877956.750621.326560@r23g2000prd.googlegroups.com> On Aug 23, 8:33 am, gmcalen... at gmail.com wrote: > Hi everybody, i'm new to the forum so: hello everybody (should I say > "world"?) ^_^ > I'm trying to do a simple spider in python which: > > 1) ask google a query > 2) parse the data > > I'm a python newbie so *any* help would be very, very welcommed. > Thanks in advice! > > cheers! Take a look at the docs for urllib2.urlopen(). The examples should give you most of what you need. From Shawn at Milochik.com Mon Aug 20 10:55:25 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Mon, 20 Aug 2007 10:55:25 -0400 Subject: Newbee Question In-Reply-To: References: Message-ID: <2dc0c81b0708200755v4cd5b2a2h2ed0893745b2615e@mail.gmail.com> #!/usr/bin/env python normalPay = 0.4 overPay = 1.4 normalLimit = 22 def calcPay(numStops): pay = 0 if numStops > normalLimit: pay = overPay * (numStops - normalLimit) numStops = normalLimit return pay + (numStops * normalPay) if __name__ == "__main__": print "Pay for 1 stops: %.2f." % calcPay(1) print "Pay for 10 stops: %.2f." % calcPay(10) print "Pay for 17 stops: %.2f." % calcPay(17) print "Pay for 25 stops: %.2f." % calcPay(25) print "Pay for 30 stops: %.2f." % calcPay(30) print "Pay for 31 stops: %.2f." % calcPay(31) From jantod at gmail.com Tue Aug 14 16:52:28 2007 From: jantod at gmail.com (Janto Dreijer) Date: Tue, 14 Aug 2007 20:52:28 -0000 Subject: Fast kNN from python In-Reply-To: <1187117048.992003.103700@x35g2000prf.googlegroups.com> References: <1187086584.076990.260680@r34g2000hsd.googlegroups.com> <1187117048.992003.103700@x35g2000prf.googlegroups.com> Message-ID: <1187124748.984371.165220@w3g2000hsg.googlegroups.com> On Aug 14, 8:44 pm, Miki wrote: > Hello, > > > I am looking for a Python implementation or bindings to a library that > > can quickly find k-Nearest Neighbors given an arbitrary distance > > metric between objects. Specifically, I have an "edit distance" > > between objects that is written in Python. > > First Google search for "k-Nearest Neighbors python", yieldedhttp://people.revoledu.com/kardi/tutorial/KNN/resources.html which > pointed tohttp://biopython.org/DIST/docs/api/public/Bio.kNN-module.html > > HTH, > -- > Miki http://pythonwise.blogspot.com Thanks. Indeed, I did see that page. Unfortunately biopython's knn does a brute force search for the nearest k and is therefore way too slow. Janto From ttkk1024 at gmail.com Wed Aug 29 23:55:57 2007 From: ttkk1024 at gmail.com (smalltalk) Date: Wed, 29 Aug 2007 20:55:57 -0700 Subject: Jython 2.2 on Ubuntu In-Reply-To: References: <-YOdnW_k3p6Fy0nb4p2dnAA@bt.com> Message-ID: <1188446157.312304.274070@i13g2000prf.googlegroups.com> On Aug 29, 10:50 pm, Neil Wallace wrote: > Thanks Tim, > > I subscribed to the Jython group hosted by sourceforge, and they are a > great bunch of guys/gals. > > Here's what I did to fix my problem. > > 1. removed Jython 2.1 (using Synaptic)jytho > 2. added the following lines (as root) to /etc/profile > # set PATH for Jython > PATH=$PATH:/home/neil/jython2.2 > export PATH > > I had to restart X, that's it solved!! > > Neil > > > > Tim Couper wrote: > > you need to ensure that the correct jython executable is in a directory > > which is on your on your path. > > > I've just successfully test-subscribed to > >https://lists.sourceforge.net/lists/listinfo/jython-users. Maybe you > > could try again. > > > Tim > > > Dr Tim Couper > > CTO, SciVisum Ltd > > >www.scivisum.com > > > Neil Wallace wrote: > >> Hi all, > > >> I am a novice Python/Jython programmer, and Ubuntu user. > > >> Ubuntu still only supports only version 2.1 of Jython. I have used the > >> GUI installer of Jython 2.2, and installed it to the default > >> /root/jython2.2 directory. The install went without issues. > > >> However, typing ............jython --version > >> in a teminal still gives me ........ Jython 2.1 on java (JIT: null) > > >> What else do I need to do? > > >> regards > >> Neil. > > >> p.s. I posted this to the jython group hosted by sourceforge, but it > >> bounced. :-(- Hide quoted text - > > - Show quoted text - you can use eclipse + pydev it is very easy to setup jython or python From vedrandekovic at v-programs.com Tue Aug 7 04:24:14 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Tue, 07 Aug 2007 01:24:14 -0700 Subject: setuptools bbfreeze install egg error Message-ID: <1186475054.223415.9040@l70g2000hse.googlegroups.com> Hello, I was download egg file bbfreeze-0.95.2-py2.4-win32.egg ( for windows of course ),and I have setuptools version 0.6c6 after I try install this with setuptools: $ ez_setup bbfreeze-0.95.2-py2.4-win32.egg Traceback (most recent call last): File "C:\Python24\Lib\site-packages\ez_setup.py", line 226, in ? main(sys.argv[1:]) File "C:\Python24\Lib\site-packages\ez_setup.py", line 183, in main from setuptools.command.easy_install import main File "C:\Python24\Lib\site-packages\setuptools\command \easy_install.py", line 16, in ? from distutils import log,dir_util ImportError: cannot import name log Regards, Vedran From bob at 1776.COM Mon Aug 13 22:10:33 2007 From: bob at 1776.COM (Robert Coe) Date: Mon, 13 Aug 2007 22:10:33 -0400 Subject: Car Air Conditioners References: <1186993120.706804.185590@b79g2000hse.googlegroups.com> Message-ID: On Mon, 13 Aug 2007 08:18:40 -0000, Lepi Duja wrote: : All the informations about car air conditioners can be found on this : website... : : http://car-air-conditioning.blogspot.com/ It's hard to imagine anything more OT in this newsgroup, but FWIW my 2003 Kia has the most powerful air conditioner I've ever seen in an automobile. Bob From jstroud at mbi.ucla.edu Fri Aug 3 20:53:23 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 03 Aug 2007 17:53:23 -0700 Subject: How to pass a reference to the current module In-Reply-To: References: Message-ID: James Stroud wrote: > Basically, what I am trying to acomplish is to be able to do this in any > arbitrary module or __main__: > > > funcname = determined_externally() > ModuleUser.do_something_with(AModule, funcname) > > > Ideally, it would be nice to leave out AModule if the functions were > designed in the same namespace in which do_something_with is called. Is this the preferred way? import sys def do_something_with(funcname, amodule=None): if amodule is None: function = sys._getframe(1).f_locals[funcname] else: function = getattr(amodule, funcname) [etc.] James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From cai.haibin at gmail.com Tue Aug 21 04:27:58 2007 From: cai.haibin at gmail.com (james_027) Date: Tue, 21 Aug 2007 08:27:58 -0000 Subject: searching dict key with reqex Message-ID: <1187684878.123427.42230@x35g2000prf.googlegroups.com> hi, can I use regex instead of a plain string with this kind of syntax ... 'name' in a_dictionary something like r'name_\D+' in a_dictionary? Thanks james From pyscottishguy at hotmail.com Fri Aug 3 12:20:10 2007 From: pyscottishguy at hotmail.com (pyscottishguy at hotmail.com) Date: Fri, 03 Aug 2007 16:20:10 -0000 Subject: Efficient Rank Ordering of Nested Lists In-Reply-To: <1186104049.022836.253470@e9g2000prf.googlegroups.com> References: <1186104049.022836.253470@e9g2000prf.googlegroups.com> Message-ID: <1186158010.322959.47370@g4g2000hsf.googlegroups.com> On Aug 2, 10:20 pm, "pablo.mitch... at gmail.com" wrote: > A naive approach to rank ordering (handling ties as well) of nested > lists may be accomplished via: > > def rankLists(nestedList): > def rankList(singleList): > sortedList = list(singleList) > sortedList.sort() > return map(sortedList.index, singleList) > return map(rankList, nestedList) > > >>> unranked = [ [ 1, 2, 3, 4, 5 ], [ 3, 1, 5, 2, 4 ], [ -1.1, 2.2, > 0, -1.1, 13 ] ] > >>> print rankLists(unranked) > > [[0, 1, 2, 3, 4], [2, 0, 4, 1, 3], [0, 3, 2, 0, 4]] > > This works nicely when the dimensions of the nested list are small. > It is slow when they are big. Can someone suggest a clever way to > speed it up? Isn't there something wrong with the ordering? Pablo's answers are: [ 1, 2, 3, 4, 5 ] == [0, 1, 2, 3, 4] correct [ 3, 1, 5, 2, 4 ] == [2, 0, 4, 1, 3] wrong? [ -1.1, 2.2, 0, -1.1, 13 ] == [0, 3, 2, 0, 4] wrong? Doing it in my head I get: [ 3, 1, 5, 2, 4 ] == [ 1, 3, 0, 4, 2 ] [ -1.1, 2.2, 0, -1.1, 13 ] == [0, 3, 2, 1, 4] What gives? Did I misunderstand what "rank ordering (handling ties as well)" means? From bbxx789_05ss at yahoo.com Thu Aug 9 03:50:07 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 09 Aug 2007 00:50:07 -0700 Subject: wxPython before MainLoop In-Reply-To: <13bl9a75laqcm70@corp.supernews.com> References: <13bl9a75laqcm70@corp.supernews.com> Message-ID: <1186645807.343558.180500@d55g2000hsg.googlegroups.com> On Aug 8, 11:25 pm, "[david]" wrote: > I'd like to refresh the display before I start the main loop. > > I have code like this: > > app = App() > app.Show() > app.long_slow_init() > app.MainLoop() > > The main frame partly loads at Show, but because the mainloop has not > started yet, the display does not update until long_slow_init() finishes. > > Alternatively, I could code > > app = App() > app.long_slow_init() > app.Show() > app.MainLoop() > > Which would give me a crisp Show, but there would be a long slow wait > before the app showed any activity at all. I would need a splash screen. > > I'd rather not have a splash screen (and I don't know how anyway). I'd > like to just make app.Show() finish correctly before running > long_slow_init. > > Is there a wx internal method that I can use to give Windows the > opportunity to finish painting the frame before I run long_slow_init()? > > Or is there a better idea? > > (david) You can use a separate thread to execute long_slow_init(): -------------------------- import wx import threading import time class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "My Window") panel = wx.Panel(self, -1) button = wx.Button(panel, -1, "click me, quick!", pos=(40, 40)) self.Bind(wx.EVT_BUTTON, self.onclick) def onclick(self, event): print "button clicked" def receive_result(self, result): print "Hey, I'm done with that long, slow initialization." print "The result was:", result class MyApp(wx.App): def __init__(self): wx.App.__init__(self, redirect=False) def OnInit(self): the_frame = MyFrame() the_frame.Show() t = MyThread(the_frame) t.start() #calls run() in t's class return True class MyThread(threading.Thread): def __init__(self, a_frame): threading.Thread.__init__(self) self.frame_obj = a_frame def run(self): self.result = self.long_slow_init() def long_slow_init(self): print "starting long_slow_init()..." time.sleep(6) result = 20.5 #Send result to frame: wx.CallAfter(self.frame_obj.receive_result, result) app = MyApp() app.MainLoop() ---------------------------- From mccredie at gmail.com Mon Aug 27 12:28:49 2007 From: mccredie at gmail.com (Matt McCredie) Date: Mon, 27 Aug 2007 09:28:49 -0700 Subject: Image.open( "C:\test.jpg") is this wrong ? In-Reply-To: References: Message-ID: <9e95df10708270928j551c6b84r8fd26001d5d52b5@mail.gmail.com> > Image.open("C:\test.jpg") # this is what I have right now. And it can't > find the file or directory. The file is there (it is everywhere on my > computer now!!!) > > I found some code where they apply the file path to a variable in single > quotes. Is that how it is done. Also I thought single quotes were for > characters not strings. In python there is no difference between single and double quotes. You are close, but the "C:\test.jpg", sees the "\t" as the escape sequence for `tab'. You can generally use three things: "C:\\test.jpg" where "\\" is the escape sequence for a single backslash `\' You can use a raw string: r"C:\test.jpg" which disables escaping. You can use forward slashes "C:/test.jpg", which might look funny but does work. Read more here: http://docs.python.org/tut/node5.html#SECTION005120000000000000000 Matt From claird at lairds.us Wed Aug 15 09:37:16 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 15 Aug 2007 13:37:16 +0000 Subject: Simple python iteration question References: <20070814163430.GJ22017@lass.lfod.us> Message-ID: In article , Shawn Milochik wrote: . . . >Just for my own sanity: Isn't this the third response advocating the >use of enumerate()? Did the other responses not get through, or was >this a time-delay thing? . . . Yes. Yes, for a variety of reasons, it's easy for it to happen that all three-or-more enumerate-responders independently saw the original question, but not any of their colleagues' responses. Sometime we'll tell a few Usenet funnies about The Old Days when transport included tape-backup-driven-by-private-car. From carsten at uniqsys.com Thu Aug 30 14:06:34 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 30 Aug 2007 14:06:34 -0400 Subject: list index() In-Reply-To: <1188495863.242815.236900@o80g2000hse.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188495863.242815.236900@o80g2000hse.googlegroups.com> Message-ID: <1188497194.3468.55.camel@dot.uniqsys.com> On Thu, 2007-08-30 at 10:44 -0700, zzbbaadd at aol.com wrote: > > > > How could it not be an exception, in the plain English sense of the > > word? Most certainly you're asking for the index because you want to do > > something with the index. If the item is not found, you have no index, > > so that's a special case that must be handled separately. There is no > > logical difference between handling that special case in an except > > clause versus handling it with an if-branch. > > In my case of have done os.listdir() on two directories. I want to see > what files are in directory A that are not in directory B. > [...] list.index() is the wrong tool for that job. Python has sets, use them. -- Carsten Haese http://informixdb.sourceforge.net From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Aug 9 17:26:36 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 09 Aug 2007 23:26:36 +0200 Subject: Querying Graphics Card Name References: <1186686984.160312.175270@i13g2000prf.googlegroups.com> Message-ID: <5i1f4cF3mbqqdU1@mid.individual.net> Benjamin Goldenberg wrote: > I would like to find out the name of the graphics card of the > machine my program is running on. I have looked into the pyopengl > module, and using them to query the card, but it seems like there > ought to be a simpler way to find this out without setting up a > glcontext. Does anyone have any ideas? You could execute glxinfo and look for the renderer string. If that's sharp enough for your purpose. Another option is lspci. Regards, Bj?rn -- BOFH excuse #215: High nuclear activity in your area. From http Fri Aug 17 19:20:53 2007 From: http (Paul Rubin) Date: 17 Aug 2007 16:20:53 -0700 Subject: Encryption and hashing References: <1187377630.017794.36510@50g2000hsm.googlegroups.com> <1187392383.237609.97250@19g2000hsx.googlegroups.com> Message-ID: <7x1we1eoiy.fsf@ruckus.brouhaha.com> Kless writes: > So it haven't Twofish, Serpent, neither Whirlpool. Neither many others. Unless you have an interoperability requirement or some other specific issue, you should stick with AES and the SHA2 family. Don't make your own cipher selections unless you know completely what you're doing. This is especially the case for business applications in the US, since AES and SHA are US federal standards and if you use them and something goes wrong with them, you can at least say you followed the standard. If you use anything else, you will have more to answer for. From arkanes at gmail.com Wed Aug 1 13:38:29 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 1 Aug 2007 12:38:29 -0500 Subject: Assertion in list comprehension In-Reply-To: <46b0bb19$0$14060$9b622d9e@news.freenet.de> References: <1185982643.001546.138180@e16g2000pri.googlegroups.com> <46b0bb19$0$14060$9b622d9e@news.freenet.de> Message-ID: <4866bea60708011038h3efec20dl6fe4dbe468970210@mail.gmail.com> On 01 Aug 2007 16:55:53 GMT, Stargaming wrote: > On Wed, 01 Aug 2007 11:28:48 -0500, Chris Mellon wrote: > > > On 8/1/07, beginner wrote: > >> Hi, > >> > >> Does anyone know how to put an assertion in list comprehension? I have > >> the following list comprehension, but I want to use an assertion to > >> check the contents of rec_stdl. I ended up using another loop which > >> essentially duplicates the functions of list comprehension. It just > >> look like a waste of coding and computer time to me. > >> > >> I just wish I could put the assertions into list comprehensions. > >> > >> x=[(rec_stdl[0].st/10000.0, > >> rec_stdl[0].cl, > >> rec_stdl[0].bb, > >> rec_stdl[0].bo, > >> rec_stdl[1].bb, > >> rec_stdl[1].bo, > >> rec_stdl[0].ex > >> ) > >> for rec_stdl in rec_by_ex if len(rec_stdl)==2 > >> ] > >> > >> #duplicated loop > >> if __debug__: > >> for rec_stdl in rec_by_ex: > >> l=len(rec_stdl) > >> assert(l<=2 and l>0) > >> if l==2: > >> assert(rec_stdl[0].c=="C" and rec_stdl[1].c=="P") > >> assert(rec_stdl[0].ex==rec_stdl[1].ex) > >> assert(rec_stdl[0].st==rec_stdl[1].st) > >> assert(rec_stdl[0].cp==rec_stdl[1].cp) > > > > First: All your asserts are wrong. Assert is a statement, not a > > function. These specific ones will behave as expected, but it's easy to > > accidentally write ones that always pass this way. > > Could you come up with an example? I can only think of accidentally > injecting a comma, what would create a (true, in a boolean context) tuple. > > And, well, if you're only using () for readabilty, this might sometimes > look messy when calling assert with the extended syntax:: > > assert(False), "error text" > It's very easy to write this as assert(False, "error text") if you're in the habit of thinking that assert is a function. > Where one could expect the construction of a tuple. > > > Secondly: This is a waste of code, because if __debug__ is not defined > > asserts will be skipped by the compiler. You could use the same loop > > block for both branches. > > Well, the `assert` isn't there for no reason, but if you're serious about > it, `raise` could be better. > > > Thirdly: This sort of testing is precisely what unit tests and/or > > doctests are for. > > Huh? What beginner is doing there seems more like input validation than > testing. Unit or doctests are meant for testing (and in case of doctests, > showing) whether a function works as expected. Not in a big __debug__ block it isn't. > -- > http://mail.python.org/mailman/listinfo/python-list > From __peter__ at web.de Sat Aug 4 06:07:24 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 04 Aug 2007 12:07:24 +0200 Subject: How to pass a reference to the current module References: <7xtzrg3vof.fsf@ruckus.brouhaha.com> Message-ID: James Stroud wrote: > Yes, those were typos. And to be consistent, the whole listing of the > configuration file should be (note: 'doit'->do_something_with): > > [foo] > param1 = float > param2 = 4 > > [option1] > __module__ = UserDefined1 > __function__ = do_something_with > param1 = str > param2 = 30.0 > > [doit] > param1 = float > param2 = float > > [etc.] > > > With the user's main having the following in it: > > from UserDefined1 import some_function > def foo(): [etc.] > def doit(): [etc.] Why don't you just let your userse write def foo(param1=float, param2=4): ... and dump the config file? Alternatively you can devise a decorator @declare(float, int) def foo(param1, param2=4): ... The problem of mapping names to values, be they modules or functions, will magically vanish. Peter From chad at imvu.com Tue Aug 21 03:01:01 2007 From: chad at imvu.com (Chad Austin) Date: Tue, 21 Aug 2007 00:01:01 -0700 Subject: GeneratorExit should derive from BaseException, not Exception In-Reply-To: References: <46CA0EFE.6020103@imvu.com> Message-ID: <46CA8DAD.6060704@imvu.com> Hi Terry, Thank you for your feedback. Responses inline: Terry Reedy wrote: > "Chad Austin" wrote in message > news:46CA0EFE.6020103 at imvu.com... > || try: > | result = yield chatGateway.checkForInvite({'userId': userId}) > | logger.info('checkForInvite2 returned %s', result) > > would not > except GeneratorExit: > solve your problem? Yes, we could add an "except GeneratorExit: raise" clause to every place we currently catch Exception, but I feel like this is one of those things where it's hard to get it right in all places and also hard to cover with unit tests. Instead, we'll have subtle bugs where finally clauses don't run because the GeneratorExit was swallowed. Also, SystemExit and KeyboardInterrupt were made into BaseExceptions for the same reasons as I'm giving. (As I understand it, anyway.) > | except Exception: > > Such catchalls are known to be prone to catch too much > and are therefore not encouraged ;-). > As in 'use at your own risk'. > Guido encourages specific catches just for the reasons you give here. More below: > There was a *long* discussion of the current 2.5 exception hierarchy on > pydev. Search either python.org's or gmane's archive if you want to pursue > this. But I expect the people involved would say much the same as above. I've actually read the background on the exception hierarchy (and agree with it all), especially other suggestions that GeneratorExit derive from BaseException. As I understand it, Guido's objections are threefold: 1) The previous "generators as coroutines" examples were too theoretical: I've wanted GeneratorExit to derive from BaseException for months now, but didn't write this proposal until I actually wrote code that failed in the presence of task cancellation. 2) You should avoid catching everything with except Exception: I think that's too idealistic. Just do a search for try: except: through publicly available Python. :) Sometimes, you really _do_ want to catch everything. When you're making a network request that involves xmlrpclib, urllib2, httplib, etc. you don't actually care what the error was. (Well, except that the exceptions are submitted for automated analysis.) Similarly, when loading a cache file with pickle, I don't care what went wrong, because it's not critical and should not be turned into a crash for the user. (We automatically report exceptions that bubble into the main loop as crashes.) 3) If GeneratorExit escapes from the generator somehow and gets raised in the main loop, then it will bubble out of the application like SystemExit and KeyboardInterrupt would: I think this argument is somewhat specious, because I can't imagine how that would happen. You'd have to store exceptions in your generator and explicitly bubble them out somehow. Our crash handling has to specially handle KeyboardInterrupt and SystemExit anyway, since there are currently non-Exception exceptions, such as strings and custom classes that forgot to derive from Exception, that should count as crashes. I personally can't think of any cases where I would _want_ to handle GeneratorExit. I just want finally: and with: clauses to do the right thing when a task is cancelled. Anyway, I haven't yet encountered any serious bugs due to this yet... I'm just worried that if a task is holding some resource and blocking on something, then the resource won't get released. If this really does come up, then I do have a little bit of python + ctypes that replaces GeneratorExit with ImvuGeneratorExit (deriving from BaseException), but that's not very appealing. Thanks again, -- Chad Austin http://imvu.com/technology From wpdster at gmail.com Thu Aug 9 09:12:51 2007 From: wpdster at gmail.com (Patrick Doyle) Date: Thu, 9 Aug 2007 09:12:51 -0400 Subject: check if regeular expression has results In-Reply-To: <1186664302.050036.302670@g4g2000hsf.googlegroups.com> References: <1186664302.050036.302670@g4g2000hsf.googlegroups.com> Message-ID: On 8/9/07, shahargs at gmail.com wrote: > Hi, > I'm looking for the best way to check if regular expression return > true (it's mean - there is a match). for example, i want "if" that > check if this regular expression: .*born.*to.* has a match. > > What's the way to do that simply? > How about import re re.match(".*born.*to", "This is a test") re.match(".*born.*to.*", "This test was born so that it worked too.") (Try these at the python prompt) The first call to 're.match()' returns 'None' which will fail an if test. The second one returns a match object, which evaluates to TRUE in an if test. --wpd From justin at sevenfiveo.com Sun Aug 5 10:45:54 2007 From: justin at sevenfiveo.com (Justin Donato) Date: Sun, 5 Aug 2007 10:45:54 -0400 Subject: RDF Library / Py 2.5 Message-ID: <200708051445.l75EjwRV023663@mail3.webfaction.com> Hello, Can I install the win32 binaries for the Redland RDF library if I have Python 2.5 installed? The latest .exe that I can find is for Python 2.4. HYPERLINK "http://librdf.org/"http://librdf.org/ (I?m new to Python and this list.) -Justin No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.5.476 / Virus Database: 269.11.4/936 - Release Date: 8/4/2007 2:42 PM -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Fri Aug 31 20:23:23 2007 From: roy at panix.com (Roy Smith) Date: Fri, 31 Aug 2007 20:23:23 -0400 Subject: So what exactly is a complex number? References: <451mq4-les.ln1@ozzie.tundraware.com> <46d89ba9$0$30380$9b4e6d93@newsspool4.arcor-online.net> Message-ID: Wildemar Wildenburger wrote: > Again, that is just one way to interpret them. Complex numbers are not > vectors (at least no moe than real numbers are). OK, let me take a shot at this. Math folks like to group numbers into sets. One of the most common sets is the set of integers. I'm not sure what the formal definition of an integer is, but I expect you know what they are: 0, 1, 2, 3, 4, etc, plus the negative versions of these: -1, -2, -3, etc. The set of integers have a few interesting properties. For example, any integer plus any other integer gives you another integer. Math geeks would say that as, "The set of integers is closed under addition". Likewise for subtraction; any integer subtracted from any other integer gives you another integers. Thus, the set of integers is closed under subtraction as well. And multiplication. But, division is a bit funky. Some integers divided by some integers give you integers (i.e. 6 / 2 = 3), but some done (i.e. 5 / 2 = 2.5). So, now we need another kind of number, which we call reals (please, no nit picking about rationals). Reals are cool. Not only are the closed under addition, subtraction, and multiplication, but division too. Any real number divided by any other real number gives another real number. But, it's not closed over *every* possible operation. For example, square root. If you take the square root of 4.23, you get some real number. But, if you try to take the square root of a negative number, you can't do it. There is no real number which, when you square it, gives you (to use the cannonical example), -1. That's where imaginary numbers come in. The math geeks invented a wonderful magic number called i (or sometimes j), which gives you -1 when you square it. So, the next step is to take an imaginary number and add it to a real number. Now you've got a complex number. There's all kinds of wonderful things you can do with complex numbers, but this posting is long enough already :-) From michele.simionato at gmail.com Mon Aug 13 02:09:43 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 13 Aug 2007 06:09:43 -0000 Subject: decorators - more than just syntactic sugar In-Reply-To: <46be005e$0$13866$ba620e4c@news.skynet.be> References: <46be005e$0$13866$ba620e4c@news.skynet.be> Message-ID: <1186985383.303334.110230@19g2000hsx.googlegroups.com> On Aug 11, 8:30 pm, Helmut Jarausch wrote: > Hi, > > are decorators more than just syntactic sugar in python 2.x and what > about python 3k ? Well, I argued may times that syntactic sugar is important (all Turing complete languages differs by syntactic sugar only) and having or not having a given syntactic sugar makes a difference between writing and not writing a given program. Having decorators in core Python makes us think differently. Have a look at David Mertz article http://www.ibm.com/developerworks/linux/library/l-cpdecor.html Michele Simionato From cajnnjonaj at fjireanjtjprodjuctijons.com Tue Aug 21 11:36:38 2007 From: cajnnjonaj at fjireanjtjprodjuctijons.com (Aaron) Date: Tue, 21 Aug 2007 10:36:38 -0500 Subject: I Need help from all the group participants References: Message-ID: "Boris Ozegovic" wrote in message news:fac7nj$ci9$1 at localhost.localdomain... > Hi, > > I am working on some system, and the communication will take place through > the chatterbot which will be written in AIML (interpreter is written in > Python). English is not my mother tongue, so I need huge favor: if all > of > you can write two sentences, so that I could have greater pattern base. > The first sentence is finding someone's heart rate, example: "Please, can > you tell me John's heart rate", and the other one is setting the alarm > when > someone's heart rate is lower then x, and greater than y, example: "Can > you, please, send me information when John's heart rate is lower than 60, > and greater than 100". You can manipulate time (right now, now, right > this > moment), and everything else you can think about. > Give me John's heart rate. John's heart rate? John's pulse? John's pulse is? (The last three are not exactly complete sentences. Rather they are fragments, but who cares when you're talking to a computer, right?) Tell me when John's heart rate drops below x or goes above y. Tell could be replaced with notify me, alert me, call me, or any other verbs that describe how the computer might contact the person. Drops below could be replaced with "goes below", "is less than" "slows to" "slows down to" "drops to" "decreases to" "goes down to" ETC. "goes above" could be "exceeds" "passes" "goes past" "increases to" "speeds up to" "goes up to" "reaches" "exceeds" "surpasses" "is faster than" "goes faster than" "is above" ETC. Good luck. I'm glad this isn't my project. Aaron -- To reply directly, remove j's from email address. From lionchao at gmail.com Fri Aug 24 15:14:42 2007 From: lionchao at gmail.com (Eric CHAO) Date: Fri, 24 Aug 2007 20:14:42 +0100 Subject: IDE for Python In-Reply-To: <46CAB7D4.5070308@gmail.com> References: <46CAB7D4.5070308@gmail.com> Message-ID: I think many python developers don't need such an IDE actually. Just like Ruby guys, they use a powerful editor, for example, Textmate, instead of all-in-one IDE. It's quick and direct. On 8/21/07, Joel Andres Granados wrote: > Hello list: > > I have tried various times to use an IDE for python put have always been > disapointed. > I haven't revisited the idea in about a year and was wondering what the > python people > use. > I have also found http://pida.co.uk/main as a possible solution. Anyone > tried it yet? > > suggestions. > Regards > Joel Andres Granados > > -- > http://mail.python.org/mailman/listinfo/python-list > > From twisted0n3 at gmail.com Sun Aug 19 23:02:07 2007 From: twisted0n3 at gmail.com (Twisted) Date: Mon, 20 Aug 2007 03:02:07 -0000 Subject: Xah's Edu Corner: Under the spell of Leibniz's dream In-Reply-To: <1187567809.896668.228650@z24g2000prh.googlegroups.com> References: <1187567809.896668.228650@z24g2000prh.googlegroups.com> Message-ID: <1187578927.945921.280180@q4g2000prc.googlegroups.com> On Aug 19, 7:56 pm, Xah Lee wrote: > So, when you "dress up formally" to attend your friend's wedding... Oh dear God, please *don't* remind me. > "Under the spell of Leibniz's dream" (2000) By Edsger W Dijkstrahttp://www.cs.utexas.edu/~EWD/ewd12xx/EWD1298.PDF A link to a copy in a non-toxic format would be nice. From martin at v.loewis.de Wed Aug 22 01:04:58 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 22 Aug 2007 07:04:58 +0200 Subject: Python 2.51 install on Vista "files in use" In-Reply-To: References: Message-ID: <46CBC3FA.20606@v.loewis.de> Steve Mavronis schrieb: > I tried to install Python 2.51 on Microsoft Vista Ultimate 32-bit > because I use the 3D modeler software Blender 2.44, in case I needed > additional Python support in the future for add-on scripts. > > I got a warning about "files in use" during installation that needed > updating. I aborted the install since the files were Intel Viiv and > Microsoft Vista Media Center related so didn't want to mess them up. Can > someone explain why Python wants to update those files? I think you misinterpreted the message. It's not that Python wanted to update Intel Viiv or Microsoft Vista Media Center; instead, it wants to update files that are used both by Python and by these software packages. Unfortunately, Microsoft installer does not put information into the UI which specific files conflict. About the only file I can imagine that both these software packages and Python would use, and which Python might update, is the Microsoft C runtime library, msvcr71.dll. If so, doing the update should be harmless: the update is only performed when the version of the DLL that comes with Python is more recent than the one installed on the sysem, and Microsoft promises that the newer version will be fully compatible with the older one. Regards, Martin From ladaan at iptel.org Thu Aug 23 14:16:45 2007 From: ladaan at iptel.org (Ladislav Andel) Date: Thu, 23 Aug 2007 20:16:45 +0200 Subject: comparing two lists In-Reply-To: References: Message-ID: <46CDCF0D.9090605@iptel.org> Peter Otten wrote: > Ladislav Andel wrote: > > >> what would be the most efficient way to do following? >> >> I have a list of dictionaries taken from DB e.g. >> dblist = [{'id:1, 'host':'google.com','ip_address':'1.2.3.4'}, >> {'id:3, 'host':'yahoo.com','ip_address':'5.6.7.8'}, >> {'id:9, 'host':'msn.com','ip_address':'11.3.2.3'}] >> >> and list of object instances in memory(it's just for example) >> which are looping within itself and testing particular hosts >> >> memlist = [,] >> memlist[0].id is 1 and memlist[0].host is google.com etc. >> memlist[1].id is 9 and memlist[1].host is msn.com etc. >> >> Now I want to add a new instance to memlist since id=3(in dblist) is not >> in memlist. >> How would you iterate through it and insert a new instance? >> >> The result should be: >> memlist = [,, ] >> memlist[0].id is 1 and memlist[0].host is google.com etc. >> memlist[1].id is 3 and memlist[1].host is yahoo.com etc. >> memlist[2].id is 9 and memlist[2].host is msn.com etc. >> > > You should replace the memlist with a dictionary using (host, id) tuples as > the keys. Here's an example that uses a set but requires you to modify the > class: > > dblist = [{'id':1, 'host':'google.com','ip_address':'1.2.3.4'}, > {'id':3, 'host':'yahoo.com','ip_address':'5.6.7.8'}, > {'id':9, 'host':'msn.com','ip_address':'11.3.2.3'}] > > class Item(object): > def __init__(self, id, host, **discarded): > self._tuple = (id, host) > def __hash__(self): > return hash(self._tuple) > def __eq__(self, other): > return self._tuple == other._tuple > def __repr__(self): > return "Item(id=%r, host=%r)" % self._tuple > > items = set([Item(1, "google.com")]) > for d in dblist: > item = Item(**d) > if item not in items: > print "adding", item > items.add(item) > else: > print item, "already there" > > Thank you for this nice solution. I wouldn't be able to write it this way at all but what about removing from memlist if there is less items in dblist than in items (instances)? I will have to iterate over items(instances) and remove that one which is not in dblist I guess. Lada > Peter > From antroy at gmail.com Fri Aug 10 07:07:35 2007 From: antroy at gmail.com (Ant) Date: Fri, 10 Aug 2007 04:07:35 -0700 Subject: Smoother Lines in Turtle Graphics In-Reply-To: <5i2tnaF3mgsofU1@mid.uni-berlin.de> References: <1186703789.695265.52390@e9g2000prf.googlegroups.com> <5i2tnaF3mgsofU1@mid.uni-berlin.de> Message-ID: <1186744055.367994.61850@g12g2000prg.googlegroups.com> On Aug 10, 11:41 am, "Diez B. Roggisch" wrote: > tomy wrote: > > Hi All ... > What turtle graphics? I'm not aware that there is some > standard-turtle-graphics available, so it might be a problem of your > turtle-graphics-package. > > Diez import turtle Its part of the standard Library! I don't know the answer to the OP's question mind you, I'd played around a little with it a while ago, but nothing more. Python: Batteries and Turtles included! -- Ant... http://antroy.blogspot.com/ From johnmfisher at comcast.net Mon Aug 13 18:16:01 2007 From: johnmfisher at comcast.net (John Fisher) Date: Mon, 13 Aug 2007 15:16:01 -0700 Subject: (sort of) deterministic timing in Python Message-ID: <1i2si8h.1qc8f77i68gyeN%johnmfisher@comcast.net> I am working on a framework for data acquisition in Python 2.5, am trying to get a structure going more like this: mark start time start event event finishes count time until next interval start second event? rather than this: start event event finishes sleep for interval start second event Do you see the difference? I get a true fixed interval from the first, including the time to accomplish the event task(s). In the second case, the sleep just gets tacked on at the end of the events, not very deterministic (timing-wise). So how do I accomplish this in Python with a minimum of labour? Thanks for any light you can shed on my darkness... wave_man From ratchetgrid at googlemail.com Sun Aug 12 20:04:40 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Mon, 13 Aug 2007 01:04:40 +0100 Subject: Complexity of methods etc Message-ID: <676224240708121704i5923bf2fvceb391559339146e@mail.gmail.com> Hi, I was wondering if anyone knew of any resources, where I might be able to find information about the complexity of certain python functions or little tips on how to reduce complexity. I mean like the "".join(), kind of thing? I want to see if there are any improvements I can add to my coding in order to reduce time/space usage/ Many Thanks in advance Nathan From chrispwd at gmail.com Wed Aug 1 14:31:18 2007 From: chrispwd at gmail.com (chrispwd at gmail.com) Date: Wed, 01 Aug 2007 11:31:18 -0700 Subject: Buffering HTML as HTMLParser reads it? Message-ID: <1185993078.651180.298620@19g2000hsx.googlegroups.com> Hello, I am working on a project where I'm using python to parse HTML pages, transforming data between certain tags. Currently the HTMLParser class is being used for this. In a nutshell, its pretty simple -- I'm feeding the contents of the HTML page to HTMLParser, then I am overriding the appropriate handle_ method to handle this extracted data. In that method, I take the found data and I transform it into another string based on some logic. Now, what I would like to do here is take that transformed string and put it "back into" the HTML document. Has anybody ever implemented something like this with HTMLParser? I'm thinking maybe somehow have HTMLParser append each character it reads except for data inside tags in some kind of buffer? This way I can have the HTML contents read into a buffer, then when I do my own handle_ overrides, I can also append to that buffer with the transformed data. Once the HTML page is finished parsing, ideally I would be able to print the contents of the buffer and the HTML would be identical except for the string transformations. I also need to make sure that all newlines, tags, spacing, etc are kept in tact -- this part is a requirement for other reasons. Thanks! From heba.farouk at yahoo.com Thu Aug 16 02:18:24 2007 From: heba.farouk at yahoo.com (Heba Farouk) Date: Wed, 15 Aug 2007 23:18:24 -0700 (PDT) Subject: Localizing numbers in python Message-ID: <681797.41390.qm@web31708.mail.mud.yahoo.com> Hello i would like to localize numbers in python according to the current selected language of the web page (English, french, arabic, ...), is there any options in python?? thanks in advance Yours Heba --------------------------------- Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. -------------- next part -------------- An HTML attachment was scrubbed... URL: From xah at xahlee.org Sun Aug 19 19:56:49 2007 From: xah at xahlee.org (Xah Lee) Date: Sun, 19 Aug 2007 16:56:49 -0700 Subject: Xah's Edu Corner: Under the spell of Leibniz's dream Message-ID: <1187567809.896668.228650@z24g2000prh.googlegroups.com> Dear computing comrades, Today, i'd like to show you a piece of literature written by a eminent mathematician Edsger W Dijkstra. Here's 2 interesting quote from his letter: ?The prevaling attitude was reflected in the creation of two literary figures ? admittedly of rather poor literature, but nevertheless of great paralyzing power ?, viz. ?the average programmer? and ?the casual user?. Up to these days, academic research in programming methodology has been supposed to respect the severe intellectual limitations of these fictitious morons: consequently any proposal that required any further education of the programming person was out.? ?... On the other hand we should be glad that the gospel of design by derivation rather by trial and error is still preached.? I happened to read it today. And, i think in your busy schedule of checking out slashdot and blogging and driveling with your excitement and concerns about current fashions and trends with your fellow peers and factions; It is good once in a while to read something unfashionable and not for-dummies. This letter of EWD is about 16 pages. Is somewhat a quaint rant. The first half i find interesting but without much sympathy, perhaps because the author is mostly talking about the situation in the mid 1990s, of which, i'm unfamiliar and too early a period to touch me personally. But the latter part of the letter, i find much empathy and concurrence. In particular, his remarks related to the formal methods. (for you math illiterates out there: the ?formal? here does not mean the opposite of ?informal?, as in ?formal dress? vs ?informal dress?. Rather, ?formal? here means ?mathematical reasoning by symbol manipulation; the ?FORM? in math FORMulas?. (for you mathematicians out there: the root of the word ?formal? as in ?formal dress? and ?formalism?, actually are the same. They both refers to ?form? as in a empty shell, appearance.)) (So, when you ?dress up formally? to attend your friend's wedding or death ceremony, it literally means you are putting on a appearance.) Now, without further ado, the article is at: ?Under the spell of Leibniz's dream? (2000) By Edsger W Dijkstra http://www.cs.utexas.edu/~EWD/ewd12xx/EWD1298.PDF Xah xah at xahlee.org ? http://xahlee.org/ From cousinstanley at gmail.com Sat Aug 4 21:59:42 2007 From: cousinstanley at gmail.com (Cousin Stanley) Date: Sat, 04 Aug 2007 20:59:42 -0500 Subject: Efficient Rank Ordering of Nested Lists References: <1186104049.022836.253470@e9g2000prf.googlegroups.com> <1i29gpw.1vh7eku1iauistN%aleax@mac.com> Message-ID: <1186279182_8217@sp12lax.superfeed.net> > .... > "beginner"'s advice to use a dictionary is also good > and may turn out to be faster, just because dicts are > SO fast in Python -- but you need to try and measure > both alternatives. > > One way to use a dict ( warning, untested code ) : def rank_list( single_list ) : d = { } for i , item in reversed( enumerate( sorted( single_list ) ) ) : d[ item ] = i return [ d[ item ] for item in single_list ] Alex .... I tested it but I don't know how to fix it .... :-) Both Pablo's original version and Neil's version work but I get the following traceback from your version .... Traceback (most recent call last): File "list_nested_rank.py", line 100, in test_01( list_source ) File "list_nested_rank.py", line 87, in test_01 list_print( this_func( list_source ) ) File "list_nested_rank.py", line 62, in rank_lists_02 return map( rank_list , nested_list ) File "list_nested_rank.py", line 56, in rank_list for i , item in reversed( enumerate( sorted( single_list ) ) ) : TypeError: argument to reversed() must be a sequence -- Stanley C. Kitching Human Being Phoenix, Arizona ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From claird at lairds.us Fri Aug 10 10:14:26 2007 From: claird at lairds.us (Cameron Laird) Date: Fri, 10 Aug 2007 14:14:26 +0000 Subject: The Future of Python Threading References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <5i329uF3muir4U1@mid.individual.net> Message-ID: <2f8uo4-d4j.ln1@lairds.us> In article <5i329uF3muir4U1 at mid.individual.net>, Bjoern Schliessmann wrote: >Justin T. wrote: > >> The detrimental effects of the GIL have been discussed several >> times and nobody has ever done anything about it. > >Also it has been discussed that dropping the GIL concept requires >very fine locking mechanisms inside the interpreter to keep data >serialised. The overhead managing those fine ones properly is not >at all negligible, and I think it's more than managing GIL. > >> The truth is that the future (and present reality) of almost every >> form of computing is multi-core, > >Is it? 8) . . . I reinforce some of these points slightly: A. An effective change to the GIL impacts not just Python in the sense of the Reference Manual, but also all its extensions. That has the potential to be a big, big cost; and B. At least part of the attention given multi-core processors--or, perhaps more accurately, the claims that multi-cores deserve threading re- writes--smells like vendor manipulation. From nytrokiss at gmail.com Wed Aug 1 12:25:36 2007 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 1 Aug 2007 09:25:36 -0700 Subject: calling a .net application from Python 2.5 In-Reply-To: <1185959694.045149.214050@19g2000hsx.googlegroups.com> References: <1185959694.045149.214050@19g2000hsx.googlegroups.com> Message-ID: <8a6b8e350708010925t56d107a0md38a8fc1f750898d@mail.gmail.com> http://pythonnet.sourceforge.net/ On 8/1/07, Acm wrote: > > I am working with Python 2.5. > > I would like to know how to call a .NET application (or .dll) from a > Python script. > > Can anyone help please? > > Thank you. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From gherzig at fmed.uba.ar Thu Aug 16 18:30:07 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Thu, 16 Aug 2007 19:30:07 -0300 Subject: advice about `correct' use of decorator In-Reply-To: <2vydnTio1a9IWlnbnZ2dnUVZ_jKdnZ2d@comcast.com> References: <2vydnTio1a9IWlnbnZ2dnUVZ_jKdnZ2d@comcast.com> Message-ID: <46C4CFEF.7020809@fmed.uba.ar> Steven Bethard wrote: >Gerardo Herzig wrote: > > >>Hi all. I guess i have a conceptual question: >>Im planing using a quite simple decorator to be used as a conditional >>for the execution of the function. I mean something like that: >> >>@is_logued_in >>def change_pass(): >> bla >> bla >> >>And so on for all the other functions who needs that the user is still >>loged in. >> >>where obviosly the is_logued_in() function will determine if the dude is >>still loged in, and THEN execute change_pass(). If the dude is not loged >>in, change_pass() is NOT executed at all. Instead, it will be redirected >>to the `login' screen. >> >>Something in my mind tells me that this is not the pythonic way...But i >>like the idea, so please tell me that im in the right way :) >> >> > >Django does it almost exactly this way: > >http://www.djangoproject.com/documentation/authentication/#the-login-required-decorator > >STeVe > > Great! So from now on, my idea is labeled as `djangothic' :) Thanks a lot! Gerardo From enleverlesX.XmcX at XmclaveauX.com Mon Aug 27 13:31:46 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Mon, 27 Aug 2007 19:31:46 +0200 Subject: How to free memory ( ie garbage collect) at run time with Python 2.5.1(windows) References: <1188224306.863247.127890@50g2000hsm.googlegroups.com> Message-ID: <46d30b62$0$5100$ba4acef3@news.orange.fr> Re! Sended by direct (private) e-mail @+ Michel Claveau From joshua at eeinternet.com Wed Aug 1 17:45:51 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 01 Aug 2007 13:45:51 -0800 Subject: Wing IDE for Python v. 3.0 beta1 released References: <46AF8ED7.2070206@wingware.com> <20070801212840.GA25065@spookie1.spookiegate> Message-ID: On Wednesday 01 August 2007 13:28, John K Masters wrote: > On 15:34 Tue 31 Jul , Wingware wrote: >> Hi, >> >> I'm happy to announce the first beta release of Wing IDE 3.0. It is >> available from http://wingware.com/wingide/beta > If their support for paid customers is anything like their support for > prospective customers then I would leave well alone. I've had excellent support from them. I'm sorry to hear your experiences have not been stellar. Questions submitted to the bug or comment list usually get a response in one day or less. And there are frequently respones by WingWare people to just about every question asked on the WingWare mailing list. > I have been trying wing for a few days but have noticed that > auto-completion does not work on all modules. I submitted this to wing > and was told that probably my PYTHONPATH was wrong. It may also not work if the IDE isn't sure what kind of object you are dealing with. You can "clarify" this as documented with an assert(isinstance()) statement. > I subsequently submitted a question about the licensing, i.e. whether I > could use wing on a home setup using Debian Etch, where I develop my > apps, and a work setup, using Debian Etch, with no net access. >From http://www.wingware.com/wingide/license: "Each Wing IDE user may run Wing on as many machines as needed for their own work, for all the operating systems which they have licensed. In order to reduce casual license sharing, which is a unfortunately a problem for small businesses like Wingware, licenses must be activated after installation on each machine." "We've worked hard to make this flexible and forgiving for valid customers. For example, reinstalling an OS and/or altering hardware usually should not break your activation. Also, activation can be done directly from Wing IDE and off-line activation is available if your machine does not have TCP port 80 (http) access to wingware.com. Each license is allowed three activations by default and more can be obtained on request from identifiable customers." > So far I have had no response I tend to let questions slide when they are answered in the documentation or on the web site. Maybe the Wing developers/support personnel are the same way. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE From steveo at syslang.net Tue Aug 14 10:24:31 2007 From: steveo at syslang.net (Steven W. Orr) Date: Tue, 14 Aug 2007 10:24:31 -0400 (EDT) Subject: Question about FutureWarning Message-ID: I have module M1 which has the following line in it: StartTime = safe_dict_get ( dic, 'starttime', 0xFFFFFFFF ) It gets imported by modules M2 and M3. And finally, M4 imports both M2 and M3. M4 |\M3 | |\M1 |\M2 | |\M1 I'm building a .deb file which means I have to compile the modules into .pyc and .pyo files. The compile command I use is python=/usr/bin/python2.3 i_python () { $python -c "import $1" $python -O -c "import $1" } i_python M1 i_python M2 i_python M3 i_python M4 When M1 is compiled, there's no problem. The same for when I compile M2 and M3. But when M4 is compiled, I get the following message: M1.py:268: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up StartTime = safe_dict_get ( dic, 'starttime', 0xFFFFFFFF ) I get the message twice, ostensibly because of M3 and M2. I was able to shut off the warning by adding the following lines *before* the import in M4. import warnings warnings.filterwarnings('ignore', category=FutureWarning) My question is this: Why can the warning not be shut off by putting the two lines in M1? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From carsten at uniqsys.com Thu Aug 30 14:11:38 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 30 Aug 2007 14:11:38 -0400 Subject: list index() In-Reply-To: <1188496588.750629.208100@g4g2000hsf.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <46d674c2$0$417$426a34cc@news.free.fr> <1188496588.750629.208100@g4g2000hsf.googlegroups.com> Message-ID: <1188497498.3468.60.camel@dot.uniqsys.com> On Thu, 2007-08-30 at 10:56 -0700, zzbbaadd at aol.com wrote: > On Aug 30, 12:42 am, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > zzbba... at aol.com a crit : > > > > > What's with using your brain instead of whining ? > > I knew there would be at least one religious zealot. While I agree that Bruno's response was perhaps needlessly snippy, your original question was needlessly inflammatory, as if you somehow wanted some "religious zealot" to act the way Bruno did. If we start labeling people, this thread will earn you a label that rhymes with "roll". -- Carsten Haese http://informixdb.sourceforge.net From paul at boddie.org.uk Wed Aug 1 18:56:23 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 01 Aug 2007 15:56:23 -0700 Subject: force unicode strings In-Reply-To: <46B0EEFD.1090709@web.de> References: <5hbmjcF3gtt39U1@mid.individual.net><46B0EEFD.1090709@web.de> Message-ID: <1186008983.150396.304000@r34g2000hsd.googlegroups.com> Stefan Behnel wrote: > > I guess you can't afford to wait for Python 3, can you? > > http://www.python.org/dev/peps/pep-3100/#atomic-types No need to: just start python with the -U option: Python 2.4.1 (#2, Oct 4 2006, 16:53:35) [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2.1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> "???" u'\xe6\xf8\xe5' It's just like Jython: Jython 2.1 on java1.5.0_03 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> "???" '\xE6\xF8\xE5' That's a Unicode object, really. Various IronPython users have pointed out similar things, too, but this kind of thing has been going on for about ten years, I guess. Paul From airconditi at gmail.com Tue Aug 14 17:54:00 2007 From: airconditi at gmail.com (airconditi at gmail.com) Date: Tue, 14 Aug 2007 14:54:00 -0700 Subject: Tuned cars Message-ID: <1187128440.369048.255470@r34g2000hsd.googlegroups.com> Cool cars, tuning & styling, here you can find many tuned cars with tons of pictures!!!!!!! http://tuning-styling.blogspot.com/ From daniels at dsl-only.net Wed Aug 22 23:53:23 2007 From: daniels at dsl-only.net (Scott David Daniels) Date: Wed, 22 Aug 2007 20:53:23 -0700 Subject: introspection and functions In-Reply-To: <1187819949.515982.15450@r23g2000prd.googlegroups.com> References: <1187819949.515982.15450@r23g2000prd.googlegroups.com> Message-ID: <13cq14sd11959fb@corp.supernews.com> yagyala wrote: > Hi. I would like to be able to tell, at run time, how many parameters > a function requires. Ideally I would like to be able to tell which are > optional as well. I've tried looking at the functions attributes, but > haven't found one that helps in this. How can I do this? > > Thanks > This really only will work for those functions that are simply constructed. You are better off not trying to do this, or code like the following will confound your code: from functools import partial def somefunction(a=23, b=14, c='hi'): print 'Finally' f = partial(somefunction, b=13) g = partial(f, a=19) h = partial(g, c=123) print whatargs(h) From v_ashe at btinternet.com Fri Aug 3 12:31:49 2007 From: v_ashe at btinternet.com (Vaughan V Ashe) Date: Fri, 3 Aug 2007 17:31:49 +0100 Subject: Using cursor.callproc with zxJDBC Message-ID: <104F88F15D1E430B96FF79E35FE6B84D@VVA> Hi We would like to use the store proc. We are using a postgreql database. what we have working so far is: params = [4,4,2] curs.callproc("update_job_status",params) db.commit() #print db #print curs.description result = curs.fetchall() if result == 1: print "good one" else: print "shite" we are using the beta version of jython. Would be very happy to get a response from you Regards Vaughan -------------- next part -------------- An HTML attachment was scrubbed... URL: From zyzhu2000 at gmail.com Thu Aug 16 18:35:50 2007 From: zyzhu2000 at gmail.com (beginner) Date: Thu, 16 Aug 2007 22:35:50 -0000 Subject: How to say $a=$b->{"A"} ||={} in Python? Message-ID: <1187303750.590497.208060@x40g2000prg.googlegroups.com> Hi All. I'd like to do the following in more succint code: if k in b: a=b[k] else: a={} b[k]=a a['A']=1 In perl it is just one line: $a=$b->{"A"} ||={}. Thanks, Geoffrey From paul at boddie.org.uk Fri Aug 3 20:34:49 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 03 Aug 2007 17:34:49 -0700 Subject: Bug in time, part 2 In-Reply-To: References: Message-ID: <1186187689.624149.105290@d55g2000hsg.googlegroups.com> Joshua J. Kugler wrote: > Or could I entitle this, "A Wrinkle in time.py," with apologies to Madeleine > L'Engle. Either I've found a bug (or rather room for improvement) in > time.py, or I *really* need a time module that doesn't assume so much. I'd be inclined to use the datetime module to avoid certain underlying library assumptions. I originally tried to retrace your steps and make comments about what is going on, but the UNIX time API is so bizarre that it's better for me to suggest a few things instead. First of all, you managed to get things working nicely in a GMT/UTC environment. Sadly, the time module doesn't provide all the functions you'd need to work with UTC without such hacks as calling tzset, although I've been trying to refine some patches which do provide such functions - see this link for more details: https://sourceforge.net/tracker/?func=detail&atid=305470&aid=1667546&group_id=5470 Although I suggested setting tm_isdst to zero previously, I'm more convinced now that it's quite difficult to do the right thing with such simple measures alone. Again, the time module doesn't provide access to timezone offsets on individual time structures in its current form, nor does it support the %z format option for strftime and strptime, although the patches mentioned above do provide it; both of these things provide the foundations to convert localtimes to UTC times and to convert back only when needed, a bit like the way you're supposed to work with Unicode and only produce specific textual encodings once you're finished. [...] Anyway, here are some suggestions: In your original test case (or problem), it looked like you were seeing a DST "boundary" which then made the times appear further apart than they actually were. Adjusting this test case for my timezone, I can reproduce the issue but then add the %z format option (see the patches) to demonstrate that with access to timezone offsets there's nothing really wrong: >>> nondst = time.mktime(time.strptime('2007-03-25 02:00:00', '%Y-%m-%d %H:%M:%S')) >>> dst = time.mktime(time.strptime('2007-03-25 03:00:00', '%Y-%m-%d %H:%M:%S')) >>> time.strftime('%Y-%m-%d %H:%M:%S %z', time.localtime(nondst)) '2007-03-25 03:00:00 +0200' >>> time.strftime('%Y-%m-%d %H:%M:%S %z', time.localtime(dst)) '2007-03-25 03:00:00 +0200' Certainly, the localtime (with undecided timezone) of 2am on 25th March gets converted to the DST timezone, but we can be more specific and make informed guesses as to what happens: >>> nondst = time.mktime(time.strptime('2007-03-25 02:00:00 CET', '%Y-%m-%d %H:%M:%S %Z')) >>> time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(nondst)) '2007-03-25 03:00:00 CEST' And trying with 1:59am gives us what we'd expect: >>> nondst = time.mktime(time.strptime('2007-03-25 01:59:00', '%Y-%m-%d %H:%M:%S')) >>> time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(nondst)) '2007-03-25 01:59:00 CET' Now, we might like to avoid dealing with localtime altogether, and for such work I've introduced a function called mktimetz which attempts to use the timezone offset to calculate a time value which works with localtime and gmtime mostly without surprises - something which mktime doesn't guarantee. However, since strptime tends to sit on the fence and not assert any knowledge about DST, and since mktimetz depends on reliable timezone information, you do need to be careful about supplying vague information in the first place: >>> tz2am = time.mktimetz(time.strptime('2007-03-25 02:00:00', '%Y-%m-%d %H:%M:%S')) >>> time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(tz2am)) '2007-03-25 05:00:00 CEST' (I can only speculate as to what happens here, but it really isn't worth too much consideration.) Here, you really need mktime instead, because it will probably make the right guesses about the presumed localtime given. However, if you indicate the timezone, the result will be better: >>> tz2am = time.mktimetz(time.strptime('2007-03-25 02:00:00 CET', '%Y-%m-%d %H:%M:%S %Z')) >>> time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(tz2am)) '2007-03-25 03:00:00 CEST' >>> time.strftime('%Y-%m-%d %H:%M:%S %Z', time.gmtime(tz2am)) '2007-03-25 01:00:00 GMT' Here, an offset wouldn't be precise enough in the input (something like +0100) because it wouldn't tell strptime about DST. I could go on for a very long time about all this, and I've spent a very long time messing around with the different time functions. My personal opinion is that Python's time/datetime support needs a boost if only in terms of useful additional library endorsements and better documentation. Perhaps we just need to give the datetime module the support it deserves and treat the time module as legacy code. > In other news, setting time.tzname = ('GMT', 'GMT') does nothing. You have > to set the environment variable, then call tzset. Is there a rational for > this? Seems odd. It's the bizarre, even perverse way of the old UNIX time API. Various enhancements have come along to diminish the need for such hacks, but as you can imagine, they aren't fully standardised *and* universally adopted. Paul From google at tyeon.com Thu Aug 30 17:17:01 2007 From: google at tyeon.com (T) Date: Thu, 30 Aug 2007 14:17:01 -0700 Subject: How to use os.putenv() ? In-Reply-To: <13de3gc197b74dd@corp.supernews.com> References: <1188436871.549201.315170@g4g2000hsf.googlegroups.com> <1188438641.676443.121510@x35g2000prf.googlegroups.com> <1188494964.539169.104180@d55g2000hsg.googlegroups.com> <13de3gc197b74dd@corp.supernews.com> Message-ID: <1188508621.556566.19530@q3g2000prf.googlegroups.com> Thank you everyone! From papalagi.pakeha at gmail.com Sun Aug 19 09:19:08 2007 From: papalagi.pakeha at gmail.com (Papalagi Pakeha) Date: Mon, 20 Aug 2007 01:19:08 +1200 Subject: How to find script's directory Message-ID: <343d1bca0708190619s1f07bb57tfdb32a70f68a031b@mail.gmail.com> Hi, I have a project (a django project actually) that has a structure something like: /path/prj/settings.py /path/prj/scripts/blah.py /path/prj/... In order to run blah.py I need to set $PYTHONPATH to /path/prj because it does "import settings". That's all good. I would however like to autodetect the path in blah.py somehow and not need to set PYTHONPATH prior to execution. Whether it's called as /path/prj/scripts/blah.py or ./blah.py or ../../prj/scripts/blah.py or even plain blah.py should the whole path to it be in $PATH I'd like it to detect it's location in the filesystem and append its parent dir to sys.path I guess I could do it with a little help of os.path.realpath() for all those cases where absolute or relative path was used. But how should I approach it when it's invoked as plain 'blah.py' because its directory name is in $PATH? TIA! PaPa From frank.wilder at gmail.com Tue Aug 21 15:43:05 2007 From: frank.wilder at gmail.com (franko353) Date: Tue, 21 Aug 2007 19:43:05 -0000 Subject: Microsoft Vista and os.exec Message-ID: <1187725385.938752.290390@r34g2000hsd.googlegroups.com> I have wxPython programs that work fine in Win2000/XP using os.exec(). They do not work in MS Vista. Has anyone else had any luck with exec()? I keep getting an 'invalid option' error. It turn out it was really a security issue and I had to move to a "win32process.CreateProcess" solution to fix this under Vista. There is a good example of using CreateProcess in the "Python programming on Win32" book. From claird at lairds.us Tue Aug 21 09:40:00 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 21 Aug 2007 13:40:00 +0000 Subject: Server-side scripting in python References: <1187614732.519547.296020@j4g2000prf.googlegroups.com> Message-ID: In article <1187614732.519547.296020 at j4g2000prf.googlegroups.com>, Nagarajan wrote: >Hi group, >I need to develop a web application. I am in a fix as to choose among >the various server-side scripting options. I want to explore python >(am a newbie) to gain expertise and upon search, I learnt about >PSP(Python Server Pages) that uses Jython as its scripting language. >Is it a better option over PHP or Perl? Could anyone point out the >pros and cons of using PSP over others? . . . I suspect that several of us don't understand your question. Python supports several--arguably, a plethora, more than any other language--distinct "frameworks" for server-side scripting of Web applications . PSP certainly is among these, although it's recommended less often than several others. Is PSP better than PHP or Perl? First, do you understand that PSP isn't directly comparable to PHP or Perl? The latter two are languages, while PSP is a Web framework. In any case, the answer is certain to be, "it depends". There certainly are situations for each of PSP, PHP, Perl, and many other technol- ogies. I summarize: if you have an interest in practicing Python while building Web applications, your prospects certainly are bright; you'll receive abundant help from the folks here and elsewhere. For us to provide more specific details about Perl, PSP, and so on, meaningful to your own needs, will only be possible when you articulate the latter more fully . From kasimmominov at gmail.com Wed Aug 22 04:07:06 2007 From: kasimmominov at gmail.com (kasim) Date: Wed, 22 Aug 2007 08:07:06 -0000 Subject: 4000 usd every month by the time you can reach or more Message-ID: <1187770026.513143.324280@q3g2000prf.googlegroups.com> AGLOCO: The Internet's First Economic Network Today's hottest Internet businesses are all about the power of social networks. Companies like MySpace, Facebook, and YouTube have become worth billions because businesses have realized that these social networks are generating huge advertising and marketing opportunities. As these social networks grow, the economic potential for its owners - and the advertisers who target the site's users - is remarkable. At AGLOCO, we asked a simple question: The users created the community, where's their share of the profit? It was from this question that AGLOCO set out to create the Internet's first Economic Network, harnessing the power of Internet-based social networks to directly benefit the Members who help to create the community. http://www.agloco.com/r/BBFR2592 Becoming a member of AGLOCO is as simple as completing a brief sign-up page (name, age, location and email address.). Once you're a Member, you will be asked to then download the Viewbar software. (Note: the Viewbar software is currently unavailable, as it is in closed testing. It will be ready for public download in a few weeks, and members will be notified when it is available.) AGLOCO makes money for its Members in many ways: http://www.agloco.com/r/BBFR2592 Search: Every time you use the Viewbar to do an Internet search, AGLOCO earns money from the search engine providers. (For example, Google pays as much as $0.10 on average for each search that is directed to its search engine.) Advertising: The Viewbar itself displays ads that are targeted based upon the websites you're visiting. When you click on an ad and make a purchase, AGLOCO receives a referral fee, which we pass on to our Members. (Please note: Individual members do not receive any compensation for clicking on ads in the Viewbar , and the Viewbar can detect if someone is clicking ads in a fraudulent manner.) Transaction commissions: Many major retailers pay commissions when you refer customers who make a purchase. AGLOCO collects that commission and passes it on to our members. (For example, Amazon pays an 8.5% commission to most websites who refer customers, and has cut deals for even larger percentages. The bigger the AGLOCO community, the better commission we can negotiate for our Members.) Software distribution: Numerous software companies pay websites to encourage the download of new software releases (for example, Adobe's Flash and Acrobat Reader software), and trial versions of new programs. AGLOCO members not only get access to the latest and coolest software, they get paid for it. Service distribution: Many online service providers will look to the AGLOCO community as a source of new and active users for their services. (For example, eBay, Skype, and PayPal, among others, all pay fees to people who help them recruit new active users to their services) Product distribution: When Members agree to use a product, such as cell phones, high-tech gadgets, office supplies, new credit cards or financial services, AGLOCO can collect referral fees. Some companies even offer special rebate and cash-back programs. AGLOCO Members make money in four ways. Members earn a monthly share of the AGLOCO revenue based on the use of the AGLOCO Viewbar that month. Members earn part of the company based on the use of the AGLOCO Viewbar that month (currently a maximum of five hours are rewarded). http://www.agloco.com/r/BBFR2592 . Members who use our referral system to help build the AGLOCO network will earn more. (AGLOCO only has significant value as a large network and people who help build it should be rewarded. - We also feel that the early users who told friends about YouTube or MySpace or even Google probably deserved something too, but no referral system was available to record their work). Members will also get a share of any commissions AGLOCO gets when a Member purchases a product or service from an AGLOCO Sponsor company. Why should I join now? First, it costs nothing to Join and takes less than one minute. Second, you can help build the AGLOCO community by recruiting new Members TODAY. Right now, inviting your friends to join AGLOCO is as easy and productive as it will ever be - but you need to invite your friends before someone else beats you to them. Remember, the bigger the AGLOCO community, the more attractive AGLOCO is to potential business partners and advertisers. Recruit your friends and family by contacting them through email. (But remember we have a strict anti-spam policy.) Use your blog and your existing social networks, such as MySpace and Facebook, to contact your friends and encourage them to join a new community that will actually let them earn money. http://www.agloco.com/r/BBFR2592 Be a part of the Internet's first Member-Owned Economic Community. From dickinsm at gmail.com Tue Aug 28 12:58:02 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 28 Aug 2007 16:58:02 -0000 Subject: int/long bug in locale? In-Reply-To: <1188309809.592078.58960@22g2000hsm.googlegroups.com> References: <1188309809.592078.58960@22g2000hsm.googlegroups.com> Message-ID: <1188320282.070950.199270@d55g2000hsg.googlegroups.com> On Aug 28, 10:03 am, tkp... at hotmail.com wrote: > Is there an int/long related bug lurking in locale? Looks like this has already been reported: See http://bugs.python.org/issue1742669 Mark From steve at holdenweb.com Thu Aug 30 14:40:19 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Aug 2007 14:40:19 -0400 Subject: list index() In-Reply-To: <1188498073.997168.282420@q5g2000prf.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <46d674c2$0$417$426a34cc@news.free.fr> <1188496588.750629.208100@g4g2000hsf.googlegroups.com> <1188498073.997168.282420@q5g2000prf.googlegroups.com> Message-ID: zzbbaadd at aol.com wrote: >> While I agree that Bruno's response was perhaps needlessly snippy, your >> original question was needlessly inflammatory, as if you somehow wanted >> some "religious zealot" to act the way Bruno did. If we start labeling >> people, this thread will earn you a label that rhymes with "roll". >> > That is correct. I did word it in a way that would hook the Bruno's of > the group. But I will probably have some more important questions so I > will word it differently in the future. Such as: I wish they were not > getting rid of dict.has_key() in Python 3, which I prefer to IN. > > Well, again Python gives you the flexibility to define your own dict subclass that has a has_key() method with the obvious implementation. But why would you want to ignore built-in support like "value in dict"? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From cai.haibin at gmail.com Tue Aug 14 21:58:26 2007 From: cai.haibin at gmail.com (james_027) Date: Wed, 15 Aug 2007 01:58:26 -0000 Subject: accessing keys in dict Message-ID: <1187143106.021325.104690@l22g2000prc.googlegroups.com> hi, a_dict = {'name':'apple', 'color':'red', 'texture':'smooth', 'shape':'sphere'} is there any difference between .. for key in a_dict: from for key in a_dict.keys(): which is more preferred? any difference in performance? THanks james From kylotan at gmail.com Sat Aug 11 17:53:31 2007 From: kylotan at gmail.com (Ben Sizer) Date: Sat, 11 Aug 2007 21:53:31 -0000 Subject: The Future of Python Threading In-Reply-To: References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <87ir7n4fps.fsf@benfinney.id.au> <1186760254.859080.137840@g12g2000prg.googlegroups.com> Message-ID: <1186869211.206352.276530@b79g2000hse.googlegroups.com> On Aug 10, 5:13 pm, "Chris Mellon" wrote: > On 8/10/07, Ben Sizer wrote: > > > On 10 Aug, 15:38, Ben Finney > > wrote: > > > Last I checked, multiple processes can run concurrently on multi-core > > > systems. That's a well-established way of structuring a program. > > > It is, however, almost always more complex and slower-performing. > > > Plus, it's underdocumented. Most academic study of concurrent > > programming, while referring to the separately executing units as > > 'processes', almost always assume a shared memory space and the > > associated primitives that go along with that. > > This is simply not true. Firstly, there's a well defined difference > between 'process' and a 'thread' and that is that processes have > private memory spaces. Nobody says "process" when they mean threads of > execution within a shared memory space and if they do they're wrong. I'm afraid that a lot of what students will be taught does exactly this, because the typical study of concurrency is in relation to contention for shared resources, whether that be memory, a file, a peripheral, a queue, etc. One example I have close to hand is 'Principles of Concurrent and Distributed Programming', which has no mention of the term 'thread'. It does have many examples of several processes accessing shared objects, which is typically the focus of most concurrent programming considerations. The idea that processes have memory space completely isolated from other processes is both relatively recent and not universal across all platforms. It also requires you to start treating memory as arbitrarily different from other resources which are typically shared. > And no, "most" academic study isn't limited to shared memory spaces. > In fact, almost every improvement in concurrency has been moving > *away* from simple shared memory - the closest thing to it is > transactional memory, which is like shared memory but with > transactional semantics instead of simple sharing. I think I wasn't sufficiently clear; research may well be moving in that direction, but you can bet that the typical student with their computer science or software engineering degree will have been taught far more about how to use synchronisation primitives within a program than how to communicate between arbitrary processes. > There's nothing "undocumented" about IPC. It's been around as a > technique for decades. Message passing is as old as the hills. I didn't say undocumented, I said underdocumented. The typical programmer these days comes educated in at least how to use a mutex or semaphore, and will probably look for that capability in any language they use. They won't be thinking about creating an arbitrary message passing system and separating their project out into separate programs, even if that has been what UNIX programmers have chosen to do since 1969. There are a multitude of different ways to fit IPC into a system, but only a few approaches to threading, which also happen to coincide quite closely to how low-level OS functionality handles processes meaning you tend to get taught the latter. That's why it's useful for Python to have good support for it. > > Hardly. Sure, so you don't have to worry about contention over objects > > in memory, but it's still completely asynchronous, and there will > > still be a large degree of waiting for the other processes to respond, > > and you have to develop the protocols to communicate. Apart from > > convenient serialisation, Python doesn't exactly make IPC easy, unlike > > Java's RMI for example. > > There's nothing that Python does to make IPC hard, either. There's > nothing in the standard library yet, but you may be interested in Pyro > (http://pyro.sf.net) or Parallel Python > (http://www.parallelpython.com/). It's not erlang, but it's not hard > either. At least, it's not any harder than using threads and locks. Although Pyro is good in what it does, simple RPC alone doesn't solve most of the problems that typical threading usage does. IPC is useful for the idea of submitting jobs in the background but it doesn't fit so well to situations where there are parallel loops both acting on a shared resource. Say you have a main thread and a network reading thread - given a shared queue for the data, you can safely do this by adding just 5 lines of code: 2 locks, 2 unlocks, and a call to start the networking thread. Implementing that using RPC will be more complex, or less efficient, or probably both. -- Ben Sizer From ptmcg at austin.rr.com Wed Aug 1 16:08:08 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 01 Aug 2007 13:08:08 -0700 Subject: Buffering HTML as HTMLParser reads it? In-Reply-To: <1185993078.651180.298620@19g2000hsx.googlegroups.com> References: <1185993078.651180.298620@19g2000hsx.googlegroups.com> Message-ID: <1185998888.811319.15150@l70g2000hse.googlegroups.com> On Aug 1, 1:31 pm, chris... at gmail.com wrote: > > I'm thinking maybe somehow have HTMLParser append each character it > reads except for data inside tags in some kind of buffer? This way I > can have the HTML contents read into a buffer, then when I do my own > handle_ overrides, I can also append to that buffer with the > transformed data. Once the HTML page is finished parsing, ideally I > would be able to print the contents of the buffer and the HTML would > be identical except for the string transformations. > > I also need to make sure that all newlines, tags, spacing, etc are > kept in tact -- this part is a requirement for other reasons. > > Thanks! What you describe is almost exactly how pyparsing implements transformString. See below: from pyparsing import * boldStart,boldEnd = makeHTMLTags("B") # convert to
and to
boldStart.setParseAction(replaceWith('
')) boldEnd.setParseAction(replaceWith('
')) converter = boldStart | boldEnd html = "Display this in bold" print converter.transformString(html) Prints: Display this in
bold
All text not matched by a pattern in the converter is left as-is. (My CSS style/form may not be up to date, but I hope you get the idea.) -- Paul From gheize at gmail.com Thu Aug 30 06:33:11 2007 From: gheize at gmail.com (Guillermo Heizenreder) Date: Thu, 30 Aug 2007 07:33:11 -0300 Subject: problem with SQLObject + mysql Message-ID: <1188469992.27740.14.camel@leinad-desktop> Hi list I'm new whit SQLObjet. I'm study the tutorial:Connecting databases to Python with SQLObjet[1] My problem is: >>>from sqlobject.mysql import builder >>>con=builder()(user='dbuser',passwd='dbpassword',host='localhost',db='garbanzo') Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/site-packages/SQLObject-0.9.1-py2.5.egg/sqlobject/mysql/mysqlconnection.py", line 51, in __init__ DBAPI.__init__(self, **kw) File "/usr/lib/python2.5/site-packages/SQLObject-0.9.1-py2.5.egg/sqlobject/dbconnection.py", line 249, in __init__ DBConnection.__init__(self, **kw) TypeError: __init__() got an unexpected keyword argument 'passwd' First i creating the user mysql: guille at leinad-desktop:~$ mysql -u root mysql> use mysql; Database changed mysql> create database garbanzo; Query OK, 1 row affected (0.02 sec) mysql> grant all privileges on garbanzo to 'dbuser'@'localhost' identified by 'dbpassword'; Query OK, 0 rows affected (0.10 sec) mysql> flush privileges; Query OK, 0 rows affected (0.09 sec) So... how i do to connect?. how create de password correctly? Thanks and kind regards from Argentina. P/D: my English it to bad, I'm a novice, :P. [1]http://www-128.ibm.com/developerworks/library/os-pythonsqlo/index.html?ca=drs#resources -- Heizenreder Guillermo http://code.google.com/u/gheize/ From max at alcyone.com Thu Aug 9 17:24:42 2007 From: max at alcyone.com (Erik Max Francis) Date: Thu, 09 Aug 2007 14:24:42 -0700 Subject: Puzzled by "is" In-Reply-To: References: <20070809194105.39BD11E400A@bag.python.org> Message-ID: John K Masters wrote: > OK fiddling around with this and reading the docs I tried:- > a = 'qqqqqqqqqq' #10 q's > b = 'qqqqqqqqqq' #10 q's > a is b > true > c = 'q' * 10 > c > 'qqqqqqqqqq' #10 q's > d = 'q' * 10 > d > 'qqqqqqqqqq' #10 q's > c is d > false > > So from what I've read "==" tests for equivalence, "is" tests for identity but > that does not explain the behaviour above. Using the `is` test between non-sentinel immutable objects (e.g., integers, floats, strings) is _completely pointless_. Since immutable objects cannot be changed, it is up to the interpreter (and thus can vary from version to version and implementation to implementation) whether or not to "cache" the objects and reuse them, or whether or not to create new ones. You should never be testing such objects for identity (`is`); you should only be testing them for equality (`==`). The only time it makes sense to use the `is` operator with immutable objects is when you're dealing with a sentinel object, e.g., `None`, or a custom sentinel object (e.g., `mySentinel = object()`), because that is the only time you actually _are_ interested in identity. All other times you are not really interested in identity. Sample code as above is essentially showing unimportant implementation details that should never concern you. Don't use `is`, use `==`. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis Chance favors the trained mind. -- Louis Pasteur From gdamjan at gmail.com Wed Aug 29 11:37:50 2007 From: gdamjan at gmail.com (Damjan) Date: Wed, 29 Aug 2007 17:37:50 +0200 Subject: encoding problems References: <46d5215b$0$411$426a74cc@news.free.fr> Message-ID: <46d592bc$0$90274$14726298@news.sunsite.dk> > > is there a way to sort this string properly (sorted()?) > I mean first 'a' then '?' then 'e' etc. (sorted puts accented letters at > the end). Or should I have to provide a comparison function to sorted? After setting the locale... locale.strcoll() -- damjan From deets at nospam.web.de Thu Aug 16 11:54:14 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 16 Aug 2007 17:54:14 +0200 Subject: A problem with Time In-Reply-To: <46c469be$0$66145$7b0f0fd3@mistral.news.newnet.co.uk> References: <46c469be$0$66145$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <5ija9dF3pjmsqU1@mid.uni-berlin.de> special_dragonfly schrieb: > Hello, > > I need to return the date yesterday in the form DDMMYYYY. I looked through > the modules: time, datetime and calendar but can't find anything that leaps > out at me. > > The problem I'm having is that although I can use time.localtime and get a > tuple of the year, month, day and so forth, I don't believe I can just minus > 1 from the day, because I don't think it's cyclic, also, I can't see the > date being linked in with the month. > > So is there any way of getting yesterdays date? RTFM is the answer... import datetime today = datetime.date.today() yesterday = today - datetime.timedelta(days=1) print yesterday Diez From rdm at rcblue.com Thu Aug 9 13:38:46 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 09 Aug 2007 10:38:46 -0700 Subject: Puzzled by "is" Message-ID: <20070809173855.9FDEB1E4009@bag.python.org> >>> () is () True >>> (1,) is (1,) False Why? Thanks, Dick Moores From gandalf at designaproduct.biz Sat Aug 18 03:56:30 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Sat, 18 Aug 2007 09:56:30 +0200 Subject: Encryption and hashing In-Reply-To: <1187392383.237609.97250@19g2000hsx.googlegroups.com> References: <1187377630.017794.36510@50g2000hsm.googlegroups.com> <1187392383.237609.97250@19g2000hsx.googlegroups.com> Message-ID: <46C6A62E.6080201@designaproduct.biz> > These are the algorithms supported in the last version of PyCrypto: > > $ ls pycrypto-2.0.1/src/ > AES.c Blowfish.c DES.c IDEA.c > RIPEMD.c winrand.c > ARC2.c cast5.c _dsa.c MD2.c > _rsa.c XOR.c > ARC4.c CAST.c _fastmath.c MD4.c SHA256.c > block_template.c DES3.c hash_template.c RC5.c > stream_template.c > > So it haven't Twofish, Serpent, neither Whirlpool. Neither many others. > OK sorry, I was wrong. Isn't blowfish a better version of twofish anyway? From jeffmess at gmail.com Tue Aug 28 09:31:45 2007 From: jeffmess at gmail.com (jeffmess at gmail.com) Date: Tue, 28 Aug 2007 13:31:45 -0000 Subject: Table update In-Reply-To: References: Message-ID: <1188307905.354612.297400@r29g2000hsg.googlegroups.com> On Aug 28, 2:57 pm, "Ahmed, Shakir" wrote: > I am trying to use python script to update a table by incremental value > based on struc_No but having problem to get right result on the value > field for the 3rd and 4th same number of struc_no. > > I need to update the Value field only with the incremental value of 15 > or so > > Any help is highly appreciated. > > Thanks > Shak > > Input table or source table > > ID struc_id Struc_No Value > 1 ABC 1001 10 > 2 EFJ 1005 15 > 3 HIK 1003 10 > 4 ILK 1005 10 > 5 PIO 1001 8 > 6 TIN 1001 12 > 7 MNO 1001 11 > 8 POW 1003 18 > > Output Table > > ID struc_id Struc_No Value Added value > 1 ABC 1001 25 15 > 2 EFJ 1005 30 15 > 3 HIK 1003 25 15 > 4 ILK 1005 40 30 > 5 PIO 1001 38 30 > 6 TIN 1001 57 45 > 7 MNO 1001 71 60 > 8 POW 1003 48 30 Well you certainly won't learn anything if you don't at least try to solve the problem. >>> file = open('Somefile', 'r').readlines() >>> for line in file: ... x = line.split() ... if not x[3] == "Value": ... print int(x[3]) + 15 I'm sure you can take it from here. Hope it helps. Best regards Jeffrey van Aswegen From aafshar at gmail.com Thu Aug 30 05:51:41 2007 From: aafshar at gmail.com (Ali) Date: Thu, 30 Aug 2007 09:51:41 -0000 Subject: IDE for Python In-Reply-To: References: Message-ID: <1188467501.364273.178320@o80g2000hse.googlegroups.com> On Aug 21, 11:00 am, Joel Andres Granados wrote: > Hello list: > > I have tried various times to use an IDE for python put have always been > disapointed. > I haven't revisited the idea in about a year and was wondering what the > python people > use. > I have also found http://pida.co.uk/main as a possible solution. Anyone > tried it yet? PIDA (http://pida.co.uk/), in my humble opinion, is the One True IDE*. It will embed the editor of your choice, use the version control system of your choice, and integrate the tools of your choice. In short, it integrates your development tools into a single environment. Hence the tag: "One True IDE". Ali * Emacs is pretty good at this, but since PIDA can embed Emacs anyway, and adds features to it... From python at jayloden.com Wed Aug 8 01:09:29 2007 From: python at jayloden.com (Jay Loden) Date: Wed, 08 Aug 2007 01:09:29 -0400 Subject: How can I programmatically find the name of a method from within that method? In-Reply-To: <1186548312.672360.259100@q3g2000prf.googlegroups.com> References: <1186548312.672360.259100@q3g2000prf.googlegroups.com> Message-ID: <46B95009.6040803@jayloden.com> kj7ny wrote: > Is there a way that I can programmatically find the name of a method I > have created from within that method? I would like to be able to log > a message from within that method (def) and I would like to include > the name of the method from which it was written without having to > hard-code that value in every message string. While we're at it, is > there a way to programmatically get the name of the class and the > module while I'm at it? This is a frequently asked question around here :-) You should search the list archives for past threads, e.g: http://aspn.activestate.com/ASPN/Mail/Message/python-list/3542665 -Jay From ldo at geek-central.gen.new_zealand Sun Aug 12 23:37:28 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 13 Aug 2007 15:37:28 +1200 Subject: Error calling module References: Message-ID: In message , fartknuckle wrote: > When I try to call gtk like so: > > > import gtk > > I get the error: > > ImportError: No module named gtk > > > I installed a new Python and a new pygtk. > Is the gtk module not a part of pygtk??? > > I have PYTHONPATH=/usr/local/lib/python2.5/site-packages > set. So what am I doing wrong? First question: where is the gtk module located? Second question: start up python interactively, type import sys sys.path Does the resulting list include the directory that is the answer to the first question? From jgarviahonrado at yahoo.es Tue Aug 28 09:38:55 2007 From: jgarviahonrado at yahoo.es (=?iso-8859-1?Q?Julio_Garv=EDa?=) Date: Tue, 28 Aug 2007 13:38:55 +0000 (GMT) Subject: HP-UX IA: Python 2.4 (64bits & gcc) Message-ID: <197077.37988.qm@web86906.mail.ukl.yahoo.com> Hello, Please, Could you kindly tell me how to build Python 2.4 in HP-UX 11i v2 (Itanium) in 64 bits using gcc/g++? Thanks in advance for your attention. With best regards, Julio Garv?a Honrado ____________________________________________________________________________________ S? un Mejor Amante del Cine ?Quieres saber c?mo? ?Deja que otras personas te ayuden! http://advision.webevents.yahoo.com/reto/entretenimiento.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan.behnel-n05pAM at web.de Wed Aug 1 08:26:51 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 01 Aug 2007 14:26:51 +0200 Subject: Plain old SAX and minidom useable? But how then? In-Reply-To: <1185969539.653078.287360@w3g2000hsg.googlegroups.com> References: <1185969539.653078.287360@w3g2000hsg.googlegroups.com> Message-ID: <46B07C0B.70507@web.de> Hi, calm down, minidom is not easy to use, but it can solve your problem. Dobedani wrote: > I guess I don't know where to look for the right information. I hope > you guys can help me on the way. I want to retrieve a string from an > XML-file. If Python were to have XPath available, my problem would be > solved. The xquery string would be enough and I have already obtained > that the string. The problem is that I cannot use any add-on - like > xmllib, sax2 or elementtree - as my customers only have the so-called > stock Python install - i.e. version 2.4.1. Too bad, that rules out lxml.etree (which has XPath and loads of other goodies). > Please: where then can I find examples of such use? If I cannot use > xpath, I would not mind to browse a bit - e.g. using functions like > getElementByTag() but I don't even know how to use those. TIA Try one of these (I looked for "minidom example"): http://www.faqs.org/docs/diveintopython/kgp_parse.html http://docs.python.org/lib/dom-example.html http://www.cutthecrap.biz/software/whitepapers/minidom.html Maybe that helps? Stefan From trebla at vex.net Mon Aug 20 18:22:19 2007 From: trebla at vex.net (Albert Y. C. Lai) Date: Mon, 20 Aug 2007 18:22:19 -0400 Subject: Xah's Edu Corner: Under the spell of Leibniz's dream In-Reply-To: <1187578927.945921.280180@q4g2000prc.googlegroups.com> References: <1187567809.896668.228650@z24g2000prh.googlegroups.com> <1187578927.945921.280180@q4g2000prc.googlegroups.com> Message-ID: Twisted wrote: > A link to a copy in a non-toxic format would be nice. http://www.cs.utexas.edu/users/EWD/transcriptions/EWD12xx/EWD1298.html From kyosohma at gmail.com Mon Aug 20 08:57:48 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 20 Aug 2007 05:57:48 -0700 Subject: datetime in microseconds In-Reply-To: <1187610776.755796.170990@r29g2000hsg.googlegroups.com> References: <1187610776.755796.170990@r29g2000hsg.googlegroups.com> Message-ID: <1187614668.711802.145740@q3g2000prf.googlegroups.com> On Aug 20, 6:52 am, mroelo... at gmail.com wrote: > Hi I have a time in microseconds, for example 0x8C905CBA7F84AF4. I > want this to a normal view in hh:mm:ss DD:MM:YYYY. I tried with > datetime, but it only takes a max of 1000000 microseconds is there > another solution? Just truncate the value so that it's less than 1000000. A slight difference of a couple seconds shouldn't matter for the output format you're talking about. Mike From korovev76 at gmail.com Wed Aug 8 11:15:41 2007 From: korovev76 at gmail.com (korovev76 at gmail.com) Date: Wed, 08 Aug 2007 08:15:41 -0700 Subject: parsing a dbIII file In-Reply-To: References: <1186469710.277542.246430@w3g2000hsg.googlegroups.com> Message-ID: <1186586141.625100.166810@57g2000hsv.googlegroups.com> On 7 Ago, 17:47, "Jerry Hill" wrote: > On 8/7/07, korove... at gmail.com wrote: > > > I have to parse a file (that is a dbIII file) whose stucture look like > > this: > > |string|, |string|, |string that may contain commas inside|, 1, 2, 3, | > > other string| > > The CSV module is probably the easiest way to go: > > >>> data = "|string|, |string|, |string that may contain commas > > inside|, 1, 2, 3, |other string|">>> import csv > >>> reader = csv.reader([data], quotechar="|", skipinitialspace=True) > >>> for row in reader: > > print row > > ['string', 'string', 'string that may contain commas inside', '1', > '2', '3', 'other string'] > > -- > Jerry you all were right, I had to mention that I must put the datas in mysql... So actually the best way to do it is with csv.reader: i tried it and it works out! thanx very much! From paul at boddie.org.uk Fri Aug 10 07:26:24 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 10 Aug 2007 04:26:24 -0700 Subject: The Future of Python Threading In-Reply-To: <1186740111.918048.77920@d30g2000prg.googlegroups.com> References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> Message-ID: <1186745184.074168.302560@x40g2000prg.googlegroups.com> On 10 Aug, 12:01, "Justin T." wrote: > > While I don't pretend to be an authority on the subject, a few days of > research has lead me to believe that a discussion needs to be started > (or continued) on the state and direction of multi-threading python. > > Python is not multi-threading friendly. Yes it is: Jython and IronPython support free threading; CPython, however, does not. Meanwhile, take a look at this page for different flavours of alternative solutions: http://wiki.python.org/moin/ParallelProcessing Paul From aleax at mac.com Mon Aug 27 11:07:50 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 27 Aug 2007 08:07:50 -0700 Subject: How to replace a method in an instance. References: <1187971953.261328.219000@q3g2000prf.googlegroups.com> <46cf2ba2$0$30562$426a74cc@news.free.fr> <1187984450.138147.62780@e9g2000prf.googlegroups.com> <46d282a9$0$415$426a74cc@news.free.fr> Message-ID: <1i3hv67.14vw1pfalghkcN%aleax@mac.com> Bruno Desthuilliers wrote: > >>> Of course, a function in a > >>> class is also know as a method. > >> Less obvious but still wrong !-) > > > > I wish the authors of the Python books would get a clue then. > > I'd think that at least some authors of some Python books would explain > all this much better than I did. But FWIW, all these rules are clearly > documented in the Fine Manual. Speaking as one such author, I think I do a reasonable job of this in "Python in a Nutshell" (2nd ed): on p. 82 and 85 I have brief mentions that "class attributes bound to functions are also known as methods of the class" (p.82) and again that "functions (called methods in this context) are important attributes for most class objects" (p.85); on p.91-94, after explaining descriptors, instances, and the basics of attribute reference, I can finally cover the subject thoroughly in "Bound and Unbound Methods". I realize that a beginner might be confused into believing that "class attributes bound to functions" means "function in a class", if they stop reading before p.91;-), but I don't literally make that wrong assertion...;-) Alex From http Wed Aug 22 01:46:02 2007 From: http (Paul Rubin) Date: 21 Aug 2007 22:46:02 -0700 Subject: for statement on empty iterable References: <1187760507.951994.50310@q4g2000prc.googlegroups.com> <7xabsk3zgm.fsf@ruckus.brouhaha.com> <1187761270.713307.224570@i38g2000prf.googlegroups.com> Message-ID: <7xejhw15r9.fsf@ruckus.brouhaha.com> james_027 writes: > Thanks for your quick answer ... Actually I was thinking how do I > access the index inside a for statement? Can you help It sounds like you're just starting to learn the language... have you read the online tutorial yet? That is a pretty easy introduction. See: http://python.org/doc/ Anyway, you can say for i in (1,2,3): print i*5 to print 5, 10, and 15 on separate lines, for example. From gnewsg3 at gmail.com Thu Aug 9 14:21:47 2007 From: gnewsg3 at gmail.com (billiejoex) Date: Thu, 09 Aug 2007 11:21:47 -0700 Subject: tempfile behavior Message-ID: <1186683707.869668.316360@g4g2000hsf.googlegroups.com> Hi all, I would like to use tempfile module to generate files having unique names excepting that I don't want them to be removed after closing. Does it is possible? From kay.schluehr at gmx.net Sun Aug 12 03:26:09 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 12 Aug 2007 00:26:09 -0700 Subject: is there anybody using __del__ correctly?? In-Reply-To: <1186731369.073644.158490@z24g2000prh.googlegroups.com> References: <1186731369.073644.158490@z24g2000prh.googlegroups.com> Message-ID: <1186903569.106760.203300@o61g2000hsh.googlegroups.com> On Aug 10, 9:36 am, Michele Simionato wrote: > P.S. BTW, I should mention that if you search comp.lang.python for > __del__ > you will find hundreds of people who were bitten by __del__, so I > usually give > advices such as "you should never __del__ in your code". If I am wrong > in > giving this advice, please let me know! I wish we had constructive proofs of cycle freedom and appropriate warnings - much more then __del__ freedom [1]. Well, we discussed a retro computing example yesterday where some guy needed to close a generator and release resources, still working with Python 2.4. http://groups.google.com/group/comp.lang.python/browse_frm/thread/3f789096bded17e7/?hl=en# We did it both wrong initially and constructed a reference cycle. Now I keep my fingers crossed that my most recent solution using __del__ works, because I like it :) [1] While I'm using Python on and off I feel subconsciously attracted by the latest Haskell mania and start to dream alike. Maybe I should visit a shrink or a shaman? From brett at python.org Mon Aug 20 16:37:58 2007 From: brett at python.org (Brett Cannon) Date: Mon, 20 Aug 2007 13:37:58 -0700 Subject: Moving Python's tracker to Roundup on Aug 23rd Message-ID: On August 23rd Python will be moving off of SourceForge and over to our own issue tracker run on Roundup (http://bugs.python.org/). During the transition there will be a time where the SourceForge tracker is no longer being used but that the new tracker has not been brought up yet. We expect this gap to be for a few hours. But to minimize issues, please try to avoid using either SourceForge or the new issue tracker on Aug 23rd if you can. -Brett Cannon Chairman, PSF Infrastructure committee From db3l.net at gmail.com Thu Aug 30 17:27:29 2007 From: db3l.net at gmail.com (David Bolen) Date: Thu, 30 Aug 2007 17:27:29 -0400 Subject: Unzip: Memory Error References: <1188413939.834662.193180@y42g2000hsy.googlegroups.com> <1188472431.290871.103720@o80g2000hse.googlegroups.com> Message-ID: I wrote: > Here's a small example of a ZipFile subclass (tested a bit this time) > that implements two generator methods: Argh, not quite tested enough - one fix needed, change: if bytes[-1] not in ('\n', '\r'): partial = lines.pop() to: if bytes[-1] not in ('\n', '\r'): partial = lines.pop() else: partial = '' (add the extra two lines) -- David From omelnyk at gmail.com Mon Aug 20 05:37:31 2007 From: omelnyk at gmail.com (Olexandr Melnyk) Date: Mon, 20 Aug 2007 12:37:31 +0300 Subject: Where we need to use Python ? In-Reply-To: <1187596936.136499.200280@l22g2000prc.googlegroups.com> References: <1187596936.136499.200280@l22g2000prc.googlegroups.com> Message-ID: 2007/8/20, gperumal at gmail.com : > > Hi > > Iam new to Python > I know Perl, JScript,C,C++,Java > But i want to know where excatly this python come in to picture > > And Is it a interpreted language or a programming language > It comes in which category > > I very keen to know this please tell Python is an interpreted programming languages, although there are compiled implementations. You can use it for a variety of tasks, except low-level programming. Regards > Ganesh P > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Sincerely yours, Olexandr Melnyk http://omelnyk.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From arkanes at gmail.com Mon Aug 6 16:43:52 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 6 Aug 2007 15:43:52 -0500 Subject: Tkinter or wxpython? In-Reply-To: <7x8x8oqy17.fsf@ruckus.brouhaha.com> References: <1186410331.905174.21370@q3g2000prf.googlegroups.com> <7xps204tin.fsf@ruckus.brouhaha.com> <7xlkcopu4r.fsf@ruckus.brouhaha.com> <7x3aywr4tc.fsf@ruckus.brouhaha.com> <7x8x8oqy17.fsf@ruckus.brouhaha.com> Message-ID: <4866bea60708061343s3cc53df7i7b4d910e80db38a0@mail.gmail.com> On 06 Aug 2007 12:10:44 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > "Chris Mellon" writes: I had a bunch of replies to each section but I think this is getting too long so I'll sum up. You repeatedly have used the word "slickness" as a pejorative. I find that offensive and it's insulting to users. When I write applications, I want the interface to be as smooth and trouble free as possible, with a simple a learning curve and the fewest possible bumps for them. This isn't a matter of adding chrome or shine or rounded corners and specular highlights. It's about letting them enjoy working with an application instead of tolerating it. It's the same reason I use Python and not C. It's about respect for their time and their preferences. As a matter of time spent in development, I do not find that non-trivial UIs are significantly easier to develop using web interfaces. As a matter of respect for the user, I'm not going to tell them to use a trivial UI if a non-trivial one will save them time, learning effort, or frustration. In order to make this decision, I like to work with the people actually using it and watch them at work. To see what kind of extra steps they have to take and where I can save them time or inaccuracy or frustration. From horpner at yahoo.com Thu Aug 30 13:59:57 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 30 Aug 2007 17:59:57 GMT Subject: Python doesn't see the directories I create References: <46d6856b$0$17674$426a74cc@news.free.fr> Message-ID: On 2007-08-30, Steve Holden wrote: > Neil Cerutti wrote: >> To me, Python's collection of special-purpose string literal >> notations is one of its little warts. > > Well, it's a wart that's shared with many other languages - > including, interestingly enough, Microsoft's very own C#, from > whose documentation the following examples are taken: > > string a = "hello, world"; // hello, world > string b = @"hello, world"; // hello, world > string c = "hello \t world"; // hello world > string d = @"hello \t world"; // hello \t world > string e = "Joe said \"Hello\" to me"; // Joe said "Hello" to me > string f = @"Joe said ""Hello"" to me"; // Joe said "Hello" to me > string g = "\\\\server\\share\\file.txt"; // \\server\share\file.txt > string h = @"\\server\share\file.txt"; // \\server\share\file.txt > string i = "one\r\ntwo\r\nthree"; Still, that's only two. > The fact is that some strings are always going to cause > trouble. Unfortunately programming itself is a task that > requires a little more knowledge to be applied to the task. Or fortunately, depending on the dictates of your temperament. ;) -- Neil Cerutti From franz.steinhaeusler at gmx.at Sun Aug 5 16:52:22 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhäusler) Date: Sun, 05 Aug 2007 22:52:22 +0200 Subject: Best programs written completly in Python References: <1186338373.738163.257890@o61g2000hsh.googlegroups.com> Message-ID: On Sun, 05 Aug 2007 11:26:13 -0700, markacy wrote: >On 5 Sie, 12:14, Franz Steinh?usler >wrote: >> Hello NG, >> >> wWhat are the best programs in your opinion, written entirly >> in pyhton, divided into categories like: >> a) Games >> b) Utilities/System >> c) Office >> d) Web/Newsreader/Mail/Browser >> ... >> >> I don't want to start a long thread, if a site of such >> an discussion already exists, a link will be enough. >> >> Many thanks in advance! >> >> -- >> Franz Steinhaeusler > >I guess, that gentoo's portage is (almost?) entirely written in >python. The same is with Zope/Plone (Web category), though I know, >that Zope has some parts of code written in C. Django? > >Big part's of google "tools" are written in python as well. Matplotlib >is said to be written entirely in python. >These are examples from the top of my head. If I'll came up with >something else, I will let You know :-) > >Cheers, >Marek Ah yes of course, One or I, often see only programs, which is "closed in itself", like an editor, viewer, newsreader, and oversee, that big parts of "invisible" software is written in python. Thank you for mentioning that pieces of software! -- Franz Steinhaeusler From horpner at yahoo.com Thu Aug 9 16:28:57 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 09 Aug 2007 20:28:57 GMT Subject: Puzzled by "is" References: <20070809194105.39BD11E400A@bag.python.org> Message-ID: On 2007-08-09, John K Masters wrote: > On 15:53 Thu 09 Aug , Steve Holden wrote: >> Dick Moores wrote: >> > At 10:46 AM 8/9/2007, Bill Scherer wrote: >> >> Dick Moores wrote: >> [...] >> >> There is only one empty tuple. >> >> Does that clear it up for you? >> > >> > But isn't that the same as saying, "That's just the reality of >> > Python; it is what it is."? I want to know why there is only one >> > empty tuple, but more than one (1,). >> > >> Why? Because. >> >> Seriously, it's just an optimization by the implementers. There is no >> need for more than one empty tuple, since tuples can never be modified >> once created. >> >> But they decided not to create (1, ) in advance. They probably knew that >> hardly anybody would want to create that tuple ;-) [Seriously: if you >> started trying to predict which tuples would be used you would go >> insane, but the empty tuple is the most likely candidate]. >> >> > Also, >> > >>> [] is [] >> > False >> > >> In that case it would definitely NOT make sense to have them the same >> list. Python always ensures that the [] constructor creates a new list, >> since that list may be bound to one or more variables and mutated. You >> wouldn't want >> >> a = [] >> b = [] >> a.append("boo!") >> >> to change b so it was no longer an empty list. If you wanted a and b to >> reference the same list you would change the second statement to >> >> b = a >> >> regards >> Steve > > OK fiddling around with this and reading the docs I tried:- > a = 'qqqqqqqqqq' #10 q's > b = 'qqqqqqqqqq' #10 q's CPython is full of cute little optimizations, and one of them is that literal strings less than a certain length are 'interned'. This makes them very fast to compare for equality, and cheaper to store (maybe?). > a is b > true > c = 'q' * 10 > c > 'qqqqqqqqqq' #10 q's > d = 'q' * 10 > d > 'qqqqqqqqqq' #10 q's > c is d > false > > So from what I've read "==" tests for equivalence, "is" tests > for identity but that does not explain the behaviour above. The 10 q's constructed with string arithmetic were not interned, because they were not literals. -- Neil Cerutti From bdesth.quelquechose at free.quelquepart.fr Wed Aug 22 01:52:39 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 22 Aug 2007 07:52:39 +0200 Subject: Regular expression use In-Reply-To: References: Message-ID: <46cf2ca6$0$30562$426a74cc@news.free.fr> Nick Maclaren a ?crit : > For reasons that I won't explain, as they are too complicated > and not terribly relevant, I am interested in discovering what > people actually use regular expressions for. Usually, to obfuscate code. Sometimes for good reasons.... Hu ? Ok, me get out ---->[] From horpner at yahoo.com Fri Aug 3 10:32:32 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 03 Aug 2007 14:32:32 GMT Subject: (no) fast boolean evaluation ? References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> <46b2e56b$0$18879$426a74cc@news.free.fr> Message-ID: On 2007-08-03, Steven D'Aprano wrote: > But that's specific to the syntax of the language. You could, > if you choose, design a language where elif was unnecessary: > > if condition: > pass > else if another_condition: > pass > > What advantage is there to "elif", apart from it needing three > fewer characters to type? It's a great boon to the authors of auto-indenting text editors. -- Neil Cerutti From coyote_x at artcom.pl Thu Aug 2 02:27:05 2007 From: coyote_x at artcom.pl (Adam Kubica) Date: Thu, 02 Aug 2007 08:27:05 +0200 Subject: Equivalent to gzinflate() function in PHP. References: <1185976461.491418.20230@i38g2000prf.googlegroups.com> Message-ID: On Thu, 02 Aug 2007 08:17:13 +0200, Adam Kubica wrote: > On Wed, 01 Aug 2007 13:54:21 +0000, kyosohma wrote: > >> On Aug 1, 8:44 am, Adam Kubica wrote: >>> Hellou. >>> >>> Anybody know about code that work equivalent to gzinflate() >>> function used in PHP? >>> >>> I search via google but I don't found anything sensible :-( >> >> I'm not sure what gzinflate does, but it looks like it's some kind of >> compression/decompression method. Python can do that. Check out the >> following links: >> >> http://www.python.org/doc/lib/module-gzip.html >> http://www.python.org/doc/lib/module-zlib.html >> http://python.active-venture.com/lib/module-bz2.html >> >> Hopefully this is the type of thing you were looking for. >> > > OK, but it isn't that I looking for :-( > > gzinflate() is reversed function of gzdeflate(), zlib module allows to use > compress methon only, it's equivalent to gzcompress() in PHP. After some king of brain fucked tries, I found: zlib.decompress( data ) #equivalent gzdecompress() zlib.decompress( data, -zlib.MAX_WBITS ) #equivalent gzdeflate() Thanks :-) From theshadowx at gmail.com Thu Aug 23 15:28:35 2007 From: theshadowx at gmail.com (TheShadow) Date: Thu, 23 Aug 2007 19:28:35 -0000 Subject: Question about embedding python in C++ In-Reply-To: <1187896641.618261.51350@e9g2000prf.googlegroups.com> References: <1187891085.147246.19380@i38g2000prf.googlegroups.com> <1187896641.618261.51350@e9g2000prf.googlegroups.com> Message-ID: <1187897315.582592.10400@x35g2000prf.googlegroups.com> On Aug 23, 1:17 pm, TheShadow wrote: > On Aug 23, 11:57 am, Farshid Lashkari wrote: > > > TheShadow wrote: > > > When extending python in c/c++ after you register a module is there a > > > way in c/c++ to check if they were correctly registered? > > > > Cause I'm having the problem where when I execute the the python > > > script it finds the module but none of the functions. > > > Are you calling Py_InitModule(...) in your initmodule function? If so, > > Py_InitModule(...) returns a reference to the module object. You can use > > this object to double check that your function names exist in the > > modules dictionary. Most likely, there is an error in your code. If you > > post it, it would be easier to tell what the problem is. > > > -Farshid > > Alright that was a dead end. Here is the source code. > > bool CPythonModule::Register() > { > bool bReturn = false; > unsigned int uiSize = static_cast int>(m_LPyMethodDefs.size()); > if (m_LPyMethodDefs.size() > 0) > { > m_pEmbMethods = new PyMethodDef[m_LPyMethodDefs.size()+1]; > unsigned int uiCounter = 0; > > IterQPyMethodDefs iterMethods = m_LPyMethodDefs.begin(); > > while (m_LPyMethodDefs.end() != iterMethods) > { > m_pEmbMethods[uiCounter].ml_name = > m_LPyMethodDefs.front().sName.c_str(); > m_pEmbMethods[uiCounter].ml_meth = > m_LPyMethodDefs.front().pFunction; > m_pEmbMethods[uiCounter].ml_flags = m_LPyMethodDefs.front().iFlags; > m_pEmbMethods[uiCounter].ml_doc = > m_LPyMethodDefs.front().sDoc.c_str(); > > ++uiCounter; > ++iterMethods; > } > > PyMethodDef PyMethodNullDef = {NULL, NULL, 0, NULL}; > > m_pEmbMethods[uiSize] = PyMethodNullDef; > > Py_InitModule(m_sModuleName.c_str(),m_pEmbMethods); > > //PythonInterfaceInst->RegisterModule(this); > > m_pInitFunc(); > > bReturn = true; > } > return bReturn; > > } Forget I said anything I found my bug... I was using m_LPyMethodDefs instead of my iterator... hurray for writing code at 12am :P From bbxx789_05ss at yahoo.com Fri Aug 10 05:40:13 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 10 Aug 2007 02:40:13 -0700 Subject: wxPython - drawing without paint event In-Reply-To: <1186710391.148396.113490@d30g2000prg.googlegroups.com> References: <1186710391.148396.113490@d30g2000prg.googlegroups.com> Message-ID: <1186738813.373909.96230@x35g2000prf.googlegroups.com> On Aug 9, 7:46 pm, Matt Bitten wrote: > I've got a wxPython program that needs to do some drawing on a DC on a > regular basis.... And there is no event, > so my code doesn't get called. What do I do? Then the event is: "on a regular basis", i.e. the passage of time. You can use a wx.Timer to create events at regular intervals, which your code can respond to: ------- import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "My Window") panel = wx.Panel(self, -1) self.text = wx.StaticText(panel, -1, "hello", pos=(40, 40) ) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_timer_event) self.timer.Start(milliseconds=1000, oneShot=False) def on_timer_event(self, event): if self.text.GetLabel() == "hello": self.text.SetLabel("goodbye") else: self.text.SetLabel("hello") app = wx.App(redirect=False) win = MyFrame() win.Show() app.MainLoop() ---------------- Make sure you save the timer in self so that you have a permanent reference to the object, otherwise the timer will be destroyed when __init_ returns. From gagsl-py2 at yahoo.com.ar Wed Aug 22 10:01:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 22 Aug 2007 07:01:49 -0700 Subject: redirect or cover .bat log In-Reply-To: <1187787876.962883.66970@r34g2000hsd.googlegroups.com> References: <1187764689.836375.212730@z24g2000prh.googlegroups.com> <5j26bvF3s7lbpU2@mid.uni-berlin.de> <1187767578.925671.107000@q4g2000prc.googlegroups.com> <5j2br6F3r2avsU1@mid.uni-berlin.de> <1187787876.962883.66970@r34g2000hsd.googlegroups.com> Message-ID: <1187791309.427046.22400@q3g2000prf.googlegroups.com> On 22 ago, 10:04, vedrandeko... at v-programs.com wrote: > > > >> > e.g I need run my my_scripts_setup.bat that contain: > > > >> > python myscript_setup.py py2exe > > > >> > Can I cover or redirect log of that process into my wx program? > > >> > I'am using Windows XP SP2, and Python 2.5. Try the subprocess module. For the single line command you posted earlier, you don't even need the bat file: import subprocess p = subprocess.Popen(["python", "myscript_setup.py", "py2exe"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.wait() output_from_process = p.stdout.readlines() This would be fine if executing the script takes relatively a short time and doesn't generate so many output lines; there are other examples in the subprocess module documentation -- Gabriel Genellina From rcdailey at gmail.com Sat Aug 11 18:00:57 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Sat, 11 Aug 2007 17:00:57 -0500 Subject: I am giving up perl because of assholes on clpm -- switching to Python In-Reply-To: References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> Message-ID: <496954360708111500k6764d019p7cbf74b1df399b94@mail.gmail.com> I had this very same problem with the doxygen mailing list... doxygen is such a great tool but full of assholes in their mailing list. On 8/2/07, Jamie wrote: > > In <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d at giganews.com>, > Martha_Jones at tx.net mentions: > >Python is a better language, with php support, anyway, but I am fed up > >with attitudes of comp.lang.perl.misc. Assholes in this newsgroup ruin > >Perl experience for everyone. Instead of being helpful, snide remarks, > >back-biting, scare tactings, and so on proliferate and self > >reinforce. All honest people have left this sad newsgroup. Buy bye, > >assholes, I am not going to miss you!!! > > > >Martha > > I've heard people tell the same story, that perl folks are... rude. > > Actually, I've pretty much heard (and noticed) that about linux, too. > > Yet, linux is still a good operating environment, so is perl. > > You'll find rude people everywhere you look. While it may be true that > there is a higher percentage of hard-core tech folks who might lack > social skills, at least they don't err.. well, maybe they do.. byte. :-) > > Seriously, it is one of the problems facing perl (and linux) people ARE > turned away by the attitude. It is rather embarassing/unflattering when > someone is critical of your work. > > I see a lot of ideas about things should be "made easier" but I think > thats the wrong course. We really just need to be nicer to new folks. > > Jamie > -- > http://www.geniegate.com Custom web programming > Perl * Java * UNIX User Management Solutions > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gerard.blais at gmail.com Fri Aug 17 09:38:18 2007 From: gerard.blais at gmail.com (Gerry) Date: Fri, 17 Aug 2007 13:38:18 -0000 Subject: Question on SPE and pwintypes.dll Message-ID: <1187357898.740425.33170@r29g2000hsg.googlegroups.com> I'm running SPE 8.3.c under XP, on a new PC. The files for SPE and Python were copied to the new machine, but the OS wasn't migrated, so the registry didn't know about either. I reinstalled Python 2.5.1, and Python seems fine. I made a shortcut to SPE.pyw. Clicking on the shortcut gives an error pop-up, application failed to start cannot find pwintypes.dll. When I click "OK", SPE seems to start normally. Any idea what's up? Googling for pwintypes.dll didn't give me any hits. Gerry From bob at cosy.com Tue Aug 14 13:54:51 2007 From: bob at cosy.com (Bob Armstrong) Date: Tue, 14 Aug 2007 10:54:51 -0700 Subject: (Re)announcing APL 2007 In-Reply-To: <1186406430.744134.298400@x35g2000prf.googlegroups.com> References: <5hnkb3F3hus4jU1@mid.individual.net> <1186406430.744134.298400@x35g2000prf.googlegroups.com> Message-ID: <1187114091.809246.308200@x40g2000prg.googlegroups.com> On Aug 6, 7:20 am, Paul Mansour wrote: > APL2007 Roll Call: Is anyone going to this? I'm thinking of going also , setting up some arrangement to provide an introductory tutorial to my free and open 4th.CoSy . My website is transiting between hosts so I don't recommend even looking at it right now . But by the end of the month I should be uploading a system with the Forth integrated and usable multiple windows ala K's "electric gui" . Hopefully by conference time , I'll have my recursive , quite APLish syntax , interpreter working . From bj_666 at gmx.net Wed Aug 15 15:09:30 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Aug 2007 19:09:30 GMT Subject: "Variable variable name" or "variable lvalue" References: <1187199722.618893.281170@r29g2000hsg.googlegroups.com> Message-ID: <5ih1baF3mc1akU3@mid.uni-berlin.de> On Wed, 15 Aug 2007 10:42:02 -0700, mfglinux wrote: > I would like to know how to declare in python a "variable name" that > it is in turn a variable > In bash shell I would wrote sthg like: > > for x in `seq 1 3` > do > M$i=Material(x) #Material is a python class > done You want a dictionary. M = dict() for x in xrange(1, 4): M[x] = Material(x) Ciao, Marc 'BlackJack' Rintsch From martin at v.loewis.de Thu Aug 23 22:26:20 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 24 Aug 2007 04:26:20 +0200 Subject: MsiLib In-Reply-To: References: <46CDE72F.2090009@v.loewis.de> Message-ID: <46CE41CC.7010105@v.loewis.de> > Thank you. I would be willing to help out, but as of now I have no idea > how to get started on it. If you would be willing to provide some > guidance, then I would be fine with giving it a shot if nothing more. My > guess is that it would have to implement the MsiRecordGetString function > so that it is accessible, but I don't know beyond that. See PC/_msi.c. If I give further guidance than that, I may well do it myself. Regards, Martin From steven.bethard at gmail.com Sun Aug 12 18:09:52 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 12 Aug 2007 16:09:52 -0600 Subject: A dumb question about a class In-Reply-To: References: Message-ID: Dick Moores wrote: > I'm still trying to understand classes. I've made some progress, I > think, but I don't understand how to use this one. How do I call it, or > any of its functions? It's from the Cookbook, at > . The short answer is that use should look something like:: >>> plist = PrimeList() >>> plist.contains(32) False >>> plist.contains(23) True But this doesn't seem like a particularly good recipe. Seems like you would really rather be writing code like:: >>> plist = PrimeList() >>> 1 in plist False >>> 2 in plist True >>> 22 in plist False >>> 23 in plist True >>> 782 in plist False >>> 787 in plist True Here's how I'd write the recipe:: import itertools def iter_primes(): # an iterator of all numbers between 2 and +infinity numbers = itertools.count(2) # generate primes forever while True: # get the first number from the iterator (always a prime) prime = numbers.next() yield prime # remove all numbers from the (infinite) iterator that are # divisible by the prime we just generated numbers = itertools.ifilter(prime.__rmod__, numbers) class PrimeList(object): def __init__(self): # infinite iterator of primes self._prime_iter = iter_primes() # the last prime we've seen self._last_prime = None # all primes seen so far self._prime_set = set() # add the first prime (so that _last_prime is set) self._add_prime() def __contains__(self, n): # add primes to the list until we exceed n while n > self._last_prime: self._add_prime() # return True if n is one of our primes return n in self._prime_set def _add_prime(self): # take a prime off the iterator and update the prime set self._last_prime = self._prime_iter.next() self._prime_set.add(self._last_prime) STeVe From carsten at uniqsys.com Fri Aug 31 00:06:54 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 31 Aug 2007 00:06:54 -0400 Subject: list index() In-Reply-To: <1188530220.815429.281380@i38g2000prf.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188495863.242815.236900@o80g2000hse.googlegroups.com> <87bqcod2gq.fsf@benfinney.id.au> <1188517370.998114.119940@q4g2000prc.googlegroups.com> <1188530220.815429.281380@i38g2000prf.googlegroups.com> Message-ID: <20070831035715.M82687@uniqsys.com> On Thu, 30 Aug 2007 20:17:00 -0700, zzbbaadd wrote > Well IN was what I was looking for and would have saved this thread. > However I don't believe IN showed up on the doc web page that has > list methods, where I found index(). They're not on the exact same page, but index() is in section 3.6.4 of the library reference (http://docs.python.org/lib/typesseq-mutable.html), whereas "in" is in section 3.6 of the library reference (http://docs.python.org/lib/typesseq.html). I'm wondering how you managed to find subsection 3.6.4 without finding section 3.6. -- Carsten Haese http://informixdb.sourceforge.net From raims at dot.com Mon Aug 13 06:20:16 2007 From: raims at dot.com (Lawrence Oluyede) Date: Mon, 13 Aug 2007 12:20:16 +0200 Subject: retrieving ATOM/FSS feeds References: <1i2s7c9.13bkwbfsd3mbqN%raims@dot.com> Message-ID: <1i2sa2z.sr8171gbnn76N%raims@dot.com> _spitFIRE wrote: > For the same feed (where the content producer doesn't provide the full > article!) I was able to see the complete post in other RSS aggregators (like > Blam). I wanted to know how they were able to collect the feed! Perhaps in the feed itself there's the link for the full content feed. -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From ldo at geek-central.gen.new_zealand Mon Aug 27 05:33:45 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 27 Aug 2007 21:33:45 +1200 Subject: my parser.py isn't imported References: <874pimqpei.fsf@wilson.homeunix.com> <1188166462.066732.123620@i13g2000prf.googlegroups.com> <87ps19q5fs.fsf@wilson.homeunix.com> Message-ID: In message <87ps19q5fs.fsf at wilson.homeunix.com>, Torsten Bronger wrote: > So I'd like to know a means to tell *explicitly* what I want to > import. Maybe I could use the imp module but that's ugly. That seems to be the standard Python-provided way to explicitly import the file you want from the place you want. > I mean, there are hundreds of modules on my harddisk, so trying to avoid > nameclashs should not be the solution... That is what namespace qualifiers are for, e.g. import my_custom_stuff.parser versus import parser > John Machin writes: > >> 2. Failure to RTFabulousM: >> """ >> Details of the module searching and loading process are >> implementation and platform specific. It generally involves >> searching for a ``built- in'' module with the given name and then >> searching a list of locations given as sys.path. >> """ > > ... the whole systems seems largely arbitrary, which I don't > believe. ;-) The documentation says quite clearly that the search order is controlled by sys.path. So why not manipulate that to get the effect you want? > "parser" is built-in on Windows but not on Linux. It is standard on all platforms . From bignose+hates-spam at benfinney.id.au Tue Aug 28 20:58:27 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 29 Aug 2007 10:58:27 +1000 Subject: "Try:" which only encompasses head of compound statement References: <1188250535.607963.42540@22g2000hsm.googlegroups.com> <87wsvgfszm.fsf@benfinney.id.au> <13d7898odj2g19b@corp.supernews.com> <87fy24fdgf.fsf@benfinney.id.au> <1188345076.396437.111160@w3g2000hsg.googlegroups.com> Message-ID: <873ay3f970.fsf@benfinney.id.au> Jameson.Quinn at gmail.com writes: > In real life, I want to set some return values to sensible defaults > if the file doesn't exist, but I want the errors from inside the > block to trickle up as normal. Sure. Just be careful only to catch the exceptions that you do want to handle at that level of the code, and the others will propagate normally. > And yes, I can easily use a temporary variable for the open file, > but it really seems to me that this defeats the purpose of the > 'with' statement - if this were something more dangerous than a > file, I'd feel mighty leery of having it in a temporary variable > outside a 'with' for even a moment. You seem to be confused about one or both of "variables" (which Python doesn't really have) and the 'with' statement. When you write:: input_file = open("foo.txt") with input_file: # do stuff there's no "temporary variable". You've merely bound the name 'input_file' to the file object; it's the same file object as is then used in the 'with' statement. You could bind a dozen other names to the object and it would still be the same file object. So, when the 'with' block exits, the context manager will close the file object, no matter how many names you bind to it. > So, the options are: > -temporary variable - could this EVER be more dangerous than the with > statement (KeyboardInterrupt which is later caught and handled?) Since it's not a "temporary variable" but rather just a way to refer to the file object, I don't see the issue you're describing. However you refer to it, that one file object will be closed when the 'with' block exits. > -'tunnel' internal exceptions past the try by wrapping them in a > TunnelException and then unwrapping them with a containing try block. > > The second looks like a hack to me Yes, it is. Catch the exceptions you want to handle, let the rest propagate normally. The context manager created by the 'with' statement will handle closing the file *and* propagate the exception normally. > and the first still feels dangerous. If it's still that way, perhaps you could be more explicit about what danger you think exists? -- \ "Are you pondering what I'm pondering?" "I think so, Brain, but | `\ pants with horizontal stripes make me look chubby." -- _Pinky | _o__) and The Brain_ | Ben Finney From geoff.bache at pobox.com Tue Aug 28 13:57:36 2007 From: geoff.bache at pobox.com (geoffbache) Date: Tue, 28 Aug 2007 10:57:36 -0700 Subject: Getting subprocesses to be hidden on Windows In-Reply-To: <1188310805.381229.13270@y42g2000hsy.googlegroups.com> References: <1188246076.131276.292010@r34g2000hsd.googlegroups.com> <1188250115.875160.276780@r29g2000hsg.googlegroups.com> <1188292102.065625.82670@22g2000hsm.googlegroups.com> <1188308231.196513.291260@19g2000hsx.googlegroups.com> <1188309590.114918.257670@y42g2000hsy.googlegroups.com> <1188310805.381229.13270@y42g2000hsy.googlegroups.com> Message-ID: <1188323856.443131.223550@r34g2000hsd.googlegroups.com> OK, more background needed. I develop the TextTest tool which is a generic test tool that starts tested applications from the command line. The idea is that it can handle any system under test at all, whatever language it's written in. Preferably without requiring a bunch of changes to the tested code before starting. I'd like to be able to pass some sort of flag to ensure that the system under test *and everything it starts* remain hidden. I can do as you suggest in my PyGTK GUI, of course, but that's only one system under test. A generic solution, if there is one, would be much better. I felt like there ought to be one because : a) It's easy on UNIX and b) I managed to hide the system under test fairly easily, just not its child windows and dialogs. Thanks for the help, anyway, it's another fallback if I can't find a solution. From goldtech at worldpost.com Sat Aug 4 18:51:27 2007 From: goldtech at worldpost.com (goldtech) Date: Sat, 04 Aug 2007 15:51:27 -0700 Subject: Client-side HTML form processing with Python? In-Reply-To: References: <1186263839.778333.143200@d30g2000prg.googlegroups.com> Message-ID: <1186267887.116300.301280@x35g2000prf.googlegroups.com> Looks like Tkinter is the way to do it. There's always a way with Python - good stuff! From theshadowx at gmail.com Thu Aug 23 15:17:21 2007 From: theshadowx at gmail.com (TheShadow) Date: Thu, 23 Aug 2007 19:17:21 -0000 Subject: Question about embedding python in C++ In-Reply-To: References: <1187891085.147246.19380@i38g2000prf.googlegroups.com> Message-ID: <1187896641.618261.51350@e9g2000prf.googlegroups.com> On Aug 23, 11:57 am, Farshid Lashkari wrote: > TheShadow wrote: > > When extending python in c/c++ after you register a module is there a > > way in c/c++ to check if they were correctly registered? > > > Cause I'm having the problem where when I execute the the python > > script it finds the module but none of the functions. > > Are you calling Py_InitModule(...) in your initmodule function? If so, > Py_InitModule(...) returns a reference to the module object. You can use > this object to double check that your function names exist in the > modules dictionary. Most likely, there is an error in your code. If you > post it, it would be easier to tell what the problem is. > > -Farshid Alright that was a dead end. Here is the source code. bool CPythonModule::Register() { bool bReturn = false; unsigned int uiSize = static_cast(m_LPyMethodDefs.size()); if (m_LPyMethodDefs.size() > 0) { m_pEmbMethods = new PyMethodDef[m_LPyMethodDefs.size()+1]; unsigned int uiCounter = 0; IterQPyMethodDefs iterMethods = m_LPyMethodDefs.begin(); while (m_LPyMethodDefs.end() != iterMethods) { m_pEmbMethods[uiCounter].ml_name = m_LPyMethodDefs.front().sName.c_str(); m_pEmbMethods[uiCounter].ml_meth = m_LPyMethodDefs.front().pFunction; m_pEmbMethods[uiCounter].ml_flags = m_LPyMethodDefs.front().iFlags; m_pEmbMethods[uiCounter].ml_doc = m_LPyMethodDefs.front().sDoc.c_str(); ++uiCounter; ++iterMethods; } PyMethodDef PyMethodNullDef = {NULL, NULL, 0, NULL}; m_pEmbMethods[uiSize] = PyMethodNullDef; Py_InitModule(m_sModuleName.c_str(),m_pEmbMethods); //PythonInterfaceInst->RegisterModule(this); m_pInitFunc(); bReturn = true; } return bReturn; } From skip at pobox.com Thu Aug 2 14:30:00 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 2 Aug 2007 13:30:00 -0500 Subject: __call__ considered harmful or indispensable? Message-ID: <18098.8872.263489.36952@montanaro.dyndns.org> I don't personally use __call__ methods in my classes, but I have encountered it every now and then here at work in code written by other people. The other day I replaced __call__ with a more obvious method name, so now instead of executing obj(foo, bar, baz) the code in question is obj.execute(foo, bar, baz) In this case there was a bug. Depending on inputs, sometimes obj initialized to a class, sometimes an instance of that class. (I fixed that too while I was at it.) The problem was that the use of __call__ obscured the underlying bug by making the instance as well as the class callable. In this particular case it was clearly unnecessary and just obfuscated the code. I'm wondering, are there some general cases where __call__ methods of a user-defined class are simply indispensable? Thx, Skip From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Aug 27 03:53:27 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 27 Aug 2007 09:53:27 +0200 Subject: How to replace a method in an instance. In-Reply-To: <1187984450.138147.62780@e9g2000prf.googlegroups.com> References: <1187971953.261328.219000@q3g2000prf.googlegroups.com> <46cf2ba2$0$30562$426a74cc@news.free.fr> <1187984450.138147.62780@e9g2000prf.googlegroups.com> Message-ID: <46d282a9$0$415$426a74cc@news.free.fr> kyosohma at gmail.com a ?crit : > On Aug 22, 12:48 am, Bruno Desthuilliers > wrote: >> kyoso... at gmail.com a ?crit : >> (snip) >>> Of course, a function in a >>> class is also know as a method. >> Less obvious but still wrong !-) > > > I wish the authors of the Python books would get a clue then. I'd think that at least some authors of some Python books would explain all this much better than I did. But FWIW, all these rules are clearly documented in the Fine Manual. > (snip) > I'm not going to help with these class / instance / whatever any more > and leave it to all you professionals. How do you think I learned ? One of the big things with usenet is that you get a chance to be corrected when you're wrong, and I personnally owe a lot of thanks to all the people that corrected me so far and still correct me. > Yes, it you can use self in an outside method, but the way the OP > asked the question and the nature of the traceback pointed to it just > being a normal function, Indeed, Steve's problem was that the function he attached to his instance was *not* wrapped into a method object. From hd1956 at yahoo.com Mon Aug 20 18:47:16 2007 From: hd1956 at yahoo.com (hd1956 at yahoo.com) Date: Mon, 20 Aug 2007 15:47:16 -0700 Subject: Newbee Question In-Reply-To: <1187622390.854759.162320@q3g2000prf.googlegroups.com> References: <1187621470.484615.7010@i13g2000prf.googlegroups.com> <1187622390.854759.162320@q3g2000prf.googlegroups.com> Message-ID: <1187650036.450645.185500@a39g2000hsc.googlegroups.com> On Aug 20, 11:06 am, kyoso... at gmail.com wrote: > On Aug 20, 9:58 am, "Shawn Milochik" wrote: > > > > > > > On 8/20/07, kyoso... at gmail.com wrote: > > > > On Aug 20, 9:23 am, "HD1956" wrote: > > > > This is probably a simple code. I am a truck driver who gets paid by > > > > stops and cases. I am trying to figure out how to code my stop pay. I > > > > get 40 cents per stop up to 22 stops, and $1.40 per stops after that. > > > > def calc(num): > > > if num < 23: > > > return 0.4 * num > > > else: > > > overtime = num - 22 > > > x = 0.4 * 22 > > > x += overtime * 1.4 > > > return x > > > > # Use your own brain next time > > > > Mike > > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > Mike, > > > I wonder if we were both just duped into helping someone with their homework... > > > Shawn > > I like to write code, so it's not a big deal when it's something so > simple. Still, that is beyond dumb! Nice code, by the way. > > Mike- Hide quoted text - > > - Show quoted text - Thanks for the help. By the way I am trying to learn the python after work and on weekends. If it was a dumb question, to this group, I will not bother you all again. Without help it will take me longer to learn. Thanks From __peter__ at web.de Tue Aug 7 04:03:32 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 07 Aug 2007 10:03:32 +0200 Subject: Regular Expression Groups - loop References: <1186472689.488634.23360@b79g2000hse.googlegroups.com> Message-ID: shahargs at gmail.com wrote: > I'm trying to write application which parse one page to sentences and > then, check every group for few things. > > The code: > rawstr = r"""([^.?!]+[.?!])""" > regex=re.compile(rawstr) > matchs=regex.search(document) > document, is the text i parsing. I cheked it in Kodos, and everything > worked well. but, i'm trying to write for loop which check every > group. > > I tried: > for group in matchs.groups(): > but then, it's check only the first group. and i tried: > for group in matchs.group(): > but then it's checking every letter, not every sentence. > > is anyone know how i should write this loop to check every group on > the groups collection that the regular expression return? A group denotes a subexpression of a single match: >>> re.compile("(a+)(b*)").search("xaaabbxbb").groups() ('aaa', 'bb') To get multiple matches use the findall() or finditer() methods, e. g. >>> for match in re.compile("([^.?!]+[.?!])").finditer("Is that what you want? Yes! At least I think so..."): ... match.group() ... 'Is that what you want?' ' Yes!' ' At least I think so.' Peter From ppgoes at gmail.com Mon Aug 6 09:04:51 2007 From: ppgoes at gmail.com (PPGOES) Date: Mon, 6 Aug 2007 06:04:51 -0700 (PDT) Subject: wxpython with python 2.5 In-Reply-To: <4a7f84ac0708020924v73dee05eq76d10507e3c2cad5@mail.gmail.com> References: <4a7f84ac0708020924v73dee05eq76d10507e3c2cad5@mail.gmail.com> Message-ID: <12015880.post@talk.nabble.com> Try with this: import wxversion wxversion.select("2.8") import wx G-18 wrote: > > Hello, > > > I am trying to get wxpython to run with python 2.5 without any > success. > wx works prefectly in python 2.4. below is the error code i get when i try > to run the code. > File "demo.py", line 3, in > import Main > File "/tmp/wxPython/Main.py", line 32, in > import wx # This module uses the new wx namespace > ImportError: No module named wx > > Any help in getting wxpython to run in 2.5 would be greatly appreciated. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- View this message in context: http://www.nabble.com/wxpython-with-python-2.5-tf4207124.html#a12015880 Sent from the Python - python-list mailing list archive at Nabble.com. From __peter__ at web.de Tue Aug 7 07:08:23 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 07 Aug 2007 13:08:23 +0200 Subject: seeking tinter module References: <46b849cf$0$21841$426a74cc@news.free.fr> Message-ID: Jean-Fran?ois Pi?ronne wrote: > I'm looking for a module name tinter (not tkinter...) > > from http://www.vex.net/parnassus/apyllo.py?i=97497223 > status: Dead and Gone > > Google return no location to download it, only a few > articles mentionned it, for example: > http://www.ibm.com/developerworks/linux/library/l-python6.html > > > Does someone has still a copy of this module? http://www.google.com/codesearch?q=lang%3Apython+file%3Atinter.py&hl=de&btnG=Code+suchen gives one hit. Peter From splifingate at gmail.com Mon Aug 20 23:34:36 2007 From: splifingate at gmail.com (ah) Date: Mon, 20 Aug 2007 23:34:36 -0400 Subject: What does this thread have to do with classical music, In-Reply-To: <180820070841431634%erfc@caballista.org> References: <7nnh7350b5h25ghocra72b23mmsnnkj8bh@4ax.com> <469392cd$0$97226$892e7fe2@authen.yellow.readfreenews.net> <469445b3$0$4819$8f2e0ebb@news.shared-secrets.com> <4694e124$0$97214$892e7fe2@authen.yellow.readfreenews.net> <46957ef1$0$10227$8f2e0ebb@news.shared-secrets.com> <46963170$0$97261$892e7fe2@authen.yellow.readfreenews.net> <46981df7$0$12095$8f2e0ebb@news.shared-secrets.com> <46990784$0$97223$892e7fe2@authen.yellow.readfreenews.net> <4699297c$0$4706$4c368faf@roadrunner.com> <140720071431044860%erfc@caballista.org> <46a3a1a7$0$15115$8f2e0ebb@news.shared-secrets.com> <220720072148091069%erfc@caballista.org> <46a5385d$0$4832$8f2e0ebb@news.shared-secrets.com> <250720071834457296%erfc@caballista.org> <46aceaa5$0$13281$8f2e0ebb@news.shared-secrets.com> <290720071853200863%erfc@caballista.org> <46b12539$0$4807$8f2e0ebb@news.shared-secrets.com> <010820072033374341%erfc@caballista.org> <46c63474$0$4844$8f2e0ebb@news.shared-secrets.com> <180820070841431634%erfc@caballista.org> Message-ID: <46c90727$0$14433$8f2e0ebb@news.shared-secrets.com> Art Deco wrote: > ah wrote: >>Art Deco wrote: >>> ah wrote: >>>>Art Deco wrote: >>>>> ah wrote: >>>>>>Art Deco wrote: >>>>>>> ah wrote: >>>>>>>>Art Deco wrote: >>>>>>>>> ah wrote: >>>>>>>>>>Art Deco wrote: >>>>>>>>>>> Who wrote? >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>>>What does that have to do with classical music, snuhwolf? >>>>>>>>>>> >>>>>>>>>>>>What does that have to do with classical music, snuhwolf? >>>>>>>>>>> >>>>>>>>>>> How many more times will you be asking the same tired, lame >>>>>>>>>>> questions, >>>>>>>>>>> Tholen? >>>>>>>>>> >>>>>>>>>>Till 2056? >>>>>>>>> >>>>>>>>> At that point, he will have made the Thirty Years Pset War look like >>>>>>>>> 1967 in the Sinai. >>>>>>>> >>>>>>>>It must have been Hell to keep a garden during those times. >>>>>>>> >>>>>>>>Did they all eat jerky, or what? >>>>>>> >>>>>>> Worse -- worm-laden hardtack. >>>>>> >>>>>>Luxury! >>>>>> >>>>>>Why, I remember when I was a lad . . . we used to watch the local churls >>>>>>across the fences eating that well. >>>>>> >>>>>>We only had millings (and (occasionally) water) on Tuesdays and Fridays. >>>>> >>>>> Grog and hardtack, life is good! >>>> >>>>?Viva la basura! >>> >>> Vivat les ordures! >> >>Vivara los trunctiato! > > das Leben ist gut! de Handel esta disgustipado! From vedrandekovic at v-programs.com Sat Aug 18 09:15:22 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Sat, 18 Aug 2007 06:15:22 -0700 Subject: python video editing libs In-Reply-To: <1187406096.013266.199030@m37g2000prh.googlegroups.com> References: <46c64393$1@news.orcon.net.nz> <1187406096.013266.199030@m37g2000prh.googlegroups.com> Message-ID: <1187442922.452889.53580@k79g2000hse.googlegroups.com> On 18 kol, 05:01, math2life wrote: > On Aug 17, 5:55 pm, DavidM wrote: > > > > > Hi, > > > Does anyone know of any python or python-wrapped libs for video editing? > > > My requirements: > > - open video files in any of the popular containers (avi, mov, ogg, flv > > etc) and all the popular codecs (mpeg3, theora, mpeg2 etc) and audio > > codecs (raw, wav, mp3 etc) > > - get an abstract video clip object on opening such a file > > - query the clip object to determine stuff like length, framerate, size > > etc > > - iterate through all the frames, and get a frame object with each frame > > - with a frame object, be able to access individual pixels, add graphic > > images (eg, via PIL), export frame to graphics file (eg jpeg) > > - with video clip object, be able to change framerate, insert/remove > > frames etc, and render out with desired a-v codecs and container > > - good well-documented API, preferably some usage examples > > > Does anything like this exist? > > > Cheers > > David > > Python OpenCV wrapper will meet most of your need, but I am not > sure , > plz check it out. Hi, I'am not sure, try pymedia Regards, Vedran From __peter__ at web.de Fri Aug 24 03:52:23 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 24 Aug 2007 09:52:23 +0200 Subject: comparing two lists References: Message-ID: Ladislav Andel wrote: > need to be stopped before deleting any instance from items. > So I need to call stopLoop method in the given item in items before it > gets removed. > If there is any addition to items it's quite easy to call > item.startLoop() method. Unless you want to rely on the __del__ method or introduce another complication (weak references) you have to be explicit: # untested # removing items db_items = set(Item(**d) for d in dblist) delenda = items - db_items for item in delenda: item.stopLoop() items.remove(item) > (I use twisted but it should not make any difference): I've not worked with twisted, so I can't confirm that. I can imagine that they provide their own way to spell a finalizer... Peter From exarkun at divmod.com Thu Aug 2 16:03:24 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 2 Aug 2007 16:03:24 -0400 Subject: python 3.0, pywin32 and scipy In-Reply-To: <5heos0F3jael1U1@mid.uni-berlin.de> Message-ID: <20070802200324.4947.837812919.divmod.quotient.17657@ohm> On Thu, 02 Aug 2007 21:16:04 +0200, "Diez B. Roggisch" wrote: >vml schrieb: >> Hello, >> >> >> I am trying to promote python in my job, my collegue only see matlab >> and microsoft scripting language. >> I understood that there willl be no backward compatibility between >> python 2.x and 3.0, does it means that: >> > [snip] > >You mean C#, the language that has seen 3 major revisions in the last 6 >years of existence, with C# 3 being announced already? And the .NET SDK, >that happily strode along with that? Compared to python, that has been >started in 1991 and now approaches it's third incarnation, I'd say >python has a record of steadiness that surpasses that of MS-based tools >by any means. This is not a valid comparison. In fact, C# 3 is completely backwards compatible with C# 2, just as C# 2 was backwards compatible with C# 1. Jean-Paul From bronger at physik.rwth-aachen.de Fri Aug 24 05:11:21 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 24 Aug 2007 11:11:21 +0200 Subject: Co-developers wanted: document markup language References: <87odgyyx9u.fsf@wilson.homeunix.com> Message-ID: <87ir7570w6.fsf@wilson.homeunix.com> Hall?chen! Evan Klitzke writes: > On 8/23/07, Torsten Bronger wrote: > >> Some LaTeX users in Aachen thought about a general-use markup >> language this spring. I wrote some code and a rough project >> description, however, we could need some help. >> >> If you are interested, visit the provisional project page at >> http://latex-bronger.sourceforge.net/gummi/ > > I briefly looked over the specification, and it looks like you're > targeting a LaTeX backend. Are you planning on outputting to LaTeX > and using that to generate e.g. PDF versions of documents, or do > you plan to have a real PDF/Postscript backend? Yes, I plan to use LaTeX as a mere backend slave for getting PDFs. I will *try* to keep the LaTeX readable but mostly for debugging purposes. I don't think that a native PDF backend is helpful on the short run because LaTeX just works well for this (I don't like LaTeX's usability but I do like TeX's typesetting abilities). There is another way to get PDFs which I certainly want to give a try sometime, namely XSL:FO. However, I don't know how feasible direct PDF output is. I'm somewhat scared by line breaking algorithms, hyphenation and all this, though. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From tomtim20 at gmail.com Fri Aug 24 09:54:53 2007 From: tomtim20 at gmail.com (tomtim20 at gmail.com) Date: Fri, 24 Aug 2007 06:54:53 -0700 Subject: Unequal Length Maze In-Reply-To: <5j85h5F3t20idU1@mid.uni-berlin.de> References: <1187941996.333191.323540@z24g2000prh.googlegroups.com> <5j85h5F3t20idU1@mid.uni-berlin.de> Message-ID: <1187963693.724859.116810@m37g2000prh.googlegroups.com> On Aug 24, 4:41 pm, "Diez B. Roggisch" wrote: > tomti... at gmail.com schrieb: > > > Hi All, > > what's the best algorithm to solve such problem ? > >http://www.stetson.edu/~efriedma/unequal/ > > > I will really appreciate some pieces of code (python). > > If you pay me 100$ (really a bargain), you get a solution in python. > > Diez What about Barack Obama Autographed Photo ? From thn at mail.utexas.edu Wed Aug 15 11:04:03 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: Wed, 15 Aug 2007 08:04:03 -0700 Subject: Combinatorial of elements in Python? In-Reply-To: References: <9e2f512b0708142203m782b0e10s817fb4d061ba0e46@mail.gmail.com> <46C2ED11.70904@freakmail.de> Message-ID: <1187190243.875896.103830@i13g2000prf.googlegroups.com> On Aug 15, 8:39 am, "Sebastian Bassi" wrote: > That was easy :) > What about extending it for N elements inside the dictionary? Sounds > like a work for a recursive function. Here's my attempt: [code] def backtrack(groups,position=0, answer=''): if position==len(groups): yield answer else: for e in groups[position]: for x in backtrack(groups,position+1,answer+e): yield x groups = [ ['a','b','c'], ['w','x','y','z'], ['1','2']] for i in backtrack(groups): print i [/code] If you need to put the result into a set, you can. As for the original question "Is there a builtin function for this", what you're asking is essentially the standard recursive backtracking algorithm. In your case, each "layer" in the network is fully connected to the network below it, much the way layers in a neural network are set up. Sadly, there isn't a graph/network algorithm module in the python standard library. There are graph-algorithm type libraries out there I think, but I've never used any of them, so I can't be much help. -Tom From mauriceling at acm.org Sun Aug 12 03:16:22 2007 From: mauriceling at acm.org (Maurice LING) Date: Sun, 12 Aug 2007 07:16:22 GMT Subject: Database intensive application In-Reply-To: <1186895306.237395.189530@z24g2000prh.googlegroups.com> References: <1186895306.237395.189530@z24g2000prh.googlegroups.com> Message-ID: <46beb3c3$1@news.unimelb.edu.au> Rohit wrote: > I am a novice. I want to know whether Python can be used to develop > client/server database and web applications like .NET. Which is the > best book/source to learn Python? > There are database access libraries for almost every RDBMS. Web applications using Django, CherryPy, TurboGears and many other tools Best book(s): Dive into Python, Learning Python maurice From torriem at chem.byu.edu Fri Aug 17 15:25:18 2007 From: torriem at chem.byu.edu (Michael L Torrie) Date: Fri, 17 Aug 2007 13:25:18 -0600 Subject: why psyco using more memery in liunx? In-Reply-To: <005d01c7e078$c13d0ed0$811ba8c0@kyom> References: <005d01c7e078$c13d0ed0$811ba8c0@kyom> Message-ID: <46C5F61E.2080102@chem.byu.edu> kyo guan wrote: > Hi all: > > When you import psyco in python2.5, you can see the memery grow up near 40MB in linux. but the same version python and > psyco, is only grow up 1MB under windows. I have a hunch it's because of how the OS's are reporting shared memory usage. IE, the 1 MB increase under windows may not be altogether truthful, and neither is the reported 40 MB on linux. Memory usage is tricky to judge on any modern OS, as shared libraries do increase the apparent memory use by an application, but the libraries are shared with other applications and OS components. > > kyo > From carsten at uniqsys.com Fri Aug 17 00:19:13 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 17 Aug 2007 00:19:13 -0400 Subject: defaultdict of arbitrary depth In-Reply-To: <1187321113.841198.195100@22g2000hsm.googlegroups.com> References: <1187321113.841198.195100@22g2000hsm.googlegroups.com> Message-ID: <1187324353.3231.6.camel@localhost.localdomain> On Thu, 2007-08-16 at 20:25 -0700, Paul McGuire wrote: > [...] > I've hacked out this recursivedefaultdict which is a > defaultdict(defaultdict(defaultdict(...))), arbitrarily deep depending > on the keys provided in the reference. > > Please comment. > [...] > > class recursivedefaultdict(object): > def __init__(self): > self.__dd = defaultdict(recursivedefaultdict) > def __getattr__(self,attr): > return self.__dd.__getattribute__(attr) > def __getitem__(self,*args): > return self.__dd.__getitem__(*args) > def __setitem__(self,*args): > return self.__dd.__setitem__(*args) This is shorter: from collections import defaultdict class recursivedefaultdict(defaultdict): def __init__(self): self.default_factory = type(self) -- Carsten Haese http://informixdb.sourceforge.net From bbxx789_05ss at yahoo.com Sat Aug 4 01:36:52 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 03 Aug 2007 22:36:52 -0700 Subject: Script that Navigates Page needs Javascript Functionality In-Reply-To: <1186192690.100410.260840@g12g2000prg.googlegroups.com> References: <1186192690.100410.260840@g12g2000prg.googlegroups.com> Message-ID: <1186205812.203227.299730@57g2000hsv.googlegroups.com> On Aug 3, 7:58 pm, SMERSH009 wrote: > I have a script that navigates pages and scrapes the HTML source of > the page. > in order to view the results I need I need python to "navigate to" > this Javascript link: > javascript:__doPostBack('ctl00$cpMain$pagerTop','4') This basically > translates into "go to page 4." > I read the posts on this group, and from what I understand, the > functionality I need is with simplejson? If so, what is the syntax i > would use to execute that Javascript? > Or am I completely off base with using simplejson altogether? > > Thanks for the help > -Sam json is a specific way of formatting strings. If an application expects to receive a string as input and the string is supposed be formatted according to json, then you need to send the app a json formatted string. >From the brief description I just read of simplejson, it allows you to convert python objects to a string. What makes you think that simplejson has anything to do with executing javascript code? When html pages are sent to a browser, there is software in the browser that executes any javascript on the page. If you use python to download source code from a server, you are not loading anything in a browser, so no javascript executes. From steve at holdenweb.com Thu Aug 2 12:36:18 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 02 Aug 2007 12:36:18 -0400 Subject: wxpython with python 2.5 In-Reply-To: <4a7f84ac0708020924v73dee05eq76d10507e3c2cad5@mail.gmail.com> References: <4a7f84ac0708020924v73dee05eq76d10507e3c2cad5@mail.gmail.com> Message-ID: G wrote: > Hello, > > > I am trying to get wxpython to run with python 2.5 without any > success. wx works prefectly in python 2.4. below is the error code i get > when i try to run the code. > File "demo.py", line 3, in > import Main > File "/tmp/wxPython/Main.py", line 32, in > import wx # This module uses the new wx namespace > ImportError: No module named wx > > Any help in getting wxpython to run in 2.5 would be greatly appreciated. > How did you install it, and was it a version specifically made to run with Python 2.5? You can't just install 2.5 and have it pick up all the libraries you installed for 2.4, you have to download and install updated versions. At the moment it doesn't look as though 2.5 is seeing wxPython at all. Sorry if this isn't the problem. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From sbassi at clubdelarazon.org Wed Aug 15 01:03:41 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Wed, 15 Aug 2007 02:03:41 -0300 Subject: Combinatorial of elements in Python? Message-ID: <9e2f512b0708142203m782b0e10s817fb4d061ba0e46@mail.gmail.com> I have 2 (or more) groups of elements, and I want to get all possible unique combinations from all of them. Is there a build-in method to do it? ADictionary={"one":["A","B","C","D"],"two":["H","I"]} I want to have all possible combinations from "one" and "two", that is: AH BI CH DI AI BH CI DH Sounds easy, but is not :) -- Sebasti?n Bassi (???????) Diplomado en Ciencia y Tecnolog?a. GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D From Michael.J.Fromberger at Clothing.Dartmouth.EDU Tue Aug 28 15:54:26 2007 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Tue, 28 Aug 2007 15:54:26 -0400 Subject: Image manipulation References: <1188328362.992426.275780@19g2000hsx.googlegroups.com> Message-ID: In article <1188328362.992426.275780 at 19g2000hsx.googlegroups.com>, Slava wrote: > I need to add dynamic text to animated GIF images. > What is a best way to do it? > > Thanks. One possibility is the GD library, which supports animated GIF. There is a Python binding: I do not know, however, whether or not the Python wrapper supports the animated GIF portions of the library. You'll probably have to do some digging. Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From bj_666 at gmx.net Sat Aug 25 06:21:20 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Aug 2007 10:21:20 GMT Subject: Joining Big Files References: <1188035844.616831.205350@i38g2000prf.googlegroups.com> Message-ID: <5jae50F3rgskgU1@mid.uni-berlin.de> On Sat, 25 Aug 2007 02:57:24 -0700, mosscliffe wrote: > I have 4 text files each approx 50mb. > > I need to join these into one large text file. > > I only need to do this very occasionally, as the problem has occurred > because of upload limitations. > > Bearing in mind filesize and memory useage, would I be better reading > every line in every file and writing each line to the output file or > is there someway I could execute some shell command. There are some copy functions that work with file like objects in the `shutil` module. Ciao, Marc 'BlackJack' Rintsch From kaldrenon at gmail.com Tue Aug 21 17:30:29 2007 From: kaldrenon at gmail.com (kaldrenon) Date: Tue, 21 Aug 2007 21:30:29 -0000 Subject: Latest models of Gibson guitars In-Reply-To: <%xIyi.22058$aa7.17937@bignews3.bellsouth.net> References: <1187544898.289948.322160@22g2000hsm.googlegroups.com> <%xIyi.22058$aa7.17937@bignews3.bellsouth.net> Message-ID: <1187731829.843146.36220@r34g2000hsd.googlegroups.com> On Aug 21, 5:11 pm, John McGaw wrote: > mobile... at gmail.com wrote: > > Reviews of latest models of best guitars, fender, gibson, yamaha, and > > many more, with pictures and prices. > > Are these new guitars made of SPAM like your message and your "blog"? That'd be bloody terrible to play, and sound awful. Gimme a 100% Angus 12-string, or give me nothing, I say. From f.guerrieri at gmail.com Wed Aug 15 16:54:39 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Wed, 15 Aug 2007 22:54:39 +0200 Subject: "Variable variable name" or "variable lvalue" In-Reply-To: <1187199722.618893.281170@r29g2000hsg.googlegroups.com> References: <1187199722.618893.281170@r29g2000hsg.googlegroups.com> Message-ID: <79b79e730708151354q46a35999n34a42aaf1bb9312d@mail.gmail.com> On 8/15/07, mfglinux wrote: > > > #Let's say x=3, then Period definition is > Period=Slab(Material1(12.5)+Material2(25)+Material3(12.5)) #Slab is a > python class > > I dont know how to automatize last piece of code for any x > Hello, you could use exec to create on the fly the variables as you need them (but be aware that the use of exec can be dangerous and is probably not needed), or you could add the proper name to a relevant dictionary (for example, locals() ). Something like for counter in xrange(3): locals()["Material" + str(counter)] = Material(12.5) But if you need the variables only for calling Slab, you could write something like: material_number = 3 material_list = [Material(12.5) for x in xrange(0, counter)] Period = Slab(sum(material_list)) bye, francesco -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Aug 3 22:27:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 03 Aug 2007 22:27:05 -0400 Subject: downloading files In-Reply-To: <1186176739.765447.262720@w3g2000hsg.googlegroups.com> References: <1186166920.757662.269340@o61g2000hsh.googlegroups.com> <1186176739.765447.262720@w3g2000hsg.googlegroups.com> Message-ID: <46B3E3F9.6060202@holdenweb.com> Ehsan wrote: > On Aug 3, 10:10 pm, Steve Holden wrote: [...] >> I'm guessing there are binary files and you are running on Windows, >> which is inserting a carriage return before ebery newline. Try >> >> localFile = open(fileName, 'wb') >> >> to avoid thus behavior. [...] > thanx Steve > It works but could you explain more what's wrong with just 'w'? > Hmm, I thought I had. 'b' stand for 'binary', and the system sends out exactly the bytes you right. Without the 'b' it assumes you are handling text, so Windows "CR/LF" line endings are converted to "LF" or reading, and "LF" is converted to "CR/LF" on writing. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From cjusto at neopolitan.com Fri Aug 10 17:58:06 2007 From: cjusto at neopolitan.com (Christian Justo) Date: Fri, 10 Aug 2007 14:58:06 -0700 Subject: No subject Message-ID: Hi, I'm simply trying to get mod_python working on my apache server but when I create a .py file the output returned from the browser is the code in the file and not just the output from the script. I have read the manual and tried mptest.py with an .htaccess file both in /var/www/html/ and still no luck. When I browse to mptest.py with Firefox I get the mptest.py code: from mod_python import apache def handler(req): req.content_type = 'text/plain' req.write("Hello World!") return apache.OK This is the .htaccess file: AddHandler mod_python .py PythonHandler mptest PythonDebug On This is part of httpd.conf: LoadModule python_module modules/mod_python.so mod_python version:3.3.1-3 OS:Linux Fedora 7 Python version:2.5 (r25:51908, Apr 10 2007, 10:29:13)[GCC 4.1.2 20070403 (Red Hat 4.1.2-8)] Apache version:Apache/2.2.4 (Fedora) I have a copy of my mod_python test page with more information if it's needed. Any help would be greatly appreciated, thank you much for your time. From malaclypse2 at gmail.com Fri Aug 3 16:05:10 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 3 Aug 2007 16:05:10 -0400 Subject: os.listdir path error In-Reply-To: <1186170609.001778.15230@l70g2000hse.googlegroups.com> References: <1186170609.001778.15230@l70g2000hse.googlegroups.com> Message-ID: <16651e80708031305q6b0fa7cak13a194d80aa4b546@mail.gmail.com> On 8/3/07, vedrandekovic at v-programs.com wrote: > Hello > > Here is my simple listdir example: > > >>> import os > >>> os.listdir("C:\Python24\") # This directory relly exists > > Here is my error: > > WindowsError: [Errno 3] The system cannot find the path specified: 'l/ > *.*' That's a somewhat surprising error. Under 2.5, I get a more helpful error message: >>> import os >>> os.listdir("C:\Python25\") SyntaxError: EOL while scanning single-quoted string That's because I've escaped the closing quote of the string with \". Use this instead: >>> os.listdir("C:\\Python25\\") or >>> os.listdir("C:/Python25/") since windows is usually happy to use forward slashes instead of backslashes in directory names. -- Jerry From zyzhu2000 at gmail.com Thu Aug 2 08:50:16 2007 From: zyzhu2000 at gmail.com (beginner) Date: Thu, 02 Aug 2007 05:50:16 -0700 Subject: standalone process to interact with the web In-Reply-To: <46b05aac$0$31743$426a74cc@news.free.fr> References: <1185899130.331170.151980@e16g2000pri.googlegroups.com> <1185904623.754078.198910@e9g2000prf.googlegroups.com> <1185909098.952860.217190@j4g2000prf.googlegroups.com> <46b05aac$0$31743$426a74cc@news.free.fr> Message-ID: <1186059016.461925.295520@e16g2000pri.googlegroups.com> On Aug 1, 5:04 am, Bruno Desthuilliers wrote: > beginner a ?crit : > (snip) > > > Yes exactly. I just don't want to reinvent the wheel as I imagine > > there are already tons of libraries and frameworks that support RPC or > > the like functions. > > Why go thru the pain of RPC, SOAP or such bloated horrors ? Why not just > use plain old HTTP with a RESTful API ? Then you just need to make your > app wsgi compliant. I am not familiar with RESTful API. I will look into it. From python at jayloden.com Mon Aug 20 15:36:56 2007 From: python at jayloden.com (Jay Loden) Date: Mon, 20 Aug 2007 15:36:56 -0400 Subject: reading a line in file In-Reply-To: <2dc0c81b0708201207p7f83f2e0l6de15fd70be252a5@mail.gmail.com> References: <93066C069973ED448DC2BCEA9C44A7383BE2B2@efmailx> <2dc0c81b0708201029k5909d919vcf0deebae74a79c7@mail.gmail.com> <93066C069973ED448DC2BCEA9C44A7383BE2B4@efmailx> <2dc0c81b0708201207p7f83f2e0l6de15fd70be252a5@mail.gmail.com> Message-ID: <46C9ED58.5080403@jayloden.com> Shawn Milochik wrote: > Hopefully this will help (using your input file) > > #!/usr/bin/env python > import re > buildinfo = "input.txt" > input = open(buildinfo, 'r') > > regex = re.compile(r"^\s*build.number=(\d+)\s*$") > > for line in input: > if re.search(regex, line): > print line > buildNum = re.sub(r"^\s*build.number=(\d+)\s*$", "\\1", line) > print line > print buildNum If the only thing needed is this specific match text, this should be more efficient (re module and regular expressions have a lot of overhead): #!/usr/bin/env python buildinfo = "input.txt" input = open(buildinfo, 'r') token = "build.number=" BUILDNUM = "" for line in input: if line.startswith(token): BUILDNUM = line[len(token):-1] print "Build number: %s" % BUILDNUM From sbellon at sbellon.de Sat Aug 11 08:00:17 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Sat, 11 Aug 2007 14:00:17 +0200 Subject: Destruction of generator objects References: <20070808002852.6228ae91@cube.tz.axivion.com> <1186613044.494852.306970@q75g2000hsh.googlegroups.com> <20070809011441.05d7dfb6@cube.tz.axivion.com> <1186819365.988117.232230@g4g2000hsf.googlegroups.com> <20070811121630.1b010eab@cube.tz.axivion.com> <1186831173.814193.235420@o61g2000hsh.googlegroups.com> Message-ID: <20070811140017.22a11f82@cube.tz.axivion.com> On Sat, 11 Aug, Kay Schluehr wrote: > Honestly, I'd recommend wrapping the generator into a function object, > create the resource on construction ( or pass it ) and destroy it > implementing __del__. > > def gen_value(self): > while True: > yield self.iter.next() > > class GeneratorObj(object): > def __init__(self, obj, gen): > self.iter = make_iter(obj) > self.gen = gen(self) > > def __del__(self): > destroy(self.iter) > > def next(self): > return self.gen.next() Ok, I think there is an __iter__ missing in order to implement the iterator protocol, and I don't see why the generator cannot be inside the class itself. Anyway, I came up with this code now: class ListGenerator(object): def __init__(self, iter): print "gen init" self.iter = iter self.gen = self._value() def __del__(self): print "gen del" destroy(self.iter) def _value(self): print "gen value" while more(self.iter): yield next(self.iter) def __iter__(self): print "gen iter" return self def next(self): print "gen next" return self.gen.next() When iterating over such a generator, I see the following output: >>> list(obj) gen init gen iter gen next gen value gen next gen next gen next gen next ['Item1', 'Item2', 'Item3', 'Item4'] But I do not see an output of "gen del" which makes me think that the destructor is not called, thus not releasing the resource. It seems I have not completely understood how generators work ... -- Stefan Bellon From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Aug 13 09:46:18 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 13 Aug 2007 15:46:18 +0200 Subject: check if var is dict In-Reply-To: References: <46C02BFA.10703@al.com.au> Message-ID: <46c0608a$0$427$426a34cc@news.free.fr> Jeff McNeil a ?crit : (top-post corrected) > On 8/13/07, Astan Chee wrote: >> Hi, >> I have a variable, I want to check if it is a dictionary or a string. >> Is there any better way to do this than I've done. How I did it is by >> doing a .items() and catching a AttributeError that it raises if its not >> a dictionary. >> How do i properly do it? >> Thanks > You could use 'isinstance' to determine whether or not your object is > an instance of a particular class. > >>>> isinstance({}, dict) > True >>>> isinstance("", basestring) > True > > Note the use of 'basestring', which will catch unicode as well. > The problem is that it will prevent passing some perfectly valid objects (in this case, mostly dict-like objects, and there are quite a lot of dict-like objects in existing Python code). From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Aug 27 08:02:24 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 27 Aug 2007 14:02:24 +0200 Subject: beginner, idiomatic python In-Reply-To: <13d4gjm3qq0lt7c@corp.supernews.com> References: <13cqlqbbpn0dmea@corp.supernews.com><1187898049.734696.9500@l22g2000prc.googlegroups.com><13csoronscqp7d2@corp.supernews.com><1188090322.663217.102750@22g2000hsm.googlegroups.com><13d4bucfm4m1lc4@corp.supernews.com> <13d4gjm3qq0lt7c@corp.supernews.com> Message-ID: <46d2bd01$0$427$426a74cc@news.free.fr> bambam a ?crit : > Thank you, I have been through the tutorial several times, I guess > I'm just not smart enough. Perhaps I have been led astray by what > I read here? > > My code started like this: > > for i in range(self.parent.GetPageCount()): > > I was asked: > >> Does page count change? i.e. is it necessary to retrieve it in every loop > > > Is self.parent.GetPageCount() 'retrieved every loop'? If your question is 'is self.parent.GetPageCount()' called for each iteration of this loop, then the answer is obviously 'no', and it's quite easy to check it out: Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def test(): ... print "test called" ... return range(5) ... >>> for x in test(): print x ... test called 0 1 2 3 4 >>> Now if you need to use the result of self.parent.GetPageCount() more than once in the same function and this result is not likely to change during the function's execution, you're certainly better storing it in a local variable - but now that's such a CS101 thing that it's probably not even worth mentionning. IOW, Zentrader's remark was at best misleading, at worst plain wrong... From paul.heslop at blueyonder.co.uk Wed Aug 22 07:31:39 2007 From: paul.heslop at blueyonder.co.uk (Paul Heslop) Date: Wed, 22 Aug 2007 11:31:39 GMT Subject: Free Air Conditioners!!!!!! References: <1187738115.972271.94080@r23g2000prd.googlegroups.com> Message-ID: <46CC1E9B.778915A6@blueyonder.co.uk> "Scott M." wrote: > > Oh my God! How did you know?!! You were so smart to post that here! > about a hundred times at least by now :O( -- Paul (We won't die of devotion) ------------------------------------------------------- Stop and Look http://www.geocities.com/dreamst8me/ From stargaming at gmail.com Mon Aug 6 08:00:25 2007 From: stargaming at gmail.com (Stargaming) Date: 06 Aug 2007 12:00:25 GMT Subject: Something in the function tutorial confused me. References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <46b6df49$0$26165$9b622d9e@news.freenet.de> Message-ID: <46b70d58$0$18070$9b622d9e@news.freenet.de> On Mon, 06 Aug 2007 11:13:45 +0000, Alex Popescu wrote: > Stargaming wrote in news:46b6df49$0$26165 > $9b622d9e at news.freenet.de: > [snip] >> >> You're just unluckily shadowing the name `y` in the local scope of > your >> function. Your code snippet could be rewritten as:: >> >> def f(x, y=None): >> if y is None: my_y = [] >> else: my_y = y >> my_y.append(x) >> return my_y >> >> HTH, >> Stargaming > > For the given example this will continue to print: > >> print f(23) # prints [23] >> print f(42) # prints [42] > > so this doesn't solve/explain OP's initial question. A previous post has > already clarified the reasons for seeing this normal behavior. > > bests, > ./alex If it keeps normal behaviour, that's exactly what it ought to explain. In his local scope, there is an `y`, having the value of f.func_defaults. Because it's harder to see "hey, in some cases, y vanishes, in some it survives", I invented the new local reference `my_y` -- which should be clear to go away after completion of the function body. Regards, Stargaming From rainwatching at gmail.com Sat Aug 4 13:51:36 2007 From: rainwatching at gmail.com (=?iso-8859-1?q?S=F6nmez_Kartal?=) Date: Sat, 04 Aug 2007 17:51:36 -0000 Subject: regexp problem in Python In-Reply-To: <1186236610.438810.230580@22g2000hsm.googlegroups.com> References: <1186177312.117581.129910@d55g2000hsg.googlegroups.com> <1186222973.073756.300890@r34g2000hsd.googlegroups.com> <1186236610.438810.230580@22g2000hsm.googlegroups.com> Message-ID: <1186249896.086430.47790@q75g2000hsh.googlegroups.com> On 4 A ustos, 17:10, Ehsan wrote: > On Aug 4, 1:22 pm, S?nmez Kartal wrote: > > > > > > > > > On 4 A ustos, 00:41, Ehsan wrote: > > > > I want to find "http://www.2shared.com/download/1716611/e2000f22/ > > > Jadeed_Mlak14.wmv?tsid=20070803-164051-9d637d11" or 3gp instead of > > > wmv in the text file like this : > > > > > > ""some code"" > > > function reportAbuse() { > > > var windowname="abuse"; > > > var url="/abuse.jsp?link=" + "http://www.2shared.com/file/1716611/ > > > e2000f22/Jadeed_Mlak14.html"; > > > OpenWindow = > > > window.open(url,windowname,'toolbar=no,scrollbars=no,resizable=no,width=500?,height=500,left=50,top=50'); > > > OpenWindow.focus(); > > > } > > > function startDownload(){ > > > window.location = "http://www.2shared.com/download/1716611/ > > > e2000f22/Jadeed_Mlak14.wmv?tsid=20070803-164051-9d637d11"; > > > //document.downloadForm.submit(); > > > } > > > > > > > > > http://www.2shared.com/download/1716611/e2000f22/ > > > Jadeed_Mlak14.3gp?tsid=20070803-164051-9d637d11"sfgsfgsfgv > > > > I use this pattern : > > > "http.*?\.(wmv|3gp).*"" > > > > but it returns only 'wmv' and '3gp' instead of "http://www.2shared.com/ > > > download/1716611/e2000f22/Jadeed_Mlak14.wmv? > > > tsid=20070803-164051-9d637d11" > > > > what can I do? what's wrong whit this pattern? thanx for your comments > > > You could use r'window.location = "(.*?\.(wmv|3gp)";' as your regex > > string, I guess..- Hide quoted text - > > > - Show quoted text - > > I didn't get what do you mean? i think i must just change the pattern > but I don't know how to find bestfit pattern If you append "window.location = " and ';' to your pattern, it would be more clear to detect it. r'window.location = "(.*?)";' ... I have used this and it gave me ... >>> data = """ ... ""some code"" ... function reportAbuse() { ... var windowname="abuse"; ... var url="/abuse.jsp?link=" + "http://www.2shared.com/file/ 1716611/e2000f22/Jadeed_Mlak14.html"; ... OpenWindow = ... window.open(url,windowname,'toolbar=no,scrollbars=no,resizable=no,width=500,height=500,left=50,top=50'); ... OpenWindow.focus(); ... } ... function startDownload(){ ... window.location = "http://www.2shared.com/download/1716611/ e2000f22/Jadeed_Mlak14.wmv?tsid=20070803-164051-9d637d11"; ... //document.downloadForm.submit(); ... } ... ... ... """ >>> re.findall(r'window.location = "(.*?)";', data) ['http://www.2shared.com/download/1716611/e2000f22/Jadeed_Mlak14.wmv? tsid=20070803-164051-9d637d11'] >>> print 'It works! :-)' It works! :-) >>> Happy coding From JYOUNG79 at kc.rr.com Mon Aug 6 08:36:25 2007 From: JYOUNG79 at kc.rr.com (JYOUNG79 at kc.rr.com) Date: Mon, 06 Aug 2007 07:36:25 -0500 Subject: xlrd question Message-ID: Hi Has, >> (as well as >> an alias to it from '/System/Library/Frameworks/Python.framework/ >> Versions/2.3/lib/python2.3/site-packages') >No, /System.../python2.3/site-packages is a symlink to /Library/Python/ >2.3/site-packages set up by Apple. DistUtils makes no modification to >anything under /System. Thanks very much for this clarification (I apologize for not paying closer attention to your previous post). Again, thanks so much for taking the time to help me understand this. I really appreciate it! :-) Jay From jeremy at omba.demon.co.uk Wed Aug 15 07:34:27 2007 From: jeremy at omba.demon.co.uk (Jeremy C B Nicoll) Date: Wed, 15 Aug 2007 12:34:27 +0100 Subject: What order does info get returned in by os.listdir() References: Message-ID: Jeremy C B Nicoll wrote: > When I use os.listdir() to return that list of leaf values, I do seem to > get them in alphabetical order, A before B before C etc, but the > ~-prefixed ones are returned after the Z-prefixed files rather than before > the A-ones. Thanks to people who replied here, and by email. I've some supplementary questions... my original code was looking at each leafname in turn via for leaf in os.listdir(path): wholefile = os.path.join(path,leaf) if os.path.isfile(wholefile): if leaf.startswith("~"): etc. But I now realise I might alternatively do something like: leaflist = os.listdir(path) for leaf in leaflist: How would I sort leaflist in a way that mimics the sort order that XP shows me things under? Secondly, my code is wasting time looking at subdirectories/files which I already know I'm not interested in. Is there a way to restrict listdir to, say, only return info about subdirectories, or only about dirs/files whose names match a pattern? Thirdly, once I've go a list of leafnames, somehow, is there a way to ask Python if a specific leaf-value is in that list, without explicitly looping through the items in the list? -- Jeremy C B Nicoll - my opinions are my own. From dorjetarap at googlemail.com Sat Aug 18 14:40:49 2007 From: dorjetarap at googlemail.com (dorje tarap) Date: Sat, 18 Aug 2007 19:40:49 +0100 Subject: sort dictionary by specific values Message-ID: Hi, I need to perform some horrible functions in python I need to do, using sort in a similar way that Excel can. With a dictionary like: Code: ( text ) 1. >>> d 2. {8: (99, 99), 9: [(55, 67), (77, 66), (67, 88)], 4: [(45, 78), (56, 78), (99, 78)], 5: (67, 77)} I want to sort the entire dictionary based on the last values in each line. First for [-1][0] and then[-1][0]. So sorted descending I would like the output to look like: Code: ( text ) 1. >>> d 2. {8: (99, 99), 4: [(45, 78), (56, 78), (99, 78)], 9: [(55, 67), (77, 66), (67, 88)], 5: (67, 77)} Many thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at liquidtrust.org Wed Aug 22 16:50:21 2007 From: lists at liquidtrust.org (Charlie) Date: Wed, 22 Aug 2007 14:50:21 -0600 Subject: MsiLib Message-ID: <20070822145021.rk1vj9u0ow80o4g0@74.220.202.27> This doesn't seem to be my day for this. When I add view.Execute() to the script, it gives me an error of Execute() takes exactly 1 argument (0 given). I can't seem to find anything on the Microsoft page that concerns the execute function that states what exactly needs to be included as an argument, especially for a select statement. Thanks for the help. Charlie From cdleary at gmail.com Thu Aug 2 09:49:42 2007 From: cdleary at gmail.com (cdleary at gmail.com) Date: Thu, 02 Aug 2007 06:49:42 -0700 Subject: Case study: library class inheritance with property declarations Message-ID: <1186062582.975223.230270@g12g2000prg.googlegroups.com> Hi all, It's possible that I'm missing the obvious -- I've been up for over 24 hours and I'm most likely dehydrated from mass coffee intake, but I figure many people in similar circumstances will be searching comp.lang.python one day, so here goes! class LibraryClass(object): """ A class whose implementation is out of my hands. """ def __init__(self): """ Follows good dynamic-language form and binds all instance variables at initialization time. """ # Omitted: complex initialization functionality. self.useful_attr = None class MyInheritedClass(LibraryClass): """ My refinement of the functionality offered by the LibraryClass. I now want the instance to initialize with a reference to an external object, and the useful_attr defined in the superclass will now reference an attribute of that external object via fget. Changing the attribute of the external object has undefined behavior, so I want to omit an fset in the property declaration; however, I have to provide some way for the superclass to initialize useful_attr -- I can't change the superclass' code, as it resides in a library that is out of my hands. """ def __init__(self, external_obj): LibraryClass.__init__(self) self._external_obj = external_obj def get_useful_attr(self): return self._external_obj.proxy_useful_attr useful_attr = property(fget=get_useful_attr) def test(): class _Fake(object): pass external_obj = _Fake() external_obj.proxy_useful_attr = 12 spam = MyInheritedClass(external_obj) if __name__ == '__main__': test() EOF If you're one of those people who doesn't like laboriously reading contrived examples (elitists ;) I'll boil it down for you: Library class initializes some attribute, but derived class wants to eliminate fsets for said attribute. As a result, our ideal solution Of course, this means that the derived class will raise an error in some circumstances where the base class wouldn't (when you're setting that attribute), but one can assume that the inheritance is worthwhile. How do I come up with silly solutions to circumvent this? Let me count the ways... 1. So-and-so: make an fset that does nothing. This ignores (what should be) errors in code that uses MyInheritedClass in an attempt to accommodate a useless statement in the base class -- surely non-ideal. 2. The ugly one: since you can probably view the library, copy and paste the complex initialization functionality in the above, but leave out the bad statement. This not only forfeits the ideals of inheritance, but makes you totally incompatible with future library changes. 3. Cheerleader: Pure evil. On top of the ugliness of 2, you assume that across library revisions the indenting won't change and that the troublesome statement will remain on the same line, and pull off one of these babies: def super_evil_test(): from inspect import getsourcelines exec(''.join([line[4:] for line in getsourcelines(LibraryClass.__init__)[0][:-1]])) LibraryClass.__init__ = __init__ test() # Passes, but several angels no longer get their wings Totally kidding, everybody! I hope Guido doesn't read this thread... And this concludes the sleep deprived rambling that follows the somewhat interesting case in point. Thoughts? From luismgz at gmail.com Sun Aug 26 20:23:27 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 27 Aug 2007 00:23:27 -0000 Subject: ActiveRecord for Python/MySQL In-Reply-To: <1188118323.164567.6290@e9g2000prf.googlegroups.com> References: <1188103880.146814.110780@q4g2000prc.googlegroups.com> <1188118323.164567.6290@e9g2000prf.googlegroups.com> Message-ID: <1188174207.530036.117400@r34g2000hsd.googlegroups.com> On Aug 26, 5:52 am, Devraj wrote: > Thanks > > On Aug 26, 5:26 pm, EuGeNe Van den Bulke > > wrote: > > Devraj wrote: > > > My application uses MySQL as a backend and am using the MySQL/Python > > > bindings. Are there any libraries that provide a database abstraction > > > layer like Activerecords for Python?' > > > SQLObject > > SQLAclhemy > > DejaVu > > Storm > > > Google for Python ORM you may find more! > > > EuGeNe --http://www.3kwa.com If you want an ActiveRecord -like experience with SQLAlchemy, you can use the extension Elixir on top of it. From mike.klaas at gmail.com Fri Aug 31 14:19:46 2007 From: mike.klaas at gmail.com (Klaas) Date: Fri, 31 Aug 2007 18:19:46 -0000 Subject: platform system may be Windows or Microsoft since Vista In-Reply-To: <1188578878.264671.296440@k79g2000hse.googlegroups.com> References: <1188578878.264671.296440@k79g2000hse.googlegroups.com> Message-ID: <1188584386.174981.168040@z24g2000prh.googlegroups.com> On Aug 31, 9:47 am, p.lava... at ieee.org wrote: > Let's suppose you get Python for Vista Windows today fromhttp://www.python.org/download/. > > Should you then conclude that the tests: > > if platform.system() in ('Windows', 'Microsoft'): > if not (platform.system() in ('Windows', 'Microsoft')): Good analysis. Log a bug @ bugs.python.org -Mike From cai.haibin at gmail.com Wed Aug 1 05:06:42 2007 From: cai.haibin at gmail.com (james_027) Date: Wed, 01 Aug 2007 09:06:42 -0000 Subject: access the name of my method inside it Message-ID: <1185959202.302467.276080@x35g2000prf.googlegroups.com> Hi, for example I have this method def my_method(): # do something # how do I get the name of this method which is my_method here? Thanks, james From greg.kujawa at gmail.com Thu Aug 2 19:45:30 2007 From: greg.kujawa at gmail.com (gregarican) Date: Thu, 02 Aug 2007 23:45:30 -0000 Subject: i am new to python-Please somebody help In-Reply-To: <46b249a4$0$31219$426a74cc@news.free.fr> References: <1186047103.673871.150460@z24g2000prh.googlegroups.com> <1186063842.827016.95030@q3g2000prf.googlegroups.com> <46b249a4$0$31219$426a74cc@news.free.fr> Message-ID: <1186098330.831148.46010@j4g2000prf.googlegroups.com> On Aug 2, 11:03 am, Bruno Desthuilliers wrote: > gregarican a ?crit : > (snip) > > > This link answers my question -->http://www.google.com/search?hl=en&q=Python+list+rudeness. > > I seriously don't think that this newsgroup can be qualified as "rude" > (and I'm possibly one of the "rudest" persons here). Compared to most > comp.* newsgroup, Python is certainly one of the most tolerant and > newbie-friendly around - and quite a lot of newcomers say so. FWIW, even > FAQs, RTFMs or STFWs are usually expressed in a mostly polite way, and > almost always with links and pointers (and FWIW, it's the case here). > > > Honestly, I have developed in both Ruby and Python for years now and > > have consistently found that the Ruby community if more newbie- > > friendly than Python's. > > I spent sometimes lurking on c.l.ruby and didn't find it *that* > friendly. Not more than c.l.py at least, and certainly less respectful > of peoples coming from other languages... > > Now if you want some examples of definitively "rude" newsgroups, I > suggest you take your chance on other newsgroups in the comp.* > hierarchy... Good points. I guess I read a little too much into things. Apology extended. I do recall when I was learning Python most of my questions weren't crushed or anything. And I hear you about some of the other comp.* lists. Browsing them awhile back I was left with my jaw open thinking, "Oh no he diiiiiii....nt." From software at ginstrom.com Sun Aug 26 21:05:50 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Mon, 27 Aug 2007 10:05:50 +0900 Subject: Parser Generator? In-Reply-To: <1188159150.755231.239390@o80g2000hse.googlegroups.com> References: <1187834836.115735.111160@e9g2000prf.googlegroups.com> <1188159150.755231.239390@o80g2000hse.googlegroups.com> Message-ID: <008201c7e846$691fb970$020ba8c0@MOUSE> > On Behalf Of Jason Evans > Parsers typically deal with tokens rather than individual > characters, so the scanner that creates the tokens is the > main thing that Unicode matters to. I have written > Unicode-aware scanners for use with Parsing-based parsers, > with no problems. This is pretty easy to do, since Python > has built-in support for Unicode strings. The only caveat being that since Chinese and Japanese scripts don't typically delimit "words" with spaces, I think you'd have to pass the text through a tokenizer (like ChaSen for Japanese) before using PyParsing. Regards, Ryan Ginstrom From nitro at dr-code.org Mon Aug 6 09:06:58 2007 From: nitro at dr-code.org (Nitro) Date: Mon, 06 Aug 2007 15:06:58 +0200 Subject: Scope question Message-ID: Hello, today I wrote this piece of code and I am wondering why it does not work the way I expect it to work. Here's the code: y = 0 def func(): y += 3 func() This gives an UnboundLocalError: local variable 'y' referenced before assignment If I change the function like this: y = 0 def func(): print y func() then no error is thrown and python apparently knows about 'y'. I don't understand why the error is thrown in the first place. Can somebody explain the rule which is causing the error to me? -Matthias From duncan.booth at invalid.invalid Mon Aug 13 07:47:28 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Aug 2007 11:47:28 GMT Subject: decorators - more than just syntactic sugar References: <46be005e$0$13866$ba620e4c@news.skynet.be> <5i6f25F3ml00gU5@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Sat, 11 Aug 2007 20:30:54 +0200, Helmut Jarausch wrote: > >> are decorators more than just syntactic sugar in python 2.x and what >> about python 3k ? > > They are just syntactic sugar. > > @spam > def ham(): > pass > > is the same as > > def ham(): > pass > > ham = spam(ham) Decorators are almost just syntactic sugar, but in fact there is a subtle difference between the two bits of code you gave: in the second one you assign the function to the name ham and then replace it with the result of calling spam. With the decorator syntax you only have one assignment to ham and when that decorator is called that assignment has not yet happened. The difference is small, but you can write decorators which depend on it. For example, the code I posted in depends on this difference and will not work if you write the calls out explicitly instead of using decorators. From spam at spam.com Wed Aug 15 09:03:55 2007 From: spam at spam.com (daz.diamond) Date: Wed, 15 Aug 2007 13:03:55 GMT Subject: ming on win32 anyone ? [help a noob] Message-ID: <%QCwi.14541$rr5.1213@newsfe1-win.ntli.net> hoping someone can help ... how do I install ming (with python) on win32? have downloaded the tar.gz of ming-0.3.0 which doesn't have a handy self-installer, and I'm absolutely foxed as to what to do next ... the install instructions in the package seem to be linux oriented, which to me may as well be in greek any clues much appreciated, thx daz From neil.chriss at gmail.com Sun Aug 5 04:25:28 2007 From: neil.chriss at gmail.com (RichSaneSwindler) Date: Sun, 05 Aug 2007 08:25:28 -0000 Subject: Pyscripter Message-ID: <1186302328.706942.242920@q75g2000hsh.googlegroups.com> I think that pyscripter is the most promising Python IDE around and I am exciting about its possibilities. However, I find a few issues with it annoying enough that I don't use it. They seem easily fixed in which case I think it would be superior to most IDEs. I am wondering if any users out there would like to add to/debate this list of benefits and issues (for reference I am using Pyscripter Pyscripter Benefits: - very fast, stable GUI (compare this with Wing IDE which is horrendously slow) - screen lay it clean and uncluttered - source completion is lightning fast and I like the option to search files for selected modules - source completion searches submodules (as in "os.path.") - function search, etc. Pyscripter Issues: 1. smart tabbing: a. If I place the cursor anywhere in a, hitting the tab should properly indent the line to (most often) the unique correct place or (less often) to its best guess as to where to tab. Right now the editor inserts a tab, which I never want to do. a Smart tabbing for multiline expressions (eg expressions broken within parens) does not work well. 2. there is no source completion for local variables (or at least I cannot figure out how to use it). This is a major difference between it and Wing IDE. 3. source completion is easily fooled. If I type "os.path.join(fnam" and then backspace to "os.path.jo", the completion menu does not come back up. The same statement goes for the tooltips for functions. 4. lack of emacs key bindings as an option: yes you can add them, but adding shortcuts is very difficult due to the fact that key bindings are listed in both the IDE and Editor options section. 5. poor module handling in debugger mode/within the editor. I have not fully figured out what is going on, but a modules behavior during debugging or execution within the editor does not fully match behavior outside of it. E.g., when you run a module in debugger mode its behavior is not the same as if you run it from the command prompt. I think that the module is not loaded. To see this, create a module and type "print __file__" in some function. This will work from the command prompt but not from the module. If you add "from module-name import __file__" this solves it, but you should not have to do that. 6. No "Doc String" list. It would be nice if when you put the cursor over a function a window would display the full docstrings of the function. 7. The function tool tips (ie what you see when you hover over a function or open parens) are primitive looking and could show more of the functions docstrings. - poor module re-loading. If I import moduleA into moduleB and then change moduleA, when I debug, the change is not reloaded (as far as I can tell). This is aggravating. 8. lack of "IPython" like interface in the shell. Would be nice if emacs keybindings were available. 9. (would be nice) Refactoring capabilities (ala Eclipse's capabilities, especially for Python) 10. The web page http://pyscripter.googlepages.com/ has a much newer build than http://mmm-experts.com/Products.aspx?ProductId=4. I want to emphasize again that despite this lists length I think the core aspects of the system (speed and stability) are far and away better than anything else I have used. Thank you, Neil Chriss From tleeuwenburg at gmail.com Thu Aug 30 17:35:00 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: Thu, 30 Aug 2007 21:35:00 -0000 Subject: Setting a read-only attribute Message-ID: <1188509700.915517.178440@z24g2000prh.googlegroups.com> I have an object and wish to set an attribute on it which, unfortunately for me, is read-only. How can I go about this? Cheers. -T From pyth0nc0d3r at gmail.com Fri Aug 24 17:00:35 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Fri, 24 Aug 2007 16:00:35 -0500 Subject: Problem w/ Tkinter Message-ID: How do I add a command to a button say for instance class MYCLASNAME: def choices(self): choices = Toplevel() v = IntVar() a = Radiobutton(choices, text="Add News", variable=v,value=1).pack(anchor=W) b = Radiobutton(choices, text="Edit News", variable=v,value=2).pack(anchor=W) c = Radiobutton(choices, text="Delete News", variable=v,value=3).pack(anchor=W) d = Radiobutton(choices, text="Quit", variable=v,value=4).pack(anchor=W) button = Button(choices, text="Action?",command=self.V (a,b,c,d)).pack(anchor=W) choices.title("What are your actions?") def V(self,a,b,c,d): if a != "": print a elif b != "": print b elif c != "": print c elif d != "": print d else: print "error"; button = Button(choices, text="Action?",command=self.V(a,b,c,d)).pack(anchor=W) doesn't even do anything, what can I do to fix this problem? -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Tue Aug 7 13:42:20 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 07 Aug 2007 17:42:20 GMT Subject: Another question about variable args. References: Message-ID: On 2007-08-07, Steven W. Orr wrote: > I have a structure I need to pack. I call struct.pack about a dozen times > and each call takes about 53 arguments. > > I create a sequence of the arguments: > a1 = 1 > a2 = 2 > a3 = 3 > etc... > a54 = 88 > myseq = (a1, a2, a3, a4 etc... a53) > Also I made > > def mpack ( fmt, *ss ): > print type(ss) > for ii in ss: > print 'ii = ', ii, 'type(ii) = ', type(ii) > for ii in list(ss): > print 'ii = ', ii, 'type(ii) = ', type(ii) > return struct.pack(fmt, *ss ) > > In my main, this first print statement works. > print 'main:', mpack(ff, a, b, c, d, e, f, g, h, i) > > 1. For the life of me, I can't figure out what to do to get the > next print to work. The idea is that I want to make my code > clearer by not passing 50+ args each time and to instead pass a > sequence which when evaluated will be the desired list of args. > > print 'main:', mpack(ff, subseq) > > 2. And then, if possible, I'd like to do it in such a way that > one myseq is defined, its value can automagically be re-eval'd > so I don't have to re-assign to myseq each time one of the 50+ > variables changes prior to calling pack. A functor might be a fun solution. class mpack_maker(object): def __init__(self, fmt, *args): self.fmt = fmt self.arg_list = list(args) def __call__(self, slice=None, subseq=None): if slice: self.arg_list[slice] = subseq return struct.pack(self.fmt, *self.arg_list) You can pass in a slice object and a subsequence to change arguments (permanently). >>> mpack = mpack_maker(ff, a, b, c, d, e, f, g, h) >>> mpack() # Call the function >>> mpack(slice(5, 7), [0, 7]) # Change args 5 and 6, and call again. The args you can change are limited by the slicing powers of Python, and probably combining arg-changing with calling the function isn't wise, but that's a sketch anyhow. -- Neil Cerutti We couldn't beat... us. We couldn't even beat us. I was trying to think of somebody bad, and I couldn't think of anybody else. Us. --Tim Legler From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Aug 10 06:01:12 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 10 Aug 2007 12:01:12 +0200 Subject: Stackless Integration In-Reply-To: References: <46bb1df0$0$403$426a74cc@news.free.fr> Message-ID: <46bc375b$0$406$426a34cc@news.free.fr> Steve Holden a ?crit : > Bruno Desthuilliers wrote: >> Jean-Paul Calderone a ?crit : >>> On Thu, 09 Aug 2007 09:00:27 -0000, "Justin T." >>> wrote: >>>> Hi, >>>> >>>> I've been looking at stackless python a little bit, and it's awesome. >>>> My question is, why hasn't it been integrated into the upstream python >>>> tree? Does it cause problems with the current C-extensions? It seems >>>> like if something is fully compatible and better, then it would be >>>> adopted. However, it hasn't been in what appears to be 7 years of >>>> existence, so I assume there's a reason. >>> It's not Pythonic. >> >> Hum... Yes ? Really ? Care to argument ? > > Unfortunately such arguments quickly descend to the "yes it is", "no it > isn't" level, as there is no objective measure of Pythonicity. indeed !-) But that doesn't prevent from honestly trying to explain why one asserts such a thing - which Jean-Paul did in another post in this thread. > Twisted is a complex set of packages Sure. Now I may be dumb, but I thought it was about stackless, not about Twisted... From fccoelho at gmail.com Mon Aug 6 10:13:51 2007 From: fccoelho at gmail.com (Flavio) Date: Mon, 06 Aug 2007 14:13:51 -0000 Subject: boolean operations on sets Message-ID: <1186409631.147290.323400@22g2000hsm.googlegroups.com> Hi, I have been playing with set operations lately and came across a kind of surprising result given that it is not mentioned in the standard Python tutorial: with python sets, intersections and unions are supposed to be done like this: In [7]:set('casa') & set('porca') Out[7]:set(['a', 'c']) In [8]:set('casa') | set('porca') Out[8]:set(['a', 'c', 'o', 'p', 's', 'r']) and they work correctly. Now what is confusing is that if you do: In [5]:set('casa') and set('porca') Out[5]:set(['a', 'p', 'c', 'r', 'o']) In [6]:set('casa') or set('porca') Out[6]:set(['a', 'c', 's']) The results are not what you would expect from an AND or OR operation, from the mathematical point of view! aparently the "and" operation is returning the the second set, and the "or" operation is returning the first. If python developers wanted these operations to reflect the traditional (Python) truth value for data structures: False for empty data structures and True otherwise, why not return simply True or False? So My question is: Why has this been implemented in this way? I can see this confusing many newbies... From http Wed Aug 22 01:33:45 2007 From: http (Paul Rubin) Date: 21 Aug 2007 22:33:45 -0700 Subject: for statement on empty iterable References: <1187760507.951994.50310@q4g2000prc.googlegroups.com> Message-ID: <7xabsk3zgm.fsf@ruckus.brouhaha.com> james_027 writes: > for i in []: > #do something > is this safe? or should I put a if statement to test it first? That doesn't crash or anything like that, but it also doesn't set the index variable, which can cause confusion in some situations. From annannienann at yahoo.co.uk Fri Aug 24 05:35:05 2007 From: annannienann at yahoo.co.uk (Peter Sutton) Date: Fri, 24 Aug 2007 09:35:05 +0000 (GMT) Subject: Clipboard Monitor (tkinter,windows) Message-ID: <797532.82583.qm@web27210.mail.ukl.yahoo.com> Hi. I am an A-level student studying computer science. I have taken it upon myself to learn python. It is now my weapon of choice. I have had a problem trying to creating a clipboard monitor in Windows(XP,Vista) that is linked to a tkinter GUI. I have a perfectly good code for clipboard monitoring, but as soon as it is linked to a tkinter gui, the gui locks when a WM.DRAWCLIPBOARD message is recieved. I am at the point of giving up. If anyone can help or offer an alternative....that is not polling....I would be very happy. Thanks. Peter import win32ui, win32clipboard, win32con, win32api, win32gui from Tkinter import * def paste(): win32clipboard.OpenClipboard(0) data = win32clipboard.GetClipboardData() win32clipboard.CloseClipboard() return data class ClipRecord(object): def __init__(self): self.gui = Tk() self.hPrev = 0 self.first = True self.win = win32ui.CreateFrame() self.win.CreateWindow(None,'',win32con.WS_OVERLAPPEDWINDOW) self.win.HookMessage(self.OnDrawClipboard,win32con.WM_DRAWCLIPBOARD) self.win.HookMessage(self.OnChangeCBChain,win32con.WM_CHANGECBCHAIN) self.win.HookMessage(self.OnDestroy,win32con.WM_DESTROY) try: self.hPrev=win32clipboard.SetClipboardViewer(self.win.GetSafeHwnd()) except win32api.error, err: if win32api.GetLastError () == 0: # information that there is no other window in chain pass else: raise self.l = Label(self.gui,text="I have losted the will to live") self.l.pack() self.gui.mainloop() def OnChangeCBChain(self, *args): msg, wParam, lParam = args[-1][1:4] if self.hPrev == wParam: # repair the chain self.hPrev = lParam if self.hPrev: # pass the message to the next window in chain win32api.SendMessage (self.hPrev, msg, wParam, lParam) def OnDrawClipboard(self, *args): msg, wParam, lParam = args[-1][1:4] if self.first: self.first = False else: self.l["text"] = "Lord be Praised" print paste() if self.hPrev: # pass the message to the next window in chain win32api.SendMessage (self.hPrev, msg, wParam, lParam) def OnDestroy(self): if self.hPrev: win32clipboard.ChangeClipboardChain(self.win.GetSafeHwnd(),self.hPrev) else: win32clipboard.ChangeClipboardChain(self.win.GetSafeHwnd(),0) if __name__ == "__main__": cr = ClipRecord() ___________________________________________________________ Yahoo! Answers - Got a question? Someone out there knows the answer. Try it now. http://uk.answers.yahoo.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From phil at riverbankcomputing.co.uk Mon Aug 27 16:40:28 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Mon, 27 Aug 2007 21:40:28 +0100 Subject: [PyQt] Help on resizing a custom widget In-Reply-To: <1188240870.457859.207670@57g2000hsv.googlegroups.com> References: <1188240870.457859.207670@57g2000hsv.googlegroups.com> Message-ID: <200708272140.28368.phil@riverbankcomputing.co.uk> On Monday 27 August 2007, skawaii at gmail.com wrote: > Ok, here's what's going on. I've just created a custom widget. it > works great. I'm having some trouble, however, figuring out how to > allow the said widget to resize. For example, when I throw the widget > into a new dialog (using Qt Designer), I want to be able to drag it > larger/smaller and have widget expand/shrink to that size. Right now, > I can drag the widget bigger/smaller all I want, but it doesn't > actually change size. > > I'm pretty new to PyQt (and therefore, Qt), so I'm pretty sure that > the answer is a property that needs to be set somewhere. I'm just not > sure which one. So you know, I'm using Python 2.4.3 and PyQt 3.1.6. > > Any help and suggestions would be appreciated. Thanks. Probably best to start with the following... http://doc.trolltech.com/4.3.0/layout.html#custom-widgets-in-layouts Phil From tim at tdw.net Fri Aug 24 15:34:45 2007 From: tim at tdw.net (Tim Williams) Date: Fri, 24 Aug 2007 20:34:45 +0100 Subject: Using Regular Expresions to change .htm to .php in files In-Reply-To: <46CF1437.9020200@sdf.lonestar.org> References: <9afea2ac0708231305v539390dew84926f0b0dcd6974@mail.gmail.com> <46CF1437.9020200@sdf.lonestar.org> Message-ID: <9afea2ac0708241234u4f13b80an62b6b4b5b1eb33af@mail.gmail.com> On 24/08/07, J. Cliff Dyer wrote: > Tim Williams wrote: > > On 23/08/07, sebzzz at gmail.com wrote: > > > >> Hi, > >> > >> I have a bunch of files that have changed from standard htm files to > >> php files but all the links inside the site are now broken because > >> they point to the .htm files while they are now .php files. > >> > >> Does anyone have an idea about how to do a simple script that changes > >> each .htm in a given file to a .php > >> > >> Thanks a lot in advance > >> > >> > > > > Something like: > > > > Infile = open(f_name,'r+') > > Data = Infile.read() > > InFile.write(Data.replace('.htm','.php')) > > Infile.close() > > > > :) > > > Yeah, but you'd better make darn sure that *all* links point to .htm > files (including external links), because you could very easily end up > pointing to http://some.othersite.com/index.phpl > > And that's just no good. > > -- Tim Williams From Werner.Merkl at fujitsu-siemens.com Thu Aug 30 02:42:56 2007 From: Werner.Merkl at fujitsu-siemens.com (Werner) Date: Wed, 29 Aug 2007 23:42:56 -0700 Subject: self extracting zipefile (windows) and (standard module) zipefile In-Reply-To: <13dchmplshc2uff@corp.supernews.com> References: <1188388421.010643.19050@50g2000hsm.googlegroups.com> <1188393907.080206.246270@y42g2000hsy.googlegroups.com> <13db09i6rrnjc22@corp.supernews.com> <13dchmplshc2uff@corp.supernews.com> Message-ID: <1188456176.512387.177020@w3g2000hsg.googlegroups.com> On 30 Aug., 06:26, Scott David Daniels wrote: > Grant Edwards wrote: > > ... > > > Another option is to search through the file from the beginning > > looking for whatever signature matches the beginning of a > > "normal" zip file. The self-extracting zipfiles that I've > > dissected are just an executable image concatenated with a > > "normal" zipfile. If you just start searching from the > > beginning of the file, it's simple to find the actual zip data > > and copy it into a separate file which then can be unzipped > > like any other plain zipfile. > > Actually, the zip format is defined from the _end_ rather than > the _beginning_ of the file. Some random file with a zip file > concatenated on the end will have the same contents as the zip > file. You can even point Python itself at such files and get > data via: > import zipfile > zf = zipfile.ZipFile('something.exe') > ... > > -Scott David Daniels > Scott.Dani... at Acm.Org I hoped, this would work, but I got ": File is not a zip file"... WinZip and 7-ZIP may handle this file, so I take the command line version of 7-Zip (but I'd prefered a Python only version) Thanks Werner From mail at microcorp.co.za Thu Aug 23 05:54:01 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 23 Aug 2007 11:54:01 +0200 Subject: Socket recv(1) seems to block instead of returning end of file. Message-ID: <000901c7e56b$a2c17fc0$03000080@hendrik> While doing a netstring implementation I noticed that if you build a record up using socket's recv(1), then when you close the remote end down, the recv(1) hangs, despite having a short time out of 0.1 set. If however, you try to receive more than one char, (I tested with 3, did not try 2), then when you shut the remote end down you do not get a time out, but an empty string - the normal end of file, I suppose. Has anybody else seen this behaviour? The transmit side seems to give a broken pipe error, which is fine. I am using stock standard SuSe 10, Python 2.4, out of the box. - Hendrik From steve at holdenweb.com Thu Aug 23 23:34:57 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 23 Aug 2007 23:34:57 -0400 Subject: creating a tar file with python In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE2EE@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> <93066C069973ED448DC2BCEA9C44A7383BE2ED@efmailx> <46CE4D3D.7020106@holdenweb.com> <93066C069973ED448DC2BCEA9C44A7383BE2EE@efmailx> Message-ID: <46CE51E1.9020608@holdenweb.com> Brian McCann wrote: > > > Steve, > > I ran the code as you suggested, didn't work, tried variations of it > didn't work, > If you don't know the answer don't pretend you do! > > Apology not accepted, please don't wake up! > > Future correspondence on any python questions from you go to trash. > May your pillow not have pity on your head! > Well in that case it might have been a good idea to post the error message you got from trying what I suggested rather than the one you got from your fifteenth variation on my (admittedly untested) suggestion. Not to worry, I know not to try and help you any further. Sorry my limited Python experience wasn't able to help you solve your problem. [plonk] regards Steve PS: this reply is *much* more polite than the one that first came to mind, which involved making suggestions involving sex and travel. You're on your own from here on in. I don't like being incited to spew profanity on a list of people I respect. -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bj_666 at gmx.net Fri Aug 17 02:19:34 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 Aug 2007 06:19:34 GMT Subject: to property or function in class object References: <1187317787.848991.242720@i38g2000prf.googlegroups.com> Message-ID: <5iksvmF3oltfoU1@mid.uni-berlin.de> On Fri, 17 Aug 2007 02:29:47 +0000, james_027 wrote: > i am very new to python, not knowing much about good design. I have an > object here for example a Customer object, where I need to retrieve a > info which has a number of lines of code to get it. > > my question is weather what approach should I use? to use the property > which is from the python new class style as I understand or simple use > function that will return the the info I needed. I'd say it's a matter of taste here. Where `get_*` and `set_*` methods should not be used is getting and setting simple attributes. Here properties are very handy if such a simple attribute changes to something calculated later on, because it is possible to change the class without the need to change the code that uses such objects. In the other case, more complex code to get or set some information in the first place, it is a matter of taste IMHO. Ask yourself if the user would expect `balance` to be an attribute of that class. If it seems to be "natural" to have such an attribute. And usually attribute access does not trigger really heavy computation. Constructing the answer from some different attributes or doing a conversion before returning something is okay, but a calculation that lasts an hour or so would surprise many. Ciao, Marc 'BlackJack' Rintsch From david at asdf.asdf Thu Aug 30 21:03:31 2007 From: david at asdf.asdf (bambam) Date: Fri, 31 Aug 2007 11:03:31 +1000 Subject: beginner, idomatic python 2 References: <13csjmeaoqh9le3@corp.supernews.com> <1187927388.173203.298660@e9g2000prf.googlegroups.com> <13d4jfjfogbvq6f@corp.supernews.com> Message-ID: <13deq74b634tb07@corp.supernews.com> Thank you. I'm glad to see that I don't need to choose between two opposing viewpoints :~) Steve. From stefan.behnel-n05pAM at web.de Wed Aug 1 16:37:17 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 01 Aug 2007 22:37:17 +0200 Subject: force unicode strings In-Reply-To: <5hbmjcF3gtt39U1@mid.individual.net> References: <5hbmjcF3gtt39U1@mid.individual.net> Message-ID: <46B0EEFD.1090709@web.de> Thomas Guettler wrote: > is it possible to force all non ascii strings to be unicode strings > somehow? > > Sometimes I forget that I need to write u'...' if the string contains > an umlaut. I get an exception in django later. But since the > exception does not show the string it is hard to find it. I guess you can't afford to wait for Python 3, can you? http://www.python.org/dev/peps/pep-3100/#atomic-types Stefan From jstroud at mbi.ucla.edu Thu Aug 9 20:27:36 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 09 Aug 2007 17:27:36 -0700 Subject: Importing to Message-ID: Many thanks to the numerous helpful comments by Paul Rubin, Carsten Haese and others in the thread "How to pass a reference to the current module". After digesting these comments, I came up with this way to circumvent the problem of attempting to reference modules that import other modules in said imported modules (executed in main): # branches ==> dictionary of dictionaries (actually a ConfigObj) for (name, branch) in branches.items(): modname = branch.get('__module__', None) if modname is None: namespace = globals() else: namespace = __import__(modname).globals() fname = branch.get('__function__', name) function = namespace[fname] # etc. I'm wondering if this approach seems problematic to anyone. Thanks again for all of the help I've received. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From simon at brunningonline.net Tue Aug 21 13:24:22 2007 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 21 Aug 2007 18:24:22 +0100 Subject: Retrieving a variable's name. In-Reply-To: <1187658202.236626.93600@50g2000hsm.googlegroups.com> References: <1187658202.236626.93600@50g2000hsm.googlegroups.com> Message-ID: <8c7f10c60708211024j5e5765bal4ee915df7539879a@mail.gmail.com> On 8/21/07, rodrigo wrote: > How would I go about retrieving a variable's name (not its value)? http://effbot.org/pyfaq/how-can-my-code-discover-the-name-of-an-object.htm -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From miki.tebeka at gmail.com Fri Aug 31 13:33:43 2007 From: miki.tebeka at gmail.com (Miki) Date: Fri, 31 Aug 2007 17:33:43 -0000 Subject: Is there a simple way to exit a while loop on keystroke? In-Reply-To: <1188578827.809840.90100@r29g2000hsg.googlegroups.com> References: <1188578827.809840.90100@r29g2000hsg.googlegroups.com> Message-ID: <1188581623.588967.78050@z24g2000prh.googlegroups.com> Hello, > I am new to python, and have written a simple program to read a port > via telnet. I would like it to run until any key is pressed. Of > course I wouldn't mind requiring a specific keystroke in the future, > but I would think this is simpler for now. > > I have used kbhit() and getch() many times in C, but I can't find > anything similar in Python. I am using Linux also, so the msvcrt > code isn't an option. I have tried sys.stdin.read(), but that hangs > UNTIL a key is pressed. You might want to look at http://docs.python.org/lib/module-curses.html Another solution is to ask the user to hit CTRL-C from time import sleep try: while 1: print "BEEP" sleep(1) except KeyboardInterrupt: print "BYE BYE" HTH, -- Miki http://pythonwise.blogspot.com From bj_666 at gmx.net Wed Aug 22 03:39:37 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Aug 2007 07:39:37 GMT Subject: creating a dictionary from a dictionary with regex References: <1187766820.785959.170190@r23g2000prd.googlegroups.com> Message-ID: <5j27hpF3sh73oU1@mid.uni-berlin.de> On Wed, 22 Aug 2007 07:13:40 +0000, james_027 wrote: > I am trying to create a dictionary from a dictionary which the help of > regex to identify which keys to select. I have something like this but > I feel its long and not the fastest solution ... could someone > contribute? > > import re > > d= {'line2.qty':2, 'line3.qty':1, 'line5.qty':12, 'line2.item':'5c-BL > Battery', 'line3.item':'N73', 'line5.item':'Screen Cover'} > > collected = [k[:5] for k in d if re.match('^line\d+\.qty',k)] > > for i in collected: > d2 = {} > for k in d: > if re.match('^%s\.\D+' % i, k): > d2[k] = d[k] > print d2 You are iterating over `d` for every item in `collected`. With another `dict` to store the results you can iterate over `d` only once: from collections import defaultdict def main(): d= {'line2.qty':2, 'line3.qty':1, 'line5.qty':12, 'line2.item':'5c-BL Battery', 'line3.item':'N73', 'line5.item':'Screen Cover'} result = defaultdict(dict) for key, value in d.iteritems(): new_key = key.split('.', 1)[0] # Get the 'line#' part. result[new_key][key] = value print result Ciao, Marc 'BlackJack' Rintsch From carsten at uniqsys.com Fri Aug 3 14:16:59 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 03 Aug 2007 14:16:59 -0400 Subject: Global package variable, is it possible? In-Reply-To: <46b36b31$0$10622$4fafbaef@reader2.news.tin.it> References: <1186160415.065108.139160@e9g2000prf.googlegroups.com> <46b36b31$0$10622$4fafbaef@reader2.news.tin.it> Message-ID: <1186165019.3382.42.camel@dot.uniqsys.com> On Fri, 2007-08-03 at 17:51 +0000, Fabio Z Tessitore wrote: > Heve you tried to do something like: > > # module configure.py > value1 = 10 > value2 = 20 > ... > > > # other module > from configure import * > > # now I'm able to use value1 value2 etc. > var = value1 * value2 Right idea, wrong execution. Note that the OP said "I'd like to be able to reload the config file dynamically and have all my modules automatically receive the new config." "from configure import *" will import the settings into the current namespace, and subsequent changes in the original namespace will, in general, not have any effect in the current namespace. This should do the trick: # module configure.py value1 = 10 value2 = 20 ... # other module import configure var = configure.value1 * configure.value2 HTH, -- Carsten Haese http://informixdb.sourceforge.net From steve at holdenweb.com Tue Aug 7 03:21:37 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 07 Aug 2007 03:21:37 -0400 Subject: parsing a dbIII file In-Reply-To: <1186469710.277542.246430@w3g2000hsg.googlegroups.com> References: <1186469710.277542.246430@w3g2000hsg.googlegroups.com> Message-ID: korovev76 at gmail.com wrote: > Hello everybody, I'm new to python (...I work with cobol...) > > I have to parse a file (that is a dbIII file) whose stucture look like > this: > |string|, |string|, |string that may contain commas inside|, 1, 2, 3, | > other string| > > Is there anything in python that parses this stuff? > > > thanks a lot > korovev > That's not a standard dBaseIII data file though, correct? It looks more like something that was produced *from* a dBaseIII file. If the format is similar to Excel's CSV format then the csv module from Python's standard library may well be what you want. Otherwise there are parsers at all levels - one called PyParsing is quite popular, and I am sure other readers will have their own suggestions. I am not sure whether the pipe bars actually appear in your data file, so it is difficult to know quite exactly what to suggest, but I would play with the file in an interactive interpreter session first to see whether csv can do the job. Good luck with your escape from COBOL! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From greg at cosc.canterbury.ac.nz Fri Aug 10 05:28:39 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 10 Aug 2007 21:28:39 +1200 Subject: is there anybody using __del__ correctly?? In-Reply-To: <1186731369.073644.158490@z24g2000prh.googlegroups.com> References: <1186731369.073644.158490@z24g2000prh.googlegroups.com> Message-ID: <5i2plfF3mlqtnU1@mid.individual.net> Michele Simionato wrote: > So I did, and to my dismay 95% of the __del__ methods in the standard > library are just calling a close method! You can't conclude that this is wrong just from looking at the __del__ method itself. You need to consider whether there is any way the thing being closed could be referenced from somewhere else. If that's so, the __del__ method may be performing a useful service by closing it more promptly than it would otherwise be. -- Greg From google at mrabarnett.plus.com Fri Aug 31 14:58:45 2007 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 31 Aug 2007 11:58:45 -0700 Subject: strings (dollar.cents) into floats In-Reply-To: <46d84a47$0$1346$834e42db@reader.greatnowhere.com> References: <877incd20i.fsf@benfinney.id.au> <46d75cf3$0$7698$9b4e6d93@newsspool2.arcor-online.net> <1188575044.874256.42960@50g2000hsm.googlegroups.com> <46d84a47$0$1346$834e42db@reader.greatnowhere.com> Message-ID: <1188586725.667740.255700@o80g2000hse.googlegroups.com> On Aug 31, 5:39 pm, David H Wild wrote: > In article , > Chris Mellon wrote: > > > I believe that to the degree that "real" accounting was done in those > > currencies it did in fact use non-decimal bases. Just as people don't > > use decimal time values (except us crazy computer folk), you're write > > 1 pound 4 shillings, not 1.333... pounds. > > When I worked on the British Railways National Payroll system, about 35 > years ago, we, in common with many large users, wrote our system to deal > with integer amounts of pennies, and converted to pounds, shillings and > pence in the output part of the system. > So you never handled halfpennies? From ptmcg at austin.rr.com Fri Aug 24 20:51:16 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 24 Aug 2007 17:51:16 -0700 Subject: Parser Generator? In-Reply-To: <_6mdnZxbdNKTVFrbnZ2dnUVZ_tqtnZ2d@comcast.com> References: <_6mdnZxbdNKTVFrbnZ2dnUVZ_tqtnZ2d@comcast.com> Message-ID: <1188003076.702532.241950@q3g2000prf.googlegroups.com> On Aug 18, 11:37 pm, "Jack" wrote: > Thanks for all the replies! > > SPARK looks promising. Its doc doesn't say if it handles unicode > (CJK in particular) encoding though. > > Yapps also looks powerful:http://theory.stanford.edu/~amitp/yapps/ > > There's also PyGgyhttp://lava.net/~newsham/pyggy/ > > I may also give Antlr a try. > > If anyone has experiences using any of the parser generators with CJK > languages, I'd be very interested in hearing that. > > Jack > > "Jack" wrote in message > > news:abKdnVoQMu2o7FrbnZ2dnUVZ_gqdnZ2d at comcast.com... > > > > > Hi all, I need to do syntax parsing of simple naturual languages, > > for example, "weather of London" or "what is the time", simple > > things like these, with Unicode support in the syntax. > > > In Java, there are JavaCC, Antlr, etc. I wonder what people use > > in Python? Antlr also has Python support but I'm not sure how good > > it is. Comments/hints are welcome.- Hide quoted text - > > - Show quoted text - Jack - Pyparsing was already mentioned once on this thread. Here is an application using pyparsing that parses Chinese characters to convert to English Python. http://pypi.python.org/pypi/zhpy/0.5 -- Paul From multiseed at gmail.com Tue Aug 21 17:21:57 2007 From: multiseed at gmail.com (Shiao) Date: Tue, 21 Aug 2007 21:21:57 -0000 Subject: Logging module gives duplicate log entries In-Reply-To: References: <1187702248.203917.188570@k79g2000hse.googlegroups.com> Message-ID: <1187731317.661324.244870@k79g2000hse.googlegroups.com> > > You need to remove the handler from the logging object > > # remove the handler once you are done > applog.removeHandler(hdl) > > Cheers, > amit. > I'm not sure how this could help. From wollez at gmx.net Fri Aug 10 05:00:25 2007 From: wollez at gmx.net (WolfgangZ) Date: Fri, 10 Aug 2007 11:00:25 +0200 Subject: subprocess.Popen(cmd) question Message-ID: Hello, I'm starting some subprocesses inside a loop. The processes run independent and dont need any communication between each other. Due to memory issues I need to limit the number of running processes to around 10. How can I insert a break into my loop to wait until some processes are finished? Some minimal examplecode: import subprocess for i in range(0,100): cmd='ping localhost' p=subprocess.Popen(cmd) p.wait() Thanks for any ideas. Wolfgang From kj7ny at nakore.com Wed Aug 8 03:16:24 2007 From: kj7ny at nakore.com (kj7ny) Date: Wed, 08 Aug 2007 00:16:24 -0700 Subject: How can I programmatically find the name of a method from within that method? In-Reply-To: References: <1186548312.672360.259100@q3g2000prf.googlegroups.com> Message-ID: <1186557384.845276.151630@i13g2000prf.googlegroups.com> On Aug 7, 10:09 pm, Jay Loden wrote: > kj7ny wrote: > > Is there a way that I can programmatically find the name of a method I > > have created from within that method? I would like to be able to log > > a message from within that method (def) and I would like to include > > the name of the method from which it was written without having to > > hard-code that value in every message string. While we're at it, is > > there a way to programmatically get the name of the class and the > > module while I'm at it? > > This is a frequently asked question around here :-) > > You should search the list archives for past threads, e.g:http://aspn.activestate.com/ASPN/Mail/Message/python-list/3542665 > > -Jay Thanks for the link. I had actually searched the past threads, but apparently didn't enter the right search criteria because I did not find that thread. Or, that thread isn't findable by searching Google groups? I tried the example in the interpreter and it appears to work. Despite my years and years of programming in python, I am a bit baffled by the example though. What is @checkPrivs (see example copied below from other post)? In fact... how does the thing work at all? ------------------------------------------ def checkPrivs(fn): fnName = fn.func_name def restricted(*args): print "about to call function", fnName if fnName in listOfAllowedFunctions: return fn(*args) else: raise KeyError("you don't have sufficient privileges to do THAT") return restricted listOfAllowedFunctions = ['add','subtract'] @checkPrivs def add(a,b): return a+b @checkPrivs def subtract(a,b): return a-b @checkPrivs def multiply(a,b): return a*b add(1,2) subtract(4,1) multiply(3,2) From kyosohma at gmail.com Thu Aug 23 16:09:52 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 23 Aug 2007 13:09:52 -0700 Subject: Newbie: List file system roots In-Reply-To: References: Message-ID: <1187899792.259346.136640@r23g2000prd.googlegroups.com> On Aug 23, 2:48 pm, "Einar W. H?st" wrote: > Hi, > > How would you list the file system roots in Python? That is, I'm looking > for a way to list all connected drives (C:, D: etc) on a Windows box, or > all /root, /tmp etc on a *nix box. In Java, there's a built-in API > function to do this, File.listRoots(), but I couldn't find any > equivalents in the Python libraries. > > Kind regards, > Einar Looks like the win32 modules save the day again. http://mail.python.org/pipermail/python-win32/2004-January/001562.html from win32com.client import Dispatch fso = Dispatch('scripting.filesystemobject') for i in fso.Drives : print i # Mike From koje_je_ono_bilo_pitanje at bla.bla Tue Aug 28 16:11:29 2007 From: koje_je_ono_bilo_pitanje at bla.bla (Boris Ozegovic) Date: Tue, 28 Aug 2007 22:11:29 +0200 Subject: localhost, ?! References: <5jjbpfF3sm4m7U2@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > Definitely a problem with the web server (503 means "service > unavailable"). I did try on two servers, Apache and simple python server. There was identically error on both servers. >> Anybody have slightest clue wthat is going on? :-/ > > Try using wireshark or a similar tool to see what's going on on > protocol level. Ok. From gagsl-py2 at yahoo.com.ar Mon Aug 20 16:18:00 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 20 Aug 2007 13:18:00 -0700 Subject: urllib2.urlopen(url) pulling something other than HTML In-Reply-To: <1187635452.841155.88720@a39g2000hsc.googlegroups.com> References: <1187635452.841155.88720@a39g2000hsc.googlegroups.com> Message-ID: <1187641080.516885.122350@g4g2000hsf.googlegroups.com> On 20 ago, 15:44, "dogatemycompu... at gmail.com" wrote: > ---------------------------------------------------------- > f = formatter.AbstractFormatter(formatter.DumbWriter(StringIO())) > parser = htmllib.HTMLParser(f) > parser.feed(html) > parser.close() > return parser.anchorlist > ---------------------------------------------------------- The htmllib.HTMLParser class is hard to use. I would replace those lines with: from HTMLParser import HTMLParser class MyHTMLParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.anchorlist = [] def handle_starttag(self, tag, attrs): if tag=="a": href = dict(attrs).get("href") if href: self.anchorlist.append(href) parser = MyHTMLParser() parser.feed(htmltext) print parser.anchorlist The anchorlist attribute, defined by myself here, is a list containing all href attributes found in the page. See > I get the idea that we're allocating some memory that looks like a > file so formatter.dumbwriter can manipulate it. The results are > passed to formatter.abstractformatter which does something else to the > HTML code. The results are then passed to "f" which is then passed to > htmllib.HTMLParser so it can parse the html for links. I guess I > don't understand with any great detail as to why this is happening. > I know someone is going to say that I should RTFM so here is the gist > of the documentation: Don't even try to understand it - it's a mess. Use the HTMLParser module instead. > The last question is.. I can't find any documentation to explain > where the "anchorlist" attribute came from? Here is the only > reference to this attribute that I can find anywhere in the Python > documentation. And that's all you will find. > So .. How does an average developer figure out that parser returns a > list of hyperlinks in an attribute called anchorlist? Is this Usually, those attributes are hyperlinked and you can find them in the documentation index. Not for this one :( > something that you just "figure out" or is there some book I should be > reading that documents all of the attributes for a particular > method? It just seems a bit obscure and certainly not something I > would have figured out on my own. Does this make me a poor developer > who should find another hobby? I just need to know if there is > something wrong with me or if this is a reasonable question to ask. It's a very reasonable question. The attribute should be documented properly. But the class itself is a bit old; I don't never use it anymore. > The last question I have is about debugging. The spider is capable > of parsing links until it reaches: > > "html = get_page(http://www.google.com/jobs/fortune)" which returns > the contents of a pdf document, assigns the pdf contents to html which > is later passed to parser.feed(html) which crashes. You can verify the Content-Type header before processing. Quoting the get_page method: > def get_page(url, log): > """Retrieve URL and return comments, log errors.""" > try: > page = urllib2.urlopen(url) > except urllib2.URLError: > log("Error retrieving: " + url) > return '' > body = page.read() > page.close() > return body >From , the urlopen method returns a file-like object, which has an additional info() method holding the response headers. You can get the Content-Type using page.info().gettype(), which should be text/html or text/xhtml. For any other type, just return '' as you do for any error. -- Gabriel Genellina From horpner at yahoo.com Sat Aug 4 10:32:39 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 04 Aug 2007 14:32:39 GMT Subject: the one python book References: Message-ID: On 2007-08-04, dhr wrote: > newbie question: > > Is there a 'K&R" type of Python book? The book that you'd > better have on your shelf if you are going into Python? C is such a small language that the same slim volume can be both a great tutorial and an awesome language reference. With Python, you won't find anything like that. Python is too huge. So get used to the idea of needing several books. ;) -- Neil Cerutti From __peter__ at web.de Fri Aug 10 04:12:02 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 10 Aug 2007 10:12:02 +0200 Subject: float to string with different precision References: <1186731617.128913.279360@m37g2000prh.googlegroups.com> Message-ID: zunbeltz at gmail.com wrote: > I have to print float numbers to a file. Each float should be 5 > characters in width (4 numbers and the decimal point). > My problem is that I do not now how to specify float to have different > numbers of decimals. For example > > 5.32 -> 5.320 > 10.356634 -> 10.357 > 289.234 -> 289.2 > > In the string formating operations only fixed number of decimal digits > is allow. >>> ["%#.4g" % f for f in [5.32, 10.356634, 289.234, 123456789.]] ['5.320', '10.36', '289.2', '1.235e+08'] Found by playing around with format strings, so no guarantees. Peter From gagsl-py2 at yahoo.com.ar Wed Aug 22 10:58:24 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 22 Aug 2007 07:58:24 -0700 Subject: subprocess (spawned by os.system) inherits open TCP/UDP/IP port In-Reply-To: <1187742603.908139.311350@j4g2000prf.googlegroups.com> References: <1187742603.908139.311350@j4g2000prf.googlegroups.com> Message-ID: <1187794704.599878.229850@j4g2000prf.googlegroups.com> On 21 ago, 21:30, Seun Osewa wrote: > Is it possible to cause this sort of thing to happen on Windows. > Specifically, I'm looking for a way to cause multiple processes to > accept new connections on a bound socket. on UNIX, I can just fork() > after binding the server socket to a port and the children can > accept() on that same socket, but on Windows, I don't know how to make > that work. Any ideas? Thanks! Sockets are inherited by default, at least on any more-or-less-recent Windows version (that is, not on Win9x). There is a specific Winsock function (WSADuplicateSocket) and you can use the generic DuplicateHandle too with bInheritHandle=TRUE. Read about this on Microsoft site Note: Better to post a NEW message instead of replying to this old thread. -- Gabriel Genellina From david at asdf.asdf Thu Aug 30 21:19:15 2007 From: david at asdf.asdf (bambam) Date: Fri, 31 Aug 2007 11:19:15 +1000 Subject: beginner, idomatic python 2 References: <13csjmeaoqh9le3@corp.supernews.com> <1187927388.173203.298660@e9g2000prf.googlegroups.com> <13d4jfjfogbvq6f@corp.supernews.com> <46d2ba7a$0$430$426a74cc@news.free.fr> Message-ID: <13der4jquo987d1@corp.supernews.com> "Bruno Desthuilliers" wrote in message news:46d2ba7a$0$430$426a74cc at news.free.fr... > > As a side note, in Python, inheritance ... > ... should usually not be used for typing. :~( I'm sorry, I don't even know what that means... The code I have inherited from someone only a little more knowledgeable than me, and is still full of development artifacts anyway. The Pwr and Psp classes inherit from the Device class not neccessarily because that is a Good Thing, more because the development process led to them being thought of that way. All devices have a mixture of common and differing attributes. What is 'typing'? Steve. From dale at riverhall.nospam.co.uk Wed Aug 1 06:56:22 2007 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Wed, 01 Aug 2007 11:56:22 +0100 Subject: MIMEText breaking the rules? Message-ID: The email module's mimetext handling isn't what you might expect from something that appears to behave like a dictionary. $ python Python 2.5 (r25:51908, May 25 2007, 16:14:04) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from email.mime.text import MIMEText >>> msg = MIMEText("A message") >>> msg["To"] = "recipient at myhost.com" >>> msg["To"] = "other_recipient at myhost.com" >>> print msg.as_string() Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit To: recipient at myhost.com To: other_recipient at myhost.com A message >>> Having apparently REPLACED my recipient, what I've ended up with is both of them. -- Dale Strickland-Clark Riverhall Systems - www.riverhall.co.uk From ptmcg at austin.rr.com Sun Aug 26 23:26:32 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 26 Aug 2007 20:26:32 -0700 Subject: Parser Generator? In-Reply-To: References: <1188159150.755231.239390@o80g2000hse.googlegroups.com> Message-ID: <1188185192.735485.237740@57g2000hsv.googlegroups.com> On Aug 26, 8:05 pm, "Ryan Ginstrom" wrote: > > On Behalf Of Jason Evans > > Parsers typically deal with tokens rather than individual > > characters, so the scanner that creates the tokens is the > > main thing that Unicode matters to. I have written > > Unicode-aware scanners for use with Parsing-based parsers, > > with no problems. This is pretty easy to do, since Python > > has built-in support for Unicode strings. > > The only caveat being that since Chinese and Japanese scripts don't > typically delimit "words" with spaces, I think you'd have to pass the text > through a tokenizer (like ChaSen for Japanese) before using PyParsing. > > Regards, > Ryan Ginstrom Did you think pyparsing is so mundane as to require spaces between tokens? Pyparsing has been doing this type of token-recognition since Day 1. Looking for tokens without delimiting spaces was one of the first applications for pyparsing. This issue is not unique to Chinese or Japanese text. Pyparsing will easily find the tokens in this string: y=a*x**2+b*x+c as ['y','=','a','*','x','**','2','+','b','*','x','+','c'] even though there is not a single delimiting space. But pyparsing will also render this as a nested parse tree, reflecting the precedence of operations: ['y', '=', [['a', '*', ['x', '**', 2]], '+',['b', '*', 'x'], '+', 'c']] and will allow you to access individual tokens by field name: - lhs: y - rhs: [['a', '*', ['x', '**', 2]], '+', ['b', '*', 'x'], '+', 'c'] Please feel free to look through the posted examples on the pyparsing wiki at http://pyparsing.wikispaces.com/Examples, or some of the applications currently using pyparsing at http://pyparsing.wikispaces.com/WhosUsingPyparsing, and you might get a better feel for what kind of tasks pyparsing is capable of. -- Paul From david at asdf.asdf Sun Aug 26 23:18:14 2007 From: david at asdf.asdf (bambam) Date: Mon, 27 Aug 2007 13:18:14 +1000 Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com><1187898049.734696.9500@l22g2000prc.googlegroups.com><13csoronscqp7d2@corp.supernews.com><1188090322.663217.102750@22g2000hsm.googlegroups.com><13d4bucfm4m1lc4@corp.supernews.com> Message-ID: <13d4gjm3qq0lt7c@corp.supernews.com> Thank you, I have been through the tutorial several times, I guess I'm just not smart enough. Perhaps I have been led astray by what I read here? My code started like this: for i in range(self.parent.GetPageCount()): I was asked: >Does page count change? i.e. is it necessary to retrieve it in every loop Is self.parent.GetPageCount() 'retrieved every loop'? Steve. "Gabriel Genellina" wrote in message news:mailman.13.1188182594.28954.python-list at python.org... > En Sun, 26 Aug 2007 22:58:35 -0300, bambam escribi?: > >> Ok, many environments are capable of cached evaluation >> of functions without variable parameters so >> range(5) >> is cached, but >> range(v) is re-evaluated every time. Is this defined >> behaviour? > > The range builtin function returns a list, and lists are mutable objects, > so it must return a *different* list each time. > >> That is, is it defined what Python does for >> for i in f() >> I'm sure it must be, but I haven't seen it yet. If I have >> a user defined function returning a range, is it defined >> that the range function is called on every loop? If I >> have a function returning a range taking a parameter, >> for i in f(v) >> is it defined that the variable is evaluated for every loop? > > Find all the (mostly negative) answers yourself in > > > -- > Gabriel Genellina > From DustanGroups at gmail.com Tue Aug 28 07:24:44 2007 From: DustanGroups at gmail.com (Dustan) Date: Tue, 28 Aug 2007 11:24:44 -0000 Subject: Let's Unite Against Jews and Mongrels! In-Reply-To: <1188198797.772672.60840@r29g2000hsg.googlegroups.com> References: <1188198797.772672.60840@r29g2000hsg.googlegroups.com> Message-ID: <1188300284.507909.126770@57g2000hsv.googlegroups.com> On Aug 27, 2:13 am, Nenad Milicevic - The Aryan Serb wrote: > Let's break the chains of Jewish and black domination! A) Why? B) What chains? From mensanator at aol.com Sun Aug 5 13:40:56 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sun, 05 Aug 2007 10:40:56 -0700 Subject: Formatting Results so that They Can be Nicely Imported into a Spreadsheet. In-Reply-To: <1186304814.129279.207100@j4g2000prf.googlegroups.com> References: <1186270555.514649.311280@d30g2000prg.googlegroups.com> <1186278638.931477.39760@z24g2000prh.googlegroups.com> <1186284359.668342.5880@d30g2000prg.googlegroups.com> <1186304814.129279.207100@j4g2000prf.googlegroups.com> Message-ID: <1186335656.977681.284240@z24g2000prh.googlegroups.com> On Aug 5, 4:06?am, SMERSH009 wrote: > On Aug 4, 8:25 pm, "mensana... at aol.com" wrote: > > > > > > > On Aug 4, 9:21?pm, "Jim Langston" wrote: > > > > wrote in message > > > >news:1186278638.931477.39760 at z24g2000prh.googlegroups.com... > > > > > On Aug 4, 6:35?pm, SMERSH009 wrote: > > > >> Hi All. > > > >> Let's say I have some badly formatted text called doc: > > > > >> doc= > > > >> """ > > > >> friendid > > > >> Female > > > > >> 23 years old > > > > >> Los Gatos > > > > >> United States > > > >> friendid > > > >> Male > > > > >> 24 years old > > > > >> San Francisco, California > > > > >> United States > > > >> """ > > > > >> How would I get these results to be displayed in a format similar to: > > > >> friendid;Female;23 years old;Los Gatos;United States > > > >> friendid;Male; 24 years old;San Francisco, California;United States > > > > >> The latter is a lot easier to organize and can be quickly imported > > > >> into Excel's column format. > > > > >> Thanks Much, > > > >> Sam > > > > > d = doc.split('\n') > > > > > f = [i.split() for i in d if i] > > > > > g = [' '.join(i) for i in f] > > > > > rec = [] > > > > temprec = [] > > > > for i in g: > > > > if i: > > > > if i == 'friendid': > > > > rec.append(temprec) > > > > temprec = [i] > > > > else: > > > > temprec.append(i) > > > > rec.append(temprec) > > > > > output = [';'.join(i) for i in rec if i] > > > > > for i in output: print i > > > > > ## friendid;Female;23 years old;Los Gatos;United States > > > > ## friendid;Male;24 years old;San Francisco, California;United States > > > > also, I would suggest you use CSV format. > > > Well, the OP asked for a specific format. One is not > > always at liberty to change it. > > > > CSV stands for "Comma Seperated > > > Variable" and Excel can load such a sheet directly. > > > And Excel can load the shown format directly also, > > just specify the delimiter. > > > > Instead of seperating using ; seperate using , Of course, this provides a > > > problem when there is a , in a string. > > > Which explains the popularity of using tabs as delimiters. > > The data deliverable specification I use at work > > uses the pipe character | which never appears as data > > in this particular application. > > > > Resolution is to quote the string. > > > Which makes the file bigger and isn't necessary > > when tabs and pipes are used as delimiters. > > > > Being such, you can just go ahead and quote all strings. So you would want > > > the output to be: > > > > "friendid","Female","23 years old","Los Gatos","United States" > > > "friendid","Male","24 years old","San Francisco, California","United States" > > > Which I would do if I had a specification that > > demanded it or was making files for others. For my > > own use, I wouldn't bother as it's unnecessary work. > > > > Numbers should not be quoted if you wish to treat them as numeric and not > > > text. > > > A good reason not to use quotes at all. Besides which, > > Excel can handle that also. > > Thanks for all your posts guys. > mensanator's was the most helpful, and I only ended up needing to use > a few lines from that code. > The only question that remains for me--and this is just for my > knowledge-- what does the "if i" mean in this code snippet? > f = [i.split() for i in d if i] d is a list of strings, some of which are empty (caused by the previous split). "if i" evaluates False for an empty string, so that particular i will not get split and ends up ommitted from f. > How is it helpful to leave a dangling "if i"? Why not just f = > [i.split() for i in d]? Compare the result of having "if i": [[], ['friendid'], ['Female'], ['23', 'years', 'old'], ['Los', 'Gatos'], ['United', 'States'], ['friendid'], ['Male'], ['24', 'years', 'old'], ['San', 'Francisco,', 'California'], ['United', 'States']] to not having it: >>> ff = [i.split() for i in d] >>> ff [[], ['friendid'], ['Female'], [], [], ['23', 'years', 'old'], [], [], ['Los', 'Gatos'], [], [], ['United', 'States'], ['friendid'], ['Male'], [], [], ['24', 'years', 'old'], [], [], ['San', 'Francisco,', 'California'], [], [], ['United', 'States'], []] All the blank lines became empty lists which actually wouldn't change anything if they get joined. But that won't always be the case. Knowing how to use conditionals in list comprehensions is worth knowing. Even with the "if i" included, we end up with an empty list at the start. This because the first "blank" line wasn't blank, it was a space, so it passes the "if i" test. > > And yes John, this was indeed a "homework question." It was for my > daughter's preschool. You are going to help her ace her beginner > Python class! (No, this was not a homework question). From gtcopeland at gmail.com Tue Aug 21 21:01:09 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: Tue, 21 Aug 2007 18:01:09 -0700 Subject: Fast socket write Message-ID: <1187744469.240933.149610@r23g2000prd.googlegroups.com> I'm having a brain cramp right now. I can't see to recall the name of a module. I know there is a python module which allows for optimized socket writes on Linux. It uses a syscall to obtain its benefit. IIRC, it is a fast path for I/O bound servers. Can someone please refresh my memory? What is the name of this module?? Help, Greg From deets at nospam.web.de Thu Aug 2 15:16:04 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 02 Aug 2007 21:16:04 +0200 Subject: python 3.0, pywin32 and scipy In-Reply-To: <1186070475.659511.24130@q3g2000prf.googlegroups.com> References: <1186070475.659511.24130@q3g2000prf.googlegroups.com> Message-ID: <5heos0F3jael1U1@mid.uni-berlin.de> vml schrieb: > Hello, > > > I am trying to promote python in my job, my collegue only see matlab > and microsoft scripting language. > I understood that there willl be no backward compatibility between > python 2.x and 3.0, does it means that: > > - my script using pywin32 for the COM layer and scipy for the maths > won't work under 3.0 If the win32-extensions are made available (which I think is to be expected - they are too important to not being ported), I fail to see what COM-dependend code you expect to fail - after all, it's the COM-based APIs that are to be questioned there. > - will we have the equivalent of pywin32 and scipy in python ? Again, I think so - but of course I don't know for sure. But they both are to important. > I will be incharge of designing a python module which will be a > 'matrix calculator' in our current software. Will it be compatible > with python 3.0 ? I guess no. Even if not - why do you care? Is your C# 1 code being ported to C# 2 immediately? Are you preparing for C# three? > What can I answer to my collegue who will say 'Python is changing and > the stuff you are doing now is useless'? > > how can I argue against matlab and c# ? You mean C#, the language that has seen 3 major revisions in the last 6 years of existence, with C# 3 being announced already? And the .NET SDK, that happily strode along with that? Compared to python, that has been started in 1991 and now approaches it's third incarnation, I'd say python has a record of steadiness that surpasses that of MS-based tools by any means. Diez From ladaan at iptel.org Wed Aug 8 11:50:39 2007 From: ladaan at iptel.org (Ladislav Andel) Date: Wed, 08 Aug 2007 17:50:39 +0200 Subject: twisted - locking threads when deferToThread is used In-Reply-To: <4866bea60708080710ma83a713p622c2997df812a6a@mail.gmail.com> References: <46B99CCB.1070304@iptel.org> <4866bea60708080709v797c5a67w158f6f988ef5c304@mail.gmail.com> <4866bea60708080710ma83a713p622c2997df812a6a@mail.gmail.com> Message-ID: <46B9E64F.5010702@iptel.org> Chris Mellon wrote: > On 8/8/07, Chris Mellon wrote: > >> On 8/8/07, Ladislav Andel wrote: >> >>> Hi, >>> I'm writing an application which will be periodically testing servers. >>> I will have a global list of these servers(domain names) and need to do >>> few tasks. >>> 1) DNS checks - I will use asynchronous twisted-names for it >>> - in case there is a difference comparing to the list it should update >>> the list(then also in DB) >>> 2) ICMP pings - should be also possible to do it asynchronously >>> 3) Blocking function which will be pinging with SIP requests >>> - here I will use function deferToThread to make it non-blocking. >>> >>> Questions: >>> 1) How do I lock each thread when writing to a global list in twisted? >>> 2) How will I put together all three results mentioned above in the >>> global list >>> - is it by using function callLater ? >>> 3) Could you help me with a rough skeleton of this application, please? >>> >>> Thank you, >>> Lada >>> >>> >> deferToThread returns the result of the passed function in a Deferred. >> Callbacks and errbacks will be run in the main event loop, so you >> don't need to worry about thread safety of the callbacks, just of the >> function itself. >> >> The basic model would look something like this: >> >> def querySIP(what): >> return sip.query(what) #native, *threadsafe*, blocking call >> >> sipquery = reactor.deferToThread(querySIP, what) >> sipquery.addCallback(lambda result: sip_results.append(result)) >> sipquery.addErrback(log.err) >> >> > > > And, of course, deferToThread is a function in the > twisted.internet.threads module, not a method of the reactor. > Thanks for your answer. I have following code below. There are few problems. 1) I need to call getServerResponse of SIP servers for given list domains periodically. I have tried to use callLater method but probably at wrong places. 2) In my code is somthing wrong. I get the response but also following error Traceback (most recent call last): File "/home/data/iptel_summer_2007/sipcraft1/src/sipcraft/multideferred.py", line 46, in ? reactor.run() File "/usr/lib/python2.4/site-packages/twisted/internet/posixbase.py", line 220, in run self.mainLoop() File "/usr/lib/python2.4/site-packages/twisted/internet/posixbase.py", line 228, in mainLoop self.runUntilCurrent() --- --- File "/usr/lib/python2.4/site-packages/twisted/internet/base.py", line 533, in runUntilCurrent f(*a, **kw) File "/usr/lib/python2.4/site-packages/twisted/internet/defer.py", line 239, in callback self._startRunCallbacks(result) File "/usr/lib/python2.4/site-packages/twisted/internet/defer.py", line 290, in _startRunCallbacks raise AlreadyCalledError twisted.internet.defer.AlreadyCalledError: From nospam at nospam.com Fri Aug 10 00:45:04 2007 From: nospam at nospam.com (Mark T) Date: Thu, 9 Aug 2007 21:45:04 -0700 Subject: Threaded Design Question References: <1186683909.797328.68770@i13g2000prf.googlegroups.com> Message-ID: wrote in message news:1186683909.797328.68770 at i13g2000prf.googlegroups.com... > Hi all! I'm implementing one of my first multithreaded apps, and have > gotten to a point where I think I'm going off track from a standard > idiom. Wondering if anyone can point me in the right direction. > > The script will run as a daemon and watch a given directory for new > files. Once it determines that a file has finished moving into the > watch folder, it will kick off a process on one of the files. Several > of these could be running at any given time up to a max number of > threads. > > Here's how I have it designed so far. The main thread starts a > Watch(threading.Thread) class that loops and searches a directory for > files. It has been passed a Queue.Queue() object (watch_queue), and > as it finds new files in the watch folder, it adds the file name to > the queue. > > The main thread then grabs an item off the watch_queue, and kicks off > processing on that file using another class Worker(threading.thread). > > My problem is with communicating between the threads as to which files > are currently processing, or are already present in the watch_queue so > that the Watch thread does not continuously add unneeded files to the > watch_queue to be processed. For example...Watch() finds a file to be > processed and adds it to the queue. The main thread sees the file on > the queue and pops it off and begins processing. Now the file has > been removed from the watch_queue, and Watch() thread has no way of > knowing that the other Worker() thread is processing it, and shouldn't > pick it up again. So it will see the file as new and add it to the > queue again. PS.. The file is deleted from the watch folder after it > has finished processing, so that's how i'll know which files to > process in the long term. > > I made definite progress by creating two queues...watch_queue and > processing_queue, and then used lists within the classes to store the > state of which files are processing/watched. > > I think I could pull it off, but it has got very confusing quickly, > trying to keep each thread's list and the queue always in sync with > one another. The easiset solution I can see is if my threads could > read an item from the queue without removing it from the queue and > only remove it when I tell it to. Then the Watch() thread could then > just follow what items are on the watch_queue to know what files to > add, and then the Worker() thread could intentionally remove the item > from the watch_queue once it has finished processing it. > > Now that I'm writing this out, I see a solution by over-riding or > wrapping Queue.Queue().get() to give me the behavior I mention above. > > I've noticed .join() and .task_done(), but I'm not sure of how to use > them properly. Any suggestions would be greatly appreciated. > > ~Sean > Just rename the file. We've used that technique in a similar application at my work for years where a service looks for files of a particular extension to appear in a directory. When the service sees a file, in renames it to a different extension and spins off a thread to process the contents. -Mark T. From sean at buildingonline.com Fri Aug 31 10:52:48 2007 From: sean at buildingonline.com (sberry) Date: Fri, 31 Aug 2007 07:52:48 -0700 Subject: Question involving a Python app... Message-ID: <1188571968.529938.55770@i38g2000prf.googlegroups.com> I am a Flash developer (also a Python dev) and I use an editor called SEPY Actionscript Editor. The latest release version does not support Flash CS3, so I downloaded the source from subversion, edited it, and recompiled to get a version that worked with CS3. Right now, in order to run the program I have to do a command line "python main.pyw." The question now is this: Others in my company would like to use the version I have compiled without installing Python, wxPython, 4suite, antlr, and a whole bunch of other Python libs. So, how do I create an executable (on Windows) to install the program so it will run without the aforementioned framework being installed? I know this isn't really an entirely "Pythonic" question, but this group has always been very helpful in the past. Thanks From ed at leafe.com Fri Aug 24 11:33:12 2007 From: ed at leafe.com (Ed Leafe) Date: Fri, 24 Aug 2007 11:33:12 -0400 Subject: creating a tar file with python In-Reply-To: <1187969070.3385.20.camel@dot.uniqsys.com> References: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> <93066C069973ED448DC2BCEA9C44A7383BE2ED@efmailx> <46CE4D3D.7020106@holdenweb.com> <93066C069973ED448DC2BCEA9C44A7383BE2EE@efmailx> <1187969070.3385.20.camel@dot.uniqsys.com> Message-ID: <0A8A92C4-3F3A-42C4-A6F5-770C5ADFB6E5@leafe.com> On Aug 24, 2007, at 11:24 AM, Carsten Haese wrote: > You clearly have no idea who you're talking to. I suggest you > Google for > '"Steve Holden" Python' to get a clue. Good luck finding any more help > here. Even if it were Joe Nobody to whom he was directing those comments, it was *way* out of line. The fact that it was Steve only reinforces the cluelessness of the writer. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From kyosohma at gmail.com Thu Aug 2 09:38:39 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 02 Aug 2007 13:38:39 -0000 Subject: Python end of file marker similar to perl's __END__ In-Reply-To: References: <1185940391.135261.130950@i38g2000prf.googlegroups.com> <1185976656.753817.27980@x40g2000prg.googlegroups.com> Message-ID: <1186061919.007689.197670@g12g2000prg.googlegroups.com> On Aug 2, 8:08 am, Neil Cerutti wrote: > On 2007-08-02, Magnus Lycka wrote: > > > > > Neil Cerutti wrote: > >> On 2007-08-01, Cameron Laird wrote: . > >>> I want to re-emphasize the "triple-quote it" tip mentioned > >>> earlier in this thread. I think the original questioner > >>> will find this quite satisfying, if I understand his situ- > >>> ation at all. > > >>> *I* certainly have source code with embedded "junk" > >>> commented out as multi-line strings. > > >> I used to do that, but now that I use doctests so much it's > >> infeasible to comment out arbitrary code that way, since they > >> can't necessarily nest. > > > If you consistently use e.g. ''' for doc strings, you can use > > """ to comment out code blocks. > > But then I couldn't use """ in my docstrings! ;) Actually, I > wound up converting all my multiline doctests to use > concatenation instead, since they were ruining my syntax > highlighting performance in Vim. > > -- > Neil Cerutti > We shall reach greater and greater platitudes of achievement. --Richard J. > Daley Python comes with an IDE that can do bulk commenting or uncommenting. It's IDLE. Just select the test to comment out and press ALT+3. To uncomment, press ALT+4. It's cool! Mike From mbrown at phys.ksu.edu Wed Aug 22 17:59:09 2007 From: mbrown at phys.ksu.edu (yagyala) Date: Wed, 22 Aug 2007 14:59:09 -0700 Subject: introspection and functions Message-ID: <1187819949.515982.15450@r23g2000prd.googlegroups.com> Hi. I would like to be able to tell, at run time, how many parameters a function requires. Ideally I would like to be able to tell which are optional as well. I've tried looking at the functions attributes, but haven't found one that helps in this. How can I do this? Thanks From michele.simionato at gmail.com Sun Aug 12 01:04:44 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 11 Aug 2007 22:04:44 -0700 Subject: is there anybody using __del__ correctly?? In-Reply-To: References: <1186731369.073644.158490@z24g2000prh.googlegroups.com> <1186762908.121319.35900@x35g2000prf.googlegroups.com> Message-ID: <1186895084.388293.295330@57g2000hsv.googlegroups.com> On Aug 10, 7:09 pm, Steven Bethard wrote: > There were also a few recipes posted during this discussion that wrap > weakrefs up a bit nicer so it's easier to use them in place of __del__: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/519635 I knew about your recipe and I thought it was clever, *very* clever. I have been thinking about it a bit more today and here is an alternative, which does not require metaclasses, does not require descriptors, and does not require the user to declare the attributes she will use in the __finalize__ method. Warning: it is no more tested than the test case in your recipe: import weakref _get = object.__getattribute__ _set = object.__setattr__ _del = object.__delattr__ def getinnerobj(self): return _get(self, '*innerobj*') class Impostor(object): "It tries very hard to impersonate the inner object" def __init__(self, obj): _set(self, '*innerobj*', obj) def __getattribute__(self, name): return getattr(getinnerobj(self), name) def __setattr__(self, name, value): _set(getinnerobj(self), name, value) def __delattr__(self, name): _del(getinnerobj(self), name) _refset = set() class Finalized(object): def __new__(cls, *args, **kw): self = super(Finalized, cls).__new__(cls, *args, **kw) self.__init__(*args, **kw) def finalize(ref, refset=_refset): refset.remove(ref) cls.__finalize__(self) fake = Impostor(self) _refset.add(weakref.ref(fake, finalize)) return fake def __finalize__(self): pass Hope you will enjoy it, Michele Simionato From XX.XmcX at XX.XmclaveauX.com Fri Aug 31 15:32:40 2007 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Fri, 31 Aug 2007 21:32:40 +0200 Subject: JavaScript References: <1188574962.185775.274420@d55g2000hsg.googlegroups.com> Message-ID: Hi! I know "how to", but only with IE on windows. -- @-salutations Michel Claveau From jcd at sdf.lonestar.org Fri Aug 24 14:51:28 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 24 Aug 2007 14:51:28 -0400 Subject: Using Regular Expresions to change .htm to .php in files In-Reply-To: <424c8c5b0708241102q19fc19cape28c1e434994ebd5@mail.gmail.com> References: <9afea2ac0708231305v539390dew84926f0b0dcd6974@mail.gmail.com> <46CF1437.9020200@sdf.lonestar.org> <424c8c5b0708241102q19fc19cape28c1e434994ebd5@mail.gmail.com> Message-ID: <46CF28B0.10009@sdf.lonestar.org> I'd actually skip checking where the links are coming from, and just pretend any link could be .htm or .html. Check for both cases, either using a regex or just fix the .html cases first. So do 2 passes. Pass 1: Data.replace('.html', '.php') Pass 2: Data.replace('.htm','.php') I make no claims about what the surrounding code should look like. You've gotten a number of responses on that already. Cheers, Cliff S?bastien N wrote: > It's a fact, but still I went on with the solution that overwrites all > the .htm because it's a really big site and about 70-80% of the links > are internal so we'll save time this way. > > There's probably a way to analyse if a link is internal or external, > but I needed something fast. But still, I would be interested about > knowing how to do such a thing for the future. > > On 8/24/07, J. Cliff Dyer wrote: > >> Tim Williams wrote: >> On 23/08/07, sebzzz at gmail.com wrote: >> >> >> Hi, >> >> I have a bunch of files that have changed from standard htm files to >> php files but all the links inside the site are now broken because >> they point to the .htm files while they are now .php files. >> >> Does anyone have an idea about how to do a simple script that changes >> each .htm in a given file to a .php >> >> Thanks a lot in advance >> >> >> Something like: >> >> Infile = open(f_name,'r+') >> Data = Infile.read() >> InFile.write(Data.replace('.htm','.php')) >> Infile.close() >> >> :) >> >> Yeah, but you'd better make darn sure that *all* links point to .htm files >> (including external links), because you could very easily end up pointing to >> http://some.othersite.com/index.phpl >> >> And that's just no good. >> >> >> > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stanc at al.com.au Mon Aug 13 06:01:30 2007 From: stanc at al.com.au (Astan Chee) Date: Mon, 13 Aug 2007 20:01:30 +1000 Subject: check if var is dict Message-ID: <46C02BFA.10703@al.com.au> Hi, I have a variable, I want to check if it is a dictionary or a string. Is there any better way to do this than I've done. How I did it is by doing a .items() and catching a AttributeError that it raises if its not a dictionary. How do i properly do it? Thanks Astan From aleax at mac.com Mon Aug 27 00:56:19 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 26 Aug 2007 21:56:19 -0700 Subject: ANN: SCF released GPL References: <2qnAi.21495$eY.19028@newssvr13.news.prodigy.net> Message-ID: <1i3h3ki.1poi7cm865i17N%aleax@mac.com> hg wrote: ... > I am looking for a free subversion server resource to put the code ... > if you know of any. Check out code.google.com -- it has a hosting service for open source code, too, these days (and it IS subversion). Alex From newsgroups at debain.org Sun Aug 19 09:08:35 2007 From: newsgroups at debain.org (Samuel) Date: Sun, 19 Aug 2007 13:08:35 +0000 (UTC) Subject: Hot subject: a good python editor and/or IDE? References: Message-ID: On Sun, 19 Aug 2007 11:47:03 +0200, S?bastien wrote: > Hi folks, > > I am currently using Eclipse+PyDev when developping Python projects but > I lack a fast, simple editor for tiny bit of scripts. So here is my > question: what is, for you, the current best ( but still kind of light! > ) Python editor/IDE ? A tiny precision, I am on Ubuntu so I am looking > for a linux compatible editor. Vim with SnippetsEMU works great with Python. I made a demo of this in action here: http://debain.org/?p=198 Installation/configuration example on Ubuntu: --------------- $ sudo apt-get install vim $ mkdir -p $HOME/.vim/ftplugin/ $ mkdir -p $HOME/.vim/after/ftplugin/ $ wget http://www.vim.org/scripts/download_script.php?src_id=6951 -O se.vba $ vim se.vba :so % :wq $ echo "setlocal sw=4 setlocal ts=4 noremap py o/**************/ " >> ~/.vim/ftplugin/python.vim $ wget http://code.google.com/p/snippetsemu/issues/attachment?aid=-6063627743376712928&name=python_snippets.vim $ cp python_snippets.vim $HOME/.vim/after/ftplugin/ $ echo "syntax on set sw=2 set ts=2 set nu set nuw=3 set autoindent set expandtab" >> $HOME/.vimrc --------------- (not tested, but it should work) -Samuel From jzgoda at o2.usun.pl Thu Aug 2 15:25:49 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 02 Aug 2007 21:25:49 +0200 Subject: Determining if file is valid image file In-Reply-To: <1186065645.879720.27720@q75g2000hsh.googlegroups.com> References: <1186064098.587590.91210@g4g2000hsf.googlegroups.com> <1186064275.652416.250540@d55g2000hsg.googlegroups.com> <1186065645.879720.27720@q75g2000hsh.googlegroups.com> Message-ID: Andr? napisa?(a): >>>> Other than installing PIL, is there a "simple" way using Python only >>>> to determine if a file is a valid image file? >>>> I'd be happy if I could at least identify valid images files for gif, >>>> jpeg and png. Pointers to existing modules or examples would be >>>> appreciated. >>>> The reason why I'd prefer not using PIL is that I'd like to bundle >>>> such a function/module in my app. >>>> Andr? >>> I should have added: I'm interesting in validating the file *content* >>> - not the filename :-) >> Is the module imghdr enough for your needs? > > Yes, thanks. Be aware that broken images (i.e. partially downloaded) in many cases pass the imghdr.what() test. This function checks for patterns in files, just like "file" utility. -- Jarek Zgoda http://jpa.berlios.de/ From steve at holdenweb.com Tue Aug 7 02:35:59 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 07 Aug 2007 02:35:59 -0400 Subject: Relative-importing * In-Reply-To: <5hqhb9F3ldifeU2@mid.uni-berlin.de> References: <1185559874.299008.167010@x40g2000prg.googlegroups.com> <871weth2gg.fsf@benfinney.id.au> <46ae3894$0$19609$426a34cc@news.free.fr> <1186200218.666444.254200@q3g2000prf.googlegroups.com> <87vebv9yrr.fsf@benfinney.id.au> <1186363732.188847.48070@q3g2000prf.googlegroups.com> <87zm15870h.fsf@benfinney.id.au> <1186454723.425679.220510@q3g2000prf.googlegroups.com> <5hqhb9F3ldifeU2@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Tue, 07 Aug 2007 02:45:23 +0000, rbygscrsepda wrote: > >> Specifically, in Python 1.5, all of the following generate the error >> below: > > In Python *1.5*!? I somehow doubt that. ;-) > >> from . import * >> from .sibiling_package import * >> from .. import * >> from ..cousin_package import * >> >> SyntaxError: 'import *' not allowed with 'from .' >> >> Importing * is a feature, but this seems like an artificial >> inconsistency to me. It's as if the compiler raises an error when it >> tries to import * as soon as it sees "from .", regardless of what >> comes after it. So is this a bug in python? And if it happens to be a >> bug, how can I alert the developers of the python compiler? > > I'm just guessing here but as * imports are considered bad style the > developers might took the opportunity to forbid them in relative imports > because relative imports are new and this doesn't break old programs. > Yup, I searched around to find a specific statement of the reason but couldn't find anything definite. Of course, if you are writing a set of plugins then wildcard imports would seem like a train wreck waiting to happen in terms of the discipline required to avoid name collisions. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From DustanGroups at gmail.com Sat Aug 25 15:05:07 2007 From: DustanGroups at gmail.com (Dustan) Date: Sat, 25 Aug 2007 19:05:07 -0000 Subject: accessing keys in dict In-Reply-To: References: <1187143106.021325.104690@l22g2000prc.googlegroups.com> Message-ID: <1188068707.273263.200450@x35g2000prf.googlegroups.com> On Aug 25, 7:41 am, Lawrence D'Oliveiro wrote: > In message <1187143106.021325.104... at l22g2000prc.googlegroups.com>, > > james_027 wrote: > > is there any difference between .. > > > for key in a_dict: > > > from > > > for key in a_dict.keys(): > > I'm assuming the former is equivalent to > > for key in a_dict.iterkeys() : Never assume. A better approach would be to experiment: >>> a_dict = {'name':'apple', 'color':'red', 'texture':'smooth', 'shape':'sphere'} >>> for i in a_dict: print i color shape name texture >>> for i in a_dict.iterkeys(): print i color shape name texture >>> for i in a_dict.itervalues(): print i red sphere apple smooth >>> for i in a_dict.iteritems(): print i ('color', 'red') ('shape', 'sphere') ('name', 'apple') ('texture', 'smooth') From exarkun at divmod.com Thu Aug 23 13:31:05 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 23 Aug 2007 13:31:05 -0400 Subject: My 'time' module is broken, unsure of cause In-Reply-To: <200708231122.55588.bulliver@badcomputer.org> Message-ID: <20070823173105.8162.615504421.divmod.quotient.1142@ohm> On Thu, 23 Aug 2007 11:22:55 -0600, darren kirby wrote: >Hi all, > >I have a strange error here and I am unsure how to further investigate it: > >Python 2.4.4 (#1, Aug 23 2007, 10:51:29) >[GCC 4.1.2 (Gentoo 4.1.2)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> import time >40:42:0 >>>> now = time.time() >Traceback (most recent call last): > File "", line 1, in ? >AttributeError: 'module' object has no attribute 'time' > >Notice the '40:42:0' that always gets output. I searched Gentoo's bugzilla but >can not see anything relevant. I rebuilt python but the behavior recurs. I am >unsure if the issue is with Python, Gentoo, or perhaps with the underlying >lib (presumably glibc) that Python uses for the time module. This is working >fine on another machine (also 2.4.4, GCC 3.4.6, Gentoo Hardened). exarkun at charm:~$ echo "print '40:42:0'" > time.py exarkun at charm:~$ python Python 2.4.3 (#2, Oct 6 2006, 07:52:30) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time 40:42:0 >>> time.time() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'time' >>> print time.__file__ time.py >>> ^D exarkun at charm:~$ rm time.py exarkun at charm:~$ rm time.pyc exarkun at charm:~$ python Python 2.4.3 (#2, Oct 6 2006, 07:52:30) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.time() 1187890226.9293921 >>> print time.__file__ /usr/lib/python2.4/lib-dynload/time.so >>> Jean-Paul From semanticist at gmail.com Fri Aug 31 02:23:13 2007 From: semanticist at gmail.com (Miles) Date: Fri, 31 Aug 2007 02:23:13 -0400 Subject: fcntl problems In-Reply-To: <1188515889.352267.220790@q5g2000prf.googlegroups.com> References: <1188512377.441241.107900@q4g2000prc.googlegroups.com> <1188515889.352267.220790@q5g2000prf.googlegroups.com> Message-ID: Sorry, that last quote-only reply was accidental. :) On 8/30/07, mhearne808 wrote: > I've been doing some experiments, and here are some specific examples > to try. [snipped examples] > From these last two experiments I can only conclude that file locking > isn't doing a durned thing. > > What's going on? File locking isn't doing a durned thing in those cases because you're only obtaining the lock from a single process. > According to my Python Cookbook: > "Exclusive lock: This denies all _other_ processes both read and write > access to the file." This is only for mandatory locking; POSIX flock is advisory locking, which states: "Only one process may hold an exclusive lock for a given file at a given time." Advisory locks don't have any effect on processes that don't use locks. Mandatory locks are kernel enforced, but non-POSIX and not available in Mac OS X. -Miles From http Wed Aug 8 16:06:40 2007 From: http (Paul Rubin) Date: 08 Aug 2007 13:06:40 -0700 Subject: Misleading wikipedia article on Python 3? References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <7xzm15q8fy.fsf@ruckus.brouhaha.com> <41Dti.37401$G23.10727@newsreading01.news.tds.net> <1186582066.096793.14700@57g2000hsv.googlegroups.com> <1186600271.858692.182090@22g2000hsm.googlegroups.com> Message-ID: <7xmyx1bxkf.fsf@ruckus.brouhaha.com> Istvan Albert writes: > apply(), callable(), coerce(), file(), reduce(), reload() reduce() is really gone????? Maybe itertools can get an ireduce function or something like that? From bj_666 at gmx.net Mon Aug 6 03:12:02 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Aug 2007 07:12:02 GMT Subject: Something in the function tutorial confused me. References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> Message-ID: <5hnvu2F3kl28iU1@mid.uni-berlin.de> On Sun, 05 Aug 2007 23:50:24 -0700, Lee Fleming wrote: > But this, the code that "fixes" the list accumulation confounds me: > def f(x, y=None): > if y is None: y = [] > y.append(x) > return y > > print f(23) # prints [23] > print f(42) # prints [42] > > Why didn't the second call to f, f(42) return [23, 42]? > As I understand it, y is only None at the beginning of f(23). > Then y changes from None to 23. When f ends, doesn't y still have 23 > in it, just as it did in the first function I discussed? After the function's end, the name local name `y` doesn't exist anymore. If you enter a function, the names of the arguments with default values are bound to those default values. So in the second call `y` is bound to `None` just like in the first example `y` is bound to the list at every call. > In other words, what's going on here? How is it that y accumulates > argument values between function calls in the first function, but > doesn't in the second one? Not `y` is accumulating but the list object does. Ciao, Marc 'BlackJack' Rintsch From rcs at bgoark.no Sat Aug 18 18:05:27 2007 From: rcs at bgoark.no (baalbek) Date: Sun, 19 Aug 2007 00:05:27 +0200 Subject: Drawing a graph In-Reply-To: References: Message-ID: <46c76d29$0$7449$c83e3ef6@nn1-read.tele2.net> Ghirai wrote: > Hello list, > > I need to draw a graph, 2 axes, 2D, nothing fancy. > One of the axes is time, the other one is a series of integers. > > I don't care much about the output format. > > Are there any specialized libraries for this, or should i use PIL? > > Thanks. > Hey dude, why don't you just bite the bullet and implement your own plotting classes using wxPython? For your need (nothing fancy, as you said), relying on your own work is better, and making Python/wxPython plots is not really difficult. I myself have implemented a complete stock graphing application in Python using wxPython, including candlesticks and the works. In the long run, you will be better of relying on your own effort/understanding, believe me. Good luck! Baalbek From bignose+hates-spam at benfinney.id.au Mon Aug 6 05:27:01 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 06 Aug 2007 19:27:01 +1000 Subject: Global package variable, is it possible? References: <1186160415.065108.139160@e9g2000prf.googlegroups.com> <46b6d0b4$0$29273$426a74cc@news.free.fr> Message-ID: <87vebt813u.fsf@benfinney.id.au> Bruno Desthuilliers writes: > I've read all the thread, and it seems that your problem is mostly > to share a single dynamic state (the config) between several > modules. So I do wonder: have you considered the use of the > Singleton pattern (or one of it's variants...) ? Python modules are effectively singletons. So the idiomatic way to do this is to create a module for configuration (perhaps named 'config'), import that into every other module that needs it, and use its attributes. -- \ "[On the Internet,] power and control will shift to those who | `\ are actually contributing something useful rather than just | _o__) having lunch." -- Douglas Adams | Ben Finney From msherman77 at yahoo.com Mon Aug 13 19:11:05 2007 From: msherman77 at yahoo.com (Michael S) Date: Mon, 13 Aug 2007 19:11:05 -0400 (EDT) Subject: python & MS Office Message-ID: <585015.7924.qm@web88303.mail.re4.yahoo.com> http://msherman77.blogspot.com/2007/08/python-com.html From mensanator at aol.com Sun Aug 5 17:28:14 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sun, 05 Aug 2007 14:28:14 -0700 Subject: Google message munging (was: Live editing...) In-Reply-To: <7xwswfdiur.fsf@ruckus.brouhaha.com> References: <1185914335.472511.172040@m37g2000prh.googlegroups.com> <87r6moc4il.fsf@benfinney.id.au> <7xwswfdiur.fsf@ruckus.brouhaha.com> Message-ID: <1186349294.080749.171440@e16g2000pri.googlegroups.com> On Jul 31, 10:38?pm, Paul Rubin wrote: > Ben Finney writes: > > > [... more lines of broken line wrapping...] > > What the blazes is Google doing with messages that such a high > > proportion of them come through in this painful-to-read double-wrapped > > format? I'm referring to the fact that the lines appear to have been > > wrapped at one length, and then each line broken again into a long and > > a short line. > > Users write in a text editor formatting the text into lines of > reasonable size, separated by newline characters. They then paste the > text into a web form, which reformats it with slightly shorter lines > (breaking up the user's longer lines) but leaves the user's newlines > in place. Google used to provide a preview before actual posting, but that is no longer available, so there's nothing the poster can do about it. From manasd at gmail.com Fri Aug 10 08:54:03 2007 From: manasd at gmail.com (MD) Date: Fri, 10 Aug 2007 05:54:03 -0700 Subject: Does PyModule_GetDict return information about class method variables? In-Reply-To: <5i2c8rF3kqc46U1@mid.uni-berlin.de> References: <1186713277.019869.265820@d30g2000prg.googlegroups.com> <5i2c8rF3kqc46U1@mid.uni-berlin.de> Message-ID: <1186750443.773641.88450@i13g2000prf.googlegroups.com> Hi Marc, Thanks for your reply. I am calling my extension function from the class method itself. So at that point the variable does exist. I am puzzled why PyModule_GetDict is not able to access the variable even though it does exist at that point. Thanks, -Manas On Aug 10, 12:43 am, Marc 'BlackJack' Rintsch wrote: > On Thu, 09 Aug 2007 19:34:37 -0700, MD wrote: > > I have a variable which is defined inside a class method. When I > > call PyModule_GetDict on the module containing this class, the > > dictionary doesn't contain any information about this variable. Is > > this expected behavior? If so, what options do I have to access this > > variable from my Python C extension. > > You can't access names in methods because they don't exist until you call > the method. It's just like local variables in C. Consider: > > void foo(void) > { > int bar = 42; > > } > > Here `bar` does not exist until you call `foo()` and it disappears as soon > as the function returns. > > It's the very same situation in Python: > > class A(object): > def foo(self): > bar = 42 > > The local name `bar` only exists if `foo()` is called on an instance of `A`. > > Ciao, > Marc 'BlackJack' Rintsch From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Aug 14 06:37:17 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 14 Aug 2007 12:37:17 +0200 Subject: Assignments and Variable Substitution In-Reply-To: <1187085620.641516.269590@b79g2000hse.googlegroups.com> References: <1187085620.641516.269590@b79g2000hse.googlegroups.com> Message-ID: <46c185dd$0$408$426a74cc@news.free.fr> Ali a ?crit : > On Aug 14, 12:45 am, Steve Holden wrote: >> Evan Klitzke wrote: >>> On 8/13/07, brad wrote: >>>> I'd like to do something like this: >>>> var = '123' >>>> %s = [], %var > >> And why would you want a variable whose name is '123'? > > ... and thus continues the search for private variables in Python. I must be tired, but I don't see what this has to do with "private" variables. But if you want private variables, it's quite easy: prefix their names with a single underscore. From kw at codebykevin.com Wed Aug 8 12:34:35 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 08 Aug 2007 12:34:35 -0400 Subject: Tkinter or wxpython? In-Reply-To: References: <7xlkcopu4r.fsf@ruckus.brouhaha.com> <7x7io8r6na.fsf@ruckus.brouhaha.com> <46B9DE7B.3050909@codebykevin.com> Message-ID: <46B9F09B.2060903@codebykevin.com> Chris Mellon wrote: > On 8/8/07, Kevin Walzer wrote: > Using Tile, of course, loses you the first major benefit of Tk - that > it's already included in the standard library. So in this sense it's > still "ugly old school look and feel" vs "no external dependencies", > which is the swing decision for many people. People who prefer the Tk > API, of course, will be happy to use Tile. Tile has been implemented in the Tk core starting with version 8.5, still somewhere between alpha and beta stage. Once 8.5 is out, and Python is configured to build against Tk 8.5 (instead of 8.4), it should Just Work. > > Also, while you can get (mostly) native *look*, the feel is absent. > Unless I'm very uninformed, Tile is a theming engine only, and doesn't > implement platform conventions with regard to behavior (the "feel" > part of look and feel). What do you mean here? Things like keyboard accelerators, menu placement, and so on? Those things are already natively implemented by Tk, and the developer just needs to invoke them. Sometimes some conditional code is required for stuff like keyboard accelerators (the "tk windowingsytem" command is useful for this), but again, it should Just Work. Or am I missing something? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From ldo at geek-central.gen.new_zealand Sat Aug 25 08:46:45 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 26 Aug 2007 00:46:45 +1200 Subject: make images with python References: <1187147338.400947.181010@x40g2000prg.googlegroups.com> <1i2vg8p.1d8t42r1jzvm9iN%raims@dot.com> Message-ID: In message , Boris Borcic wrote: > Lawrence Oluyede wrote: > >> stefano wrote: >>> I need make some images using python but i'm lost :P >> >> >> > > If you want to do antialiased drawings into images, > you might rather want to look for pil at > > http://effbot.org/downloads/ > > and grab PIL together with the aggdraw extension > (while "core" PIL includes some drawing primitives, > last time I tried they weren't antialiased). I see that PIL supports image resizing with filters that can be used for antialiasing. So just do all your drawing at, say, 200% scale, then downsample with Image.resize to antialias. From n.marinov at sistechnology.com Thu Aug 9 09:21:43 2007 From: n.marinov at sistechnology.com (nikolay marinov) Date: Thu, 09 Aug 2007 16:21:43 +0300 Subject: tests Message-ID: <46BB14E7.6070104@sistechnology.com> Hi, everyone.Does anybody have an idea how can i test two xls files for equality with Python From deets at nospam.web.de Wed Aug 8 18:39:27 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 09 Aug 2007 00:39:27 +0200 Subject: help a n00b with a Zope site-package install In-Reply-To: <1186607528.256756.209030@i38g2000prf.googlegroups.com> References: <1186607528.256756.209030@i38g2000prf.googlegroups.com> Message-ID: <5huv0vF3m9ju9U1@mid.uni-berlin.de> sdoty044 at gmail.com schrieb: > I am having a general problem getting Zope installed as part of my > linux distro. We have a general problem solving problems that lack any concrete description of what is not working. We need stacktraces and so forth. Maybe reading this helps: http://catb.org/~esr/faqs/smart-questions.html Diez From kyosohma at gmail.com Thu Aug 2 10:38:06 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 02 Aug 2007 14:38:06 -0000 Subject: Determining if file is valid image file In-Reply-To: References: <1186064098.587590.91210@g4g2000hsf.googlegroups.com> <1186064275.652416.250540@d55g2000hsg.googlegroups.com> Message-ID: <1186065486.645871.175590@m37g2000prh.googlegroups.com> On Aug 2, 9:35 am, Thomas Jollans wrote: > On Thursday 02 August 2007, Andr? wrote: > > > On Aug 2, 11:14 am, Andr? wrote: > > > Other than installing PIL, is there a "simple" way using Python only > > > to determine if a file is a valid image file? > > > > I'd be happy if I could at least identify valid images files for gif, > > > jpeg and png. Pointers to existing modules or examples would be > > > appreciated. > > > > The reason why I'd prefer not using PIL is that I'd like to bundle > > > such a function/module in my app. > > > I should have added: I'm interesting in validating the file *content* > > - not the filename :-) > > The file name has nothing to do with the type :-P > > A straightforward way you won't like: read the specs for all formats you're > interested in and write the function yourself ;-) Use the md5 module to create checksums. Links below: http://www.peterbe.com/plog/using-md5-to-check-equality-between-files http://effbot.org/librarybook/md5.htm http://docs.python.org/lib/module-md5.html Larry is right too...what's wrong with bundling PIL or any third party module? Mike From vdicarlo at gmail.com Wed Aug 22 12:07:06 2007 From: vdicarlo at gmail.com (vdicarlo) Date: Wed, 22 Aug 2007 09:07:06 -0700 Subject: IDE for Python In-Reply-To: <1187702024.675011.324020@q4g2000prc.googlegroups.com> References: <1187702024.675011.324020@q4g2000prc.googlegroups.com> Message-ID: <1187798826.436774.271590@x35g2000prf.googlegroups.com> > Have you tried SPE? I don't know how it compares to PyDev but SPE is > pretty slick. It has several other tools integrated into it, > including a pretty nice debugger. After trying Eclipse and SPE, I'm back to using VIM and the Winpdb debugger, which is the "pretty nice debugger" in SPE, and which has become indispensable to me. Vincent From ladaan at iptel.org Wed Aug 8 06:36:59 2007 From: ladaan at iptel.org (Ladislav Andel) Date: Wed, 08 Aug 2007 12:36:59 +0200 Subject: twisted - locking threads when deferToThread is used Message-ID: <46B99CCB.1070304@iptel.org> Hi, I'm writing an application which will be periodically testing servers. I will have a global list of these servers(domain names) and need to do few tasks. 1) DNS checks - I will use asynchronous twisted-names for it - in case there is a difference comparing to the list it should update the list(then also in DB) 2) ICMP pings - should be also possible to do it asynchronously 3) Blocking function which will be pinging with SIP requests - here I will use function deferToThread to make it non-blocking. Questions: 1) How do I lock each thread when writing to a global list in twisted? 2) How will I put together all three results mentioned above in the global list - is it by using function callLater ? 3) Could you help me with a rough skeleton of this application, please? Thank you, Lada From geoff.bache at pobox.com Tue Aug 28 09:59:50 2007 From: geoff.bache at pobox.com (geoffbache) Date: Tue, 28 Aug 2007 06:59:50 -0700 Subject: Getting subprocesses to be hidden on Windows In-Reply-To: <1188308231.196513.291260@19g2000hsx.googlegroups.com> References: <1188246076.131276.292010@r34g2000hsd.googlegroups.com> <1188250115.875160.276780@r29g2000hsg.googlegroups.com> <1188292102.065625.82670@22g2000hsm.googlegroups.com> <1188308231.196513.291260@19g2000hsx.googlegroups.com> Message-ID: <1188309590.114918.257670@y42g2000hsy.googlegroups.com> > Which GUI toolkit are you using? Tkinter, wxPython, pyQt? Primarily PyGTK, but I was hoping it wouldn't matter. I hope to be able to start the process as indicated in the original post from within my test tool and instruct the subprocess to be hidden (or minimized? would that be easier?), irrespective of what it was (it might be a Java GUI or anything for all I care...) > As for > losing the command window on Windows, the best way that I know of is > to just change the extension of the python file itself from *.py to > *.pyw . I'm pretty sure you can suppress command windows if you're > calling them from the command line using a flag, but I can't recall > the flag off the top of my head. > Thanks, that seemed to work. > One way to test while still being able to use your computer is to > install a virtual machine with VMWare or some similar product. I use > VMWare's free software for testing some of my scripts, but I've heard > that Microsoft's got a free virtual product that isn't half bad. OK. If all else fails I might try that. But if there is a solution to the original problem it would be nice not to have to install VMWare everywhere for convenient testing... Geoff From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Aug 29 06:47:57 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 29 Aug 2007 12:47:57 +0200 Subject: Creating a multi-tier client/server application In-Reply-To: <7xbqcqhqbw.fsf@ruckus.brouhaha.com> References: <1188360460.838635.186930@w3g2000hsg.googlegroups.com> <7xbqcqhqbw.fsf@ruckus.brouhaha.com> Message-ID: <46d54ed8$0$429$426a34cc@news.free.fr> Paul Rubin a ?crit : > Jeff writes: >> Here's a broad overview of what I need to do: cross-platform, client- >> side GUI apps that interact with a server backed by a database. I'd >> also like the possibility of having a web interface for small portions >> of the app. ... any advice on anything I've mentioned >> (or haven't?) > > Why not do the entire app as a web app, completely bagging the client > side and just using a browser? It will help your deployment problems > a lot, and using https will help with security since it looks like the > app will be transmitting sensitive data. It also will simplify your > networking questions a lot since you're just writing a server. > (snip) > > I would certainly prototype the app as a web app, and then think about > writing a client gui only if it was clear that usability would really > benefit from it. Even still, the server would still look like a web > server, translating xml requests into database actions and responding > with xml. I'd personnaly favor json, which is much more lightweight, perfect for structured data, and widely supported. Else, and however the client is implemented (rich client or web - another possible solution being something based on the Mozilla platform, but I have no working experience with it so I can't tell if it's a good idea...), I'd second the suggestion to have a closer look at the http protocol. There's no shortage of support for writing http-based server applications in Python (given the context, I'd strongly suggest Pylons). >> I want to plan this application out as thoroughly >> as possible before writing any code, > > There is a school of thought (sometimes associated with "extreme > programming") that this is more planning than you should really do. > Think of a cross-country automobile trip. Figure out the general > route you want to take, then get in the car and go, making low-level > decisions as you get to them, rather than trying to plan every gas and > rest and restaurant stop before you leave. Anyway, unless you're a genius with decades of working experience, you can bet you'll make lots of mistakes in your "planning", mistakes that you'll discover when implementing a probably over-engineered design. I'm of course *not* advertising a cowboy-coding approach here, and preliminary work is certainly mandatory for anything non-trivial, but take care about what you really have to worry about here. AFAICT, you seem to be on the right track so far (thinking about the possible architectures given some already known requirements), but AMHE, BigDesignUpFront just doesn't work, so don't overplan. My 2 cents... From iapain at gmail.com Fri Aug 31 12:49:54 2007 From: iapain at gmail.com (iapain) Date: Fri, 31 Aug 2007 16:49:54 -0000 Subject: Google spreadsheets In-Reply-To: <1188564051.726895.288860@y42g2000hsy.googlegroups.com> References: <1188564051.726895.288860@y42g2000hsy.googlegroups.com> Message-ID: <1188578994.210244.70800@i13g2000prf.googlegroups.com> On Aug 31, 5:40 pm, Michele Simionato wrote: > I would like to upload a tab-separated file to a Google spreadsheet > from Python. Does anybody > have a recipe handy? TIA, > > Michele Simionato Probably its irrelevant to python. Use should see Google Spreadsheet API and use it in your python application. http://code.google.com/apis/spreadsheets/ From pyth0nc0d3r at gmail.com Sun Aug 26 14:37:52 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Sun, 26 Aug 2007 13:37:52 -0500 Subject: Lists Message-ID: Ok a = ['spam', 'eggs', 100, 1234] So basically when I do print a[1:-1] that will display all the choices in the array besides 0,3 Slicing was kinda weird, just making sure. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Aug 31 04:49:56 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 31 Aug 2007 10:49:56 +0200 Subject: beginner, idomatic python 2 In-Reply-To: <13der4jquo987d1@corp.supernews.com> References: <13csjmeaoqh9le3@corp.supernews.com> <1187927388.173203.298660@e9g2000prf.googlegroups.com> <13d4jfjfogbvq6f@corp.supernews.com> <46d2ba7a$0$430$426a74cc@news.free.fr> <13der4jquo987d1@corp.supernews.com> Message-ID: <46d7d623$0$12351$426a74cc@news.free.fr> bambam a ?crit : > "Bruno Desthuilliers" > wrote in message news:46d2ba7a$0$430$426a74cc at news.free.fr... >> As a side note, in Python, inheritance ... >> ... should usually not be used for typing. > > :~( > I'm sorry, I don't even know what that means... The code I > have inherited from someone only a little more knowledgeable > than me, and is still full of development artifacts anyway. > > The Pwr and Psp classes inherit from the Device class not > neccessarily because that is a Good Thing, more because > the development process led to them being thought of that > way. All devices have a mixture of common and differing > attributes. > > What is 'typing'? > Mmm... Most CS experts don't really agree on this, and I'm certainly not one (expert). So I won't even try to explain it by myself, and let you google for "type system", "static typing", "dynamic typing", "duck typing" etc... Now what I meant here is that in Python, you don't have to make class B inherit from class A to let you use an instance of B where an instance of A was expected - all you need is that both objects share the set of attributes and methods you're going to use. Inheritence is only useful for sharing common code. HTH From python-url at phaseit.net Mon Aug 20 09:47:36 2007 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 20 Aug 2007 13:47:36 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Aug 20) Message-ID: QOTW: "So I never let the age of the universe intimidate me." - mensanator, on (roughly) the occurrence of large integral exponents in combinatorics and more "You're coming from a Perl background, right? No one else would think of using a regexp for such a simple thing." - Sion Arrowsmith More people concerned about Python performance on dual core processors: http://groups.google.com/group/comp.lang.python/browse_thread/thread/cf1187deca5dd9ac/ http://groups.google.com/group/comp.lang.python/browse_thread/thread/13da24f2d6dc24a9/ Alex Martelli explains why using reduce() in some cases is a bad idea, and how to efficiently obtain a result combining all items in a container: http://groups.google.com/group/comp.lang.python/browse_thread/thread/78b5953488d772e9/4951b0e0bfd859eb#b65604f723047457 A recursive defaultdict (or an infinite level dictionary) http://groups.google.com/group/comp.lang.python/browse_thread/thread/9519c885a24a65ea/7a5bd10726f2c079?#7a5bd10726f2c079 Sorting Unicode is not as easy as one would think ... http://groups.google.com/group/comp.lang.python/browse_thread/thread/42c3dadf86f117c Some thoughts on making indentation play well with blind people http://groups.google.com/group/comp.lang.python/browse_thread/thread/80654a87bfa89e3b Using itertools to allow re-processing of lines already read from a file http://groups.google.com/group/comp.lang.python/browse_thread/thread/1aa414f4c6bb5793 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From wildemar at freakmail.de Sun Aug 19 12:38:43 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Sun, 19 Aug 2007 18:38:43 +0200 Subject: Hot subject: a good python editor and/or IDE? In-Reply-To: <46C847AD.50709@gmail.com> References: <5iqreuF3qanv6U1@mid.individual.net> <46C847AD.50709@gmail.com> Message-ID: <46C87213.5010402@freakmail.de> Buchoux S?bastien wrote: > Yeah, I know this is a FAQ, but, as you mention, there is a whole bunch > of editors, every one of them being updated constantly (+ the new ones > getting out). So I am quite sure that looking through the archives is > THE solution since it will only reflect what people thought when > question was asked. Just type "best Python editor" on Google and you > will see that almost all hits are completely out of date. > Fair enough though! ;) > Well, since this question pops up about once a *week* on this list, chances are the most recent replies are not outdated. Just search this group instead of the whole web. /W From grflanagan at yahoo.co.uk Thu Aug 2 03:19:38 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: Thu, 02 Aug 2007 00:19:38 -0700 Subject: Awkward format string In-Reply-To: References: <1185984697.605529.157110@g12g2000prg.googlegroups.com> <1186003719.783219.104200@r34g2000hsd.googlegroups.com> Message-ID: <1186039178.469009.98870@q75g2000hsh.googlegroups.com> On Aug 1, 11:52 pm, Ian Clark wrote: > Gerard Flanagan wrote: > > (snip) > > > def tostring(data): > > return tuple(strftime(x) for x in data[:2]) + data[2:] > > Hrmm, not sure that having a function named tostring() that returns a > tuple is the best idea. ;) > oops! SAD (Solipsistic API Design)... ;-) Gerard From josehectorcontreras at arnet.com.ar Thu Aug 30 14:53:18 2007 From: josehectorcontreras at arnet.com.ar (=?iso-8859-1?Q?Dr._Jos=E9_Contreras?=) Date: Thu, 30 Aug 2007 20:53:18 +0200 Subject: Ayuda Message-ID: <008c01c7eb37$0895eb80$0500000a@wf6840f5e6a1e4> Gente Inteligente y Distinguida, soy un aficionado y apelo a Ustedes, para resolver ?ste problema. Para WebMaster de Google, me solicita instalar o ejecuci?n de pit?n, c?mo comprender?n no dispongo de ning?n guru de web, por lo que solicito en la medida de sus posibilidades me ayuden a ejecutar pit?n para WebMaster, para ingresar a sitemap.xlm. Les saludo con distinguida consideraci?n y respeto. Jos? Si son tan amables, les agradecer? cualquiera sea la Repuesta, en Espa?ol o castellano. Gracias -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Sat Aug 11 09:05:50 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Aug 2007 13:05:50 GMT Subject: Destruction of generator objects References: <20070808002852.6228ae91@cube.tz.axivion.com> <1186613044.494852.306970@q75g2000hsh.googlegroups.com> <20070809011441.05d7dfb6@cube.tz.axivion.com> <1186819365.988117.232230@g4g2000hsf.googlegroups.com> <20070811121630.1b010eab@cube.tz.axivion.com> <1186831173.814193.235420@o61g2000hsh.googlegroups.com> <20070811140017.22a11f82@cube.tz.axivion.com> <1186834823.389706.137980@r34g2000hsd.googlegroups.com> <20070811145033.18c70c0c@cube.tz.axivion.com> Message-ID: <5i5qheF3ml00gU2@mid.uni-berlin.de> On Sat, 11 Aug 2007 14:50:33 +0200, Stefan Bellon wrote: > On Sat, 11 Aug, Kay Schluehr wrote: > >> But why shall the destructor be called? Your example does not indicate >> that a ListGenerator object is somewhere destroyed neither explicitely >> using del nor implicitely by destroying the scope it is living in. > > After having constructed the list itself, the generator is exhausted > and not iterated or referenced anymore, so the generator should be > destroyed, shouldn't it? > > Ok, let's make the example easier and take out the external iterator > resource and just concentrate on the Python part: > > class ListGenerator(object): > def __init__(self): > print "gen init" > self.gen = self._value() > > def __del__(self): > print "gen del" > > def _value(self): > print "gen value" > for i in xrange(4): > yield i > > def __iter__(self): > print "gen iter" > return self > > def next(self): > print "gen next" > return self.gen.next() > > Now, doing the following: > >>>> a = ListGenerator() > gen init >>>> a > <__main__.ListGenerator object at 0x4020c3ec> >>>> for i in a: print i > ... > gen iter > gen next > gen value > 0 > gen next > 1 > gen next > 2 > gen next > 3 > gen next >>>> del a >>>> > > So why is the destructor not called when the generator is even > explicitly 'del'ed? The generator is not ``del``\ed, just the name `a` is removed. > Does somebody else still hold a reference on it? Yes, the interactive Python shell holds the last non-`None` result in `_`: >>> from forum import ListGenerator >>> a = ListGenerator() gen init >>> a >>> for i in a: print i ... gen iter gen next gen value 0 gen next 1 gen next 2 gen next 3 gen next >>> del a >>> _ >>> 42 gen del 42 > But then, even when terminating the interpreter, __del__ is not called. Because that is not guaranteed by the language reference. The reason why it is a bad idea to depend on `__del__` for important resource management. Ciao, Marc 'BlackJack' Rintsch From kay.schluehr at gmx.net Sat Aug 11 07:59:29 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 11 Aug 2007 04:59:29 -0700 Subject: The Future of Python Threading In-Reply-To: <1186740111.918048.77920@d30g2000prg.googlegroups.com> References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> Message-ID: <1186833569.074364.153320@b79g2000hse.googlegroups.com> Have you checked out the processing [1] package? I've currently the impression that people want to change the whole language before they checkout a new package. It would be nice to read a review. [1] http://cheeseshop.python.org/pypi/processing From arkanes at gmail.com Thu Aug 30 14:36:58 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 30 Aug 2007 13:36:58 -0500 Subject: gc.garbage In-Reply-To: <1188498335.633506.90050@q4g2000prc.googlegroups.com> References: <1188467173.708043.44800@w3g2000hsg.googlegroups.com> <46D692FC.4030805@v.loewis.de> <1188498335.633506.90050@q4g2000prc.googlegroups.com> Message-ID: <4866bea60708301136u18ca87a0l4abfa888fa4a1c84@mail.gmail.com> On 8/30/07, 7stud wrote: > On Aug 30, 3:50 am, "Martin v. L?wis" wrote: > > > gc.set_debug(gc.DEBUG_LEAK) > > > print gc.garbage > > > > > --output:-- > > > [] > > > gc: uncollectable > > > gc: uncollectable > > > gc: uncollectable > > > gc: uncollectable > > > > gc.garbage is filled only after these messages > > are printed, not before. You need to add an explicit > > call to gc.collect() if you want to see what > > uncollectable garbage you have. > > > > Regards, > > Martin > > Hi, > > Thanks for the response. I had a cut and paste error in my reply, so > here it is again with the corrections... > > Now, if I run the code: > > ------------ > import gc > > class Cat(object): > def __del__(): > pass > > class Dog(object): > def __del__(): > pass > > def some_func(): > the_dog = Dog() > the_cat = Cat() > the_dog.cat = the_cat > the_cat.dog = the_dog > > some_func() > > gc.set_debug(gc.DEBUG_LEAK) > gc.collect() > print gc.garbage > ----------- > > I get this output: > > ---------- > gc: uncollectable > gc: uncollectable > gc: uncollectable > gc: uncollectable > [<__main__.Dog object at 0x56e10>, <__main__.Cat object at 0x56e30>, > {'cat': <__main__.Cat object at 0x56e30>}, {'dog': <__main__.Dog > object at 0x56e10>}] > ----------- > > Why are there two entries in the list for each uncollectable > object(same addresses)? Also, I haven't bound the names "cat" or > "dog" anywhere in my program. What do those names mean in the list? > Read your output carefully! gc.garbage is a list of objects. The objects are printed just as they would be anywhere else in Python. You've got the dog object, the cat object, and the __dict__ of each instance. > Doing some further testing, if I eliminate the __del__ methods: > > ----------- > import gc > > class Cat(object): > pass > > class Dog(object): > pass > > def some_func(): > the_dog = Dog() > the_cat = Cat() > the_dog.cat = the_cat > the_cat.dog = the_dog > > some_func() > > gc.set_debug(gc.DEBUG_LEAK) > gc.collect() > print gc.garbage > ------------------- > > I get this output: > > ----- > gc: collectable > gc: collectable > gc: collectable > gc: collectable > [<__main__.Dog object at 0x56e10>, <__main__.Cat object at 0x56e30>, > {'cat': <__main__.Cat object at 0x56e30>}, {'dog': <__main__.Dog > object at 0x56e10>}] > ----- > > The docs say: > > --------- > garbage > A list of objects which the collector found to be unreachable but > could not be freed (uncollectable objects). > -------- > > Since debugging doesn't show any uncollectable objects, why isn't > gc.garbage empty? The docs also say: > > ---- > garbage > ...By default, this list contains only objects with __del__() methods. > ---- > > Does set_debug() change the default? > >From the last line of the documentation block you quoted above: "If DEBUG_SAVEALL is set, then all unreachable objects will be added to this list rather than freed." From ninja.krmenadl at nes.com Mon Aug 20 16:21:27 2007 From: ninja.krmenadl at nes.com (Boris Ozegovic) Date: Mon, 20 Aug 2007 22:21:27 +0200 Subject: I Need help from all the group participants References: <1187636668.436474.289220@o80g2000hse.googlegroups.com> <1187638964.815505.85390@57g2000hsv.googlegroups.com> Message-ID: Jason wrote: > I wonder what John's pulse is? Display John's pulse. I need to know > John's pulse. How many beats per minute is John's heart going? > What's John's pulse rate? How fast is John's heart rate? How fast is > John's blood pumping? What is the rate of John's heart? What is the > rate of John's pulse? How fast is John's heart beating? What is the > frequency of John's heart pulses? What is the frequency of John's > cardiac cycle? How fast is John's cardiac cycle? What is the rate of > John's pulse? I want the result of John's auscultation. Give me > John's heart beats, or give John death! Wow! Thank you very much! > If you're trying to do some natural language processing, you should I'm doing project in AIML, www.alicebot.org/ , which will do all behind work for me, and I only need to combine patterns, for example (if you are interested :) http://www.pandorabots.com/botmaster/en/tutorial?ch=6 , you can see how AIML works. Unfortunetly, the problem with NLP, and AIML, is that you need programmer and someone with linguistic skills. :) -- Ne dajte da nas la?ljivac Bandi? truje: http://cnn.blog.hr/arhiva-2007-06.html#1622776372 From kyosohma at gmail.com Thu Aug 23 15:18:14 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 23 Aug 2007 12:18:14 -0700 Subject: how to select between two file libraries with same name? In-Reply-To: <1187894807.228812.266270@q5g2000prf.googlegroups.com> References: <1187894807.228812.266270@q5g2000prf.googlegroups.com> Message-ID: <1187896694.750383.170760@m37g2000prh.googlegroups.com> On Aug 23, 1:46 pm, jmborr wrote: > Imagine my file one.py contains the statement > import two > If there's a two.py in same directory as one.py, then this file will > be loaded. However, I want to load a different file named also two.py, > say file ~username/mypythonlib/two.py > How can I select between the two two.py files ? > -jose This kind of thing has been discussed before. See below: http://mail.python.org/pipermail/python-list/2002-October/167055.html The basic idea is not to do this. Fix your code so that you never have this problem through code refactoring. Mike From seb.buchoux at gmail.com Fri Aug 17 03:35:47 2007 From: seb.buchoux at gmail.com (=?ISO-8859-1?Q?S=E9bastien_Buchoux?=) Date: Fri, 17 Aug 2007 09:35:47 +0200 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: <1187303750.590497.208060@x40g2000prg.googlegroups.com> References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> Message-ID: <46C54FD3.6020305@gmail.com> beginner a ?crit : > Hi All. > > I'd like to do the following in more succint code: > > if k in b: > a=b[k] > else: > a={} > b[k]=a > > a['A']=1 > > > In perl it is just one line: $a=$b->{"A"} ||={}. > > Thanks, > Geoffrey > > One solution I often use in such cases: try: a = b[k] except KeyError: #or except IndexError: if b is a list/tuple and not a dict a = {} b[k] = a a['A'] = 1 Indeed, exceptions are handled faster than "if/else" loops. As it was mentionned earlier, One neat solution in Perl may not be the perfect one in Python. Cheers, S?bastien From whamil1 at entergy.com Mon Aug 6 13:30:04 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Mon, 6 Aug 2007 12:30:04 -0500 Subject: Something in the function tutorial confused me. In-Reply-To: <1186420642.112170.78940@w3g2000hsg.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CAFF@LITEXETSP001.etrsouth.corp.entergy.com> > From: Lee Fleming > > On Aug 6, 6:25 am, Neil Cerutti wrote: > Because when the function is called, the line > > > > if y is None: y = [] > > > is executed, binding a brand new empty list to y. This > "rebinding" happens every time the function is called, unless you > provide an argument for y that is not None. > > Thanks for the prompt replies. But I am still confused. This is what > confuses me.... > The first time you call the function, say with f(23), after the > function ends, > y no longer equals None. Therefore, calling f again, this time like > this f(24), > should make y equal [23,24], because the 'if y == None' test fails, or > at least I think it > fails, because y.append(x) added something that was not equal to None > during the previous call. When you call f(23), the variable y within it gets created and points at None. When f(23) exits, the y that it created gets destroyed. (Well, goes out of scope, but even if it's not garbage collected it won't ever come back into scope.) When you then call f(24), a new y is created that also points to None, and disappears forever when f(24) exits. The values in a def statement are created when the def is executed, but the variables are only created when the function is actually called, and new ones are created every time the function is called. -- -Bill Hamilton From zentraders at gmail.com Sat Aug 18 22:04:15 2007 From: zentraders at gmail.com (Zentrader) Date: Sat, 18 Aug 2007 19:04:15 -0700 Subject: How to call module functions inside class instance functions? In-Reply-To: <1187487622.450655.265000@q4g2000prc.googlegroups.com> References: <1187484041.838615.259980@e9g2000prf.googlegroups.com> <1187487622.450655.265000@q4g2000prc.googlegroups.com> Message-ID: <1187489055.946442.63880@x40g2000prg.googlegroups.com> > By the way, the reason I am naming it __module_level_func() is because > I'd like __module_level_func() to be private to the module, like the C > static function. If the interpreter cannot really enforce it, at least > it is some sort of naming convention for me. re the above: set file permissions for testmodule.py to limit access. IMHO it is a better solution. From claird at lairds.us Tue Aug 7 10:00:17 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 7 Aug 2007 14:00:17 +0000 Subject: Tkinter or wxpython? References: <7xlkcopu4r.fsf@ruckus.brouhaha.com> <7x7io8r6na.fsf@ruckus.brouhaha.com> Message-ID: In article <7x7io8r6na.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: . . . >I should also add: there is also the possibility of running a Python >program with an embedded http server on the same desktop as the >browser, using the browser purely as a gui, but with the Python >program having complete access to the file system and so forth. This >could be seen as combining the disadvantages of both the remote web >server approach (i.e. gui elements constrained by the browser) and the >all-desktop approach (deployment issues). However, a lot of the time >it's still just plain easier to do. Whenever I've written a desktop >gui app I've always just been shocked at how much time goes into >making the gui look decent and do the right stuff, even though none of >mine have been even slightly slick (they've all been for industrial >applications). When I do a web gui, it's been just a matter of >tossing some html into a file or into some print statements, viewing >it in a browser, and tweaking it a little as needed. Maybe that's >mostly a matter of the lousy state of gui toolkits, and we actually >need a toolkit that's more like an embedded browser. But we don't >have that at the moment. One key to Tkinter's longevity lurks there. While many whine about the antiquity of the appearance of Tkinter's widgets, they have the virtue of sensible defaults; more than any other toolkit, Tkinter comes up with minimal refinements in a sensible and consistent state. While those with an artistic eye assure me the simplest Tkinter programs look worse that corresponding ones built with any other toolkit, they behave the most coherently in regards to resizing and so on. From zyzhu2000 at gmail.com Mon Aug 20 14:25:23 2007 From: zyzhu2000 at gmail.com (beginner) Date: Mon, 20 Aug 2007 18:25:23 -0000 Subject: str().join() isn't working In-Reply-To: References: <496954360708200905i2100b32ag5983ab729e5d216f@mail.gmail.com> Message-ID: <1187634323.092460.39800@q3g2000prf.googlegroups.com> On Aug 20, 1:16 pm, "Robert Dailey" wrote: > here is a more realized example of the lists I'm trying to join: > > _user_includes = [ > "../src", > "../resource", > "../inc", > "../src", > "../data", > "../gui", > "../script", > "../script/actions", > "../gui/dispatch", > "../gui/factories", > "../gui/frames", > "../gui/getters", > "../gui/localization", > "../gui/player", > "../gui/setters", > "../gui/utilities", > "../sis", > "../player", > "../platform/ngi", > "../../engine", > "../../engine/audio/NGI", > "../../engine/io", > "../../engine/io\NGI", > "../../engine/math", > "../../engine/math/fixed", > "../../engine/path/NGI", > "../../engine/text/NGI", > "../../engine/mem", > "../../engine/text", > "../../engine/observer", > "../../sdk/tiny_xml", > "../../sdk/zlib", > "../../sdk/lpng", > "../../sdk/IFDLib/Source/Precompile", > "../../sdk/IFDLib/Source/CoreLib", > "../../sdk/IFDLib/inc", > "../../sdk/IFDLib/Source/UtilLib", > "../../sdk/IFDLib/Source/GameLib", > "../../sdk/IFDlib/Source/OSLib/_NGI", > "../../sdk/stl-port/NGI", > "../../sdk/mini-boost/NGI", > "../../sdk/mini-boost/COMMON", > ] > > _system_includes = [ > "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include", > "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include/osextensions/rg?a", > "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include/osextensions/st?dapis", > "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include/osextensions/st?dapis/stlport", > "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/epoc32/include/variant" > ] > > On 8/20/07, Robert Dailey wrote: > > > > > Hi, > > > First have a look at the following code: > > > In main.py: > > ---------------------------------------------------------------------------?-------- > > space = " " > > > includes = space.join ( system._user_includes ) + " " + space.join( > > system._system_includes ) > > > In system.py: > > ---------------------------------------------------------------------------?-------- > > _user_includes = [ > > ] > > > _system_includes = [ > > ] > > > The above does not work. The interpreter states: "TypeError: sequence item > > 0: expected string, list found". I'm not sure what this means. Can anyone > > help me figure out what I'm doing wrong? Thanks. > > > PS: I've also tried putting strings in the lists above just to make sure > > that them being empty wasn't the problem. I got no different results.- Hide quoted text - > > - Show quoted text - I have no system.py, but when I run includes = space.join (_user_includes ) + " " + space.join(_system_includes ) with the lists given in your post, I get no error. I am using v2.5.1 on Windows XP. From bronger at physik.rwth-aachen.de Wed Aug 15 12:28:29 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Wed, 15 Aug 2007 18:28:29 +0200 Subject: All names in the current module Message-ID: <87d4xowymq.fsf@wilson.homeunix.com> Hall?chen! How can I get a list with all classes defined in the current module? Thank you! Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From aahz at pythoncraft.com Thu Aug 9 17:34:00 2007 From: aahz at pythoncraft.com (Aahz) Date: 9 Aug 2007 14:34:00 -0700 Subject: Stackless Integration References: <1186650027.043779.276520@i38g2000prf.googlegroups.com> <1186678419.594781.149190@g12g2000prg.googlegroups.com> Message-ID: In article , Neil Cerutti wrote: >On 2007-08-09, Justin T. wrote: >>JP Calderone: >>> >>> It's not Pythonic. >> >> Ha! I wish there was a way to indicate sarcasm on the net. You >> almost got people all riled up! > >Sorry. There's NO WAY to show sarcasm on the net. ;) "If sarcasm were posted to the Net, would anybody notice?" --JDN -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "And if that makes me an elitist...I couldn't be happier." --JMS From bignose+hates-spam at benfinney.id.au Wed Aug 1 19:54:43 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 02 Aug 2007 09:54:43 +1000 Subject: Emacs + python References: Message-ID: <878x8udd4s.fsf@benfinney.id.au> Hadron writes: > Could anyone put me on the right track to developing Python with emacs > please : modes to consider, debugging etc hopefully all within emacs. The mode you're looking for is 'python-mode'. Turn it on (M-x python-mode), then read its help (C-h m) for all the cool things you can do. -- \ "Our products just aren't engineered for security." -- Brian | `\ Valentine, senior vice-president of Microsoft Windows | _o__) development | Ben Finney From iclark at mail.ewu.edu Mon Aug 13 16:45:40 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Mon, 13 Aug 2007 13:45:40 -0700 Subject: Getting started with JPype In-Reply-To: <1187014607.465437.97460@19g2000hsx.googlegroups.com> References: <1187014607.465437.97460@19g2000hsx.googlegroups.com> Message-ID: Disclaimer: I have never used (or even heard of) JPype before... porter wrote: (snip) > > "Package myclass.HelloWorld is not Callable" > (snip) > > from jpype import * > > startJVM(getDefaultJVMPath(), "-ea", "-Djava.class.path=D:/tmp/jpype- > reli/test/dist/test.jar'' ) > > package = JPackage("myclass") Shouldn't this be `package = JPackage("myclasses")` as your Java code is contained in the package 'myclasses' not 'myclass'? > x = package.HelloWorld() Change this last line to: `x = package.HelloWorld` (class would be a better name than x IMO) > x.do_a_message() > > shutdownJVM() It looks like JPype exports Java classes as members of the object referred to by `package`. You then try and call it with () and python throws it's hands in the air as it must not be a callable. Ian From nospam at here.com.org Wed Aug 22 14:31:24 2007 From: nospam at here.com.org (Eric) Date: Wed, 22 Aug 2007 14:31:24 -0400 Subject: Free Air Conditioners!!!!!! References: <1187738115.972271.94080@r23g2000prd.googlegroups.com> <1187806818.490520.231690@e9g2000prf.googlegroups.com> Message-ID: <46cc80fd$0$5180$9a6e19ea@unlimited.newshosting.com> And $15 shipping to get the "free" paper sent to you! ;^) "Zentrader" wrote in message news:1187806818.490520.231690 at e9g2000prf.googlegroups.com... > On Aug 21, 10:13 pm, "Scott M." wrote: >> Oh my God! How did you know?!! You were so smart to post that here! >> >> wrote in message >> >> news:1187738115.972271.94080 at r23g2000prd.googlegroups.com... >> >> >http://freeairconditioners.blogspot.com/ > > It's probably a handheld fan made out of a piece of paper > From jstroud at mbi.ucla.edu Wed Aug 22 19:11:29 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 22 Aug 2007 16:11:29 -0700 Subject: libgmail failure In-Reply-To: <1187810899.496022.314240@z24g2000prh.googlegroups.com> References: <1187730447.621592.93740@q4g2000prc.googlegroups.com> <1187810899.496022.314240@z24g2000prh.googlegroups.com> Message-ID: <8j3zi.4129$Oo.2593@newssvr17.news.prodigy.net> james.p.news at gmail.com wrote: > On Aug 22, 10:26 am, James Stroud wrote: >> Have you thought about spoofing explorer? Always spoof explorer. >> >> James > > > I have not heard of this. How do you spoof IE in libgmail? You might have to edit libgmail.py directly and add a header to the urllib2.Request() call. Here are the relevant lines from some code I wrote (spoofing netscape it looks like): user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' txheaders = {'User-agent' : user_agent} req = urllib2.Request(pda, signin_params, txheaders) See if this doesn't fix you up. James From steve at holdenweb.com Sat Aug 18 08:09:39 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 18 Aug 2007 08:09:39 -0400 Subject: passing arguments with ampersands In-Reply-To: <20070818112913.GA3632@gmail.com> References: <20070818112913.GA3632@gmail.com> Message-ID: O.R.Senthil Kumaran wrote: >> Quote:D:\ftp\Music\Mixes & Compilations\Above & Beyond - Essential >> Mix\001_Essential_Mix_2004-06-06_-_Above_and_Beyond.txt > >> when i put 'print sys.argv[1:]' at the very beginning of the script, all i >> get is this: >> >> Quote:['D:\\ftp\\Music\\Mixes'] >> > Can you share the portion of the code? > Are you quoting the argument that you are passing? > for e.g: > > #cat 1.py > import sys > print sys.argv[1] > > #python 1.py "I am able to print the spaces and & characters" > I am able to print the spaces and & characters > I suspect that the ampersand is being interpreted as a command terminator, and that the shell syntax error has been overlooked. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From frikker at gmail.com Thu Aug 2 11:34:11 2007 From: frikker at gmail.com (frikk) Date: Thu, 02 Aug 2007 08:34:11 -0700 Subject: Memory Leak with Tkinter Canvas (Python 2.5 Win32) Message-ID: <1186068851.011344.322980@i13g2000prf.googlegroups.com> Hey everyone. I have been working with python for a couple years now, but just recently built my first program with a GUI. I decided to start with Tkinter since it is included with the base package, although wxWindows will likely be my next choice. Tkinter seems to be pretty slow for my needs. Anyway - I am building a genetic algorithm simulator. I have a grid where an Ant moves around. It is infeasible for me to update the grid every simulation step - so I just do it at the end. But what I've realized is that my program performs worse and worse when I update the grid. Turns out there is a memory leak somewhere and I don't think it is in my code. The memory leak occurs only when I write (via create_rectangle) to the canvas widget. I wrote the following small script to demonstrate this problem (see below). Every time the button is pressed, _1040KB_ is added to the RAM of wpython.exe. This adds up FAST. I have not verified this on my OS X box. As you can see- I am doing nothing other than drawing a lot of rectangles on the canvas. I have two questions. 1. Is this a bug in my usage of Tkinter? Am I somehow leaving objects laying around that aren't being deleted? Is create_rectangle not the appropriate function to use?) 2. Is there a better, quicker way to update a "grid"-like object? Thanks, Blaine Current System: Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Windows XP SP2 - all recent patches and updates Script: from Tkinter import * canv = None HEIGHT=600 WIDTH=600 def clear_grid(): for i in range(0,HEIGHT/10): for j in range(0, HEIGHT/10): canv.create_rectangle(i*10,j*10, \ i*10+10, j*10+10, \ fill = "white") def draw_window(master): global canv frame = Frame(master) btn_grid = Button(frame, text="draw grid", command=clear_grid) btn_grid.pack(side=TOP) canv = Canvas(frame, height=HEIGHT, width=WIDTH, bg='white') canv.pack() frame.pack() root = Tk() draw_window(root) mainloop() From ksuindu at vsnl.net Thu Aug 9 02:28:27 2007 From: ksuindu at vsnl.net (indu_shreenath) Date: Thu, 09 Aug 2007 06:28:27 -0000 Subject: how to get output. Message-ID: Hey, I want to get the output of "DIR /AD /B" command to a varriable using python. How can I do this? Thanks, Indu From gagsl-py2 at yahoo.com.ar Mon Aug 20 04:05:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 20 Aug 2007 05:05:48 -0300 Subject: Problem with Thread.join() References: <496954360708131610i62c0a63aneb7c39d23a052ac0@mail.gmail.com> Message-ID: En Mon, 13 Aug 2007 20:10:53 -0300, Robert Dailey escribi?: > I have a class that derives from threading.Thread. To signal the thread > to > exit its infinite loop, I set an Event. Once the thread checks > Event.isSet() > and it is true, it proceeds to break out of the loop and exit the > function. > In the main thread, right after calling Event.set(), I call > Thread.join() to > wait on the thread to exit. However, if I call Thread.join() the > application > locks up because for some reason calling Thread.join() prevents the > thread > from exiting. I don't know why. Any help? Thanks... Conceptually you're doing it the right way. Post some code demonstrating the problem... -- Gabriel Genellina From arkanes at gmail.com Thu Aug 16 15:03:36 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 16 Aug 2007 14:03:36 -0500 Subject: Accessing Windows Network Share? In-Reply-To: <1187289961.104183.104910@50g2000hsm.googlegroups.com> References: <1187287133.737105.169960@19g2000hsx.googlegroups.com> <1187289961.104183.104910@50g2000hsm.googlegroups.com> Message-ID: <4866bea60708161203j7e9138der343d4ef15b1c371e@mail.gmail.com> On 8/16/07, frikk wrote: > On Aug 16, 2:43 pm, "Chris Mellon" wrote: > > On 8/16/07, frikk wrote: > > > > > > > > > > > > > I previously posted about accessing SharePoint over the web. Well I > > > have since given up any easy means of doing this, since something else > > > has perked my interest. Instead of going tohttp://sharepoint/site, > > > why not just access \\sharepoint\site\ directly? > > > > > So my question is this - How do I access that network share? > > > > > If I go to start -> run, and type in "\\SharPointServer\Site\Folder", > > > windows explorer will pop up with it. I suppose I could have a little > > > batch script that python runs to map the drive to a local letter, like > > > J:, but this does not seem necessary. > > > > > Suggestions? > > > > > This does not work, for obvious reasons: > > > >>> import glob.glob > > > >>> glob.glob("\\\\server\\folder\\*") > > > [] > > > > I don't see whats "obvious" about this. Access to windows shares is > > handled by Windows in a VFS layer, and glob and all other Python file > > access works fine over them for me.- Hide quoted text - > > > > - Show quoted text - > > Haha ok, you're right its not obvious. Sorry for that. > > But that code does not work - should it? > > Do you have an example of glob working over a file share, not a > network mapped drive? > import glob glob.glob(r"\\localhost\c$\python25\libs\*") ['\\\\localhost\\c$\\python25\\libs\\bz2.lib', '\\\\localhost\\c$\\python25\\libs\\libpython25.a', '\\\\localhost\\c$\\python25\\libs\\pyexpat.lib', '\\\\localhost\\c$\\python25\\libs\\python25.lib', '\\\\localhost\\c$\\python25\\libs\\select.lib', '\\\\localhost\\c$\\python25\\libs\\unicodedata.lib', '\\\\localhost\\c$\\python25\\libs\\winsound.lib', '\\\\localhost\\c$\\python25\\libs\\_bsddb.lib', '\\\\localhost\\c$\\python25\\libs\\_ctypes.lib', '\\\\localhost\\c$\\python25\\libs\\_ctypes_test.lib', '\\\\localhost\\c$\\python25\\libs\\_elementtree.lib', '\\\\localhost\\c$\\python25\\libs\\_hashlib.lib', '\\\\localhost\\c$\\python25\\libs\\_msi.lib', '\\\\localhost\\c$\\python25\\libs\\_socket.lib', '\\\\localhost\\c$\\python25\\libs\\_sqlite3.lib', '\\\\localhost\\c$\\python25\\libs\\_ssl.lib', '\\\\localhost\\c$\\python25\\libs\\_testcapi.lib', '\\\\localhost\\c$\\python25\\libs\\_tkinter.lib'] I do it all the time. I'd double check your slash escaping (consider using r'') and pathnames. From cesmiga at gmail.com Tue Aug 21 12:09:23 2007 From: cesmiga at gmail.com (epsilon) Date: Tue, 21 Aug 2007 09:09:23 -0700 Subject: Trouble with CGI code from Code Example 7.3 of the "Python Interactive CGI Tutorial" In-Reply-To: <1187710122.354087.158910@o80g2000hse.googlegroups.com> References: <1187705685.007927.55030@z24g2000prh.googlegroups.com> <1187710122.354087.158910@o80g2000hse.googlegroups.com> Message-ID: <1187712563.590974.54160@r23g2000prd.googlegroups.com> Gabriel, Thanks a bunch for your time! That took care of it. Christopher Gabriel Genellina wrote: > On 21 ago, 11:14, epsilon wrote: > > > I'm having trouble with this script from a CGI lesson I'm working and > > I can't seem to figure it out. I was wondering if someone could tell > > me what is wrong. I've spent several hours trying to debug, but no > > success. Any help would be appreciated. > > Next time try to post the exact error message you get - working > crystall balls are hard to find nowadays :) > Ok, it's a syntax error, perhaps you didn't get a useful response from > the server. > The error is here: > > > if (session_key == 0): > > session_key = create_session(id) > > print id, , you are logged in with key:", session_key, > > That should read: > > print id, "you are logged in with key:", session_key, "\n" > > -- > Gabriel Genellina From michael at jedimindworks.com Mon Aug 27 14:44:11 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Mon, 27 Aug 2007 11:44:11 -0700 Subject: convert non-delimited to delimited In-Reply-To: <1188237563.889663.228970@o80g2000hse.googlegroups.com> References: <1188237563.889663.228970@o80g2000hse.googlegroups.com> Message-ID: <48FC2954-1743-4484-8681-188B110CE879@jedimindworks.com> On Aug 27, 2007, at 10:59 AM, RyanL wrote: > I'm a newbie! I have a non-delimited data file that I'd like to > convert to delimited. > > Example... > Line in non-delimited file: > 0139725635999992000010100534+42050-102800FM-15+1198KAIA > > Should be: > 0139,725635,99999,2000,01,01,00,53,4,+42050,-102800,FM-15,+1198,KAIA > > What is the best way to go about this? I've looked all over for > examples, help, suggestions, but have not found much. CSV module > doesn't seem to do exactly what I want. Maybe I'm just missing > something or not using the correct terminology in my searches. Any > assistance is greatly appreaciated! Using Python 2.4 Is each data element a fixed size? From twisted0n3 at gmail.com Tue Aug 21 11:05:16 2007 From: twisted0n3 at gmail.com (Twisted) Date: Tue, 21 Aug 2007 15:05:16 -0000 Subject: Latest models of Gibson guitars In-Reply-To: <1187700758.572516.186610@57g2000hsv.googlegroups.com> References: <1187544898.289948.322160@22g2000hsm.googlegroups.com> <1187548916.909340.37420@k79g2000hse.googlegroups.com> <1187579396.285862.186860@e9g2000prf.googlegroups.com> <9K6dnY8HnIUNHlTbnZ2dnUVZ_gGdnZ2d@comcast.com> <1187657694.106990.266830@z24g2000prh.googlegroups.com> <1187700758.572516.186610@57g2000hsv.googlegroups.com> Message-ID: <1187708716.843211.141790@e9g2000prf.googlegroups.com> On Aug 21, 8:52 am, kaldrenon wrote: > On Aug 20, 8:54 pm, Twisted wrote: > > > If the message then > > says something absurd, like "this is a newsgroup about Python" when > > I'm reading it in cljp, well, what do you expect? :P > > I think most would expect you to go, "WTF?" but then, like a rational > person, click the helpful little "More options" link that GG provides [snip rest of insult-implying randomness] Er, right, whatever. :P > > though nothing in the headers would indicate this. > > Newsgroups: comp.lang.java.programmer, > microsoft.public.dotnet.framework.aspnet, comp.lang.python, > rec.photo.digital, alt.home.repair That indicates a *crosspost*. As I was saying in the post you've willfully misinterpreted in order to attack me, there is however nothing of the sort to indicate a *multipost*. From ironfroggy at gmail.com Fri Aug 3 11:57:07 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Fri, 3 Aug 2007 11:57:07 -0400 Subject: Coroutine API Message-ID: <76fd5acf0708030857we41631bv3a592f00c134b954@mail.gmail.com> I was talking to some other people, who all were working on different schedulers and such for coroutines. We decided to work out a common API to give coroutines, and common rules to passing data between them, etc. I am wondering now if there is already work on this, or some schedulers I'm not aware of that have any deployment and a good, simple design. We also setup a group to discuss this and iron out our details and some common coroutines. python-coro at googlegroups.com We came up with this basic rule set: 1) A coroutine can be any iterable 2) A coroutine yielding None is suspending to allow others to run 3) A coroutine yielding something else is yielding another coroutine and needs to stay suspended until that coroutine has a value to pass to the send() method of the coroutine. 4) In the above case, if the yielded coroutine raises an exception, it is passed to the waiting coroutine's throw() method. 5) A coroutine raising StopIteration(arg), where arg is its final result, expects arg to be passed to the send() method of any coroutine which is waiting for its completion. The idea is that we don't rely on defining any new types or functions and we keep it extremely simple. I'd like to consider it WSGI for coroutines. -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From tdelaney at avaya.com Wed Aug 8 19:34:46 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 9 Aug 2007 07:34:46 +0800 Subject: Jython - problem import os In-Reply-To: <1186575029.494729.327550@b79g2000hse.googlegroups.com> Message-ID: nmin at freenet.de wrote: > I'm using Jython in combination with Java, webservices and jboss4.0.4. > > The webservice is implemented in java and creates an PythonInterpreter > object which loads the jython scripts. > I wrote an jython script which uses a function from another jython > file called library.py. ... > ImportError: no module named javaos in library.py. > > Any ideas? You need to make sure that the Jython Lib directory is on sys.path - the easiest way it to put it in the same directory as jython.jar e.g. in your webapp have: WEB-INF/ lib/ jython.jar Lib/ ... os.py ... Tim Delaney From godzillaismad at gmail.com Thu Aug 9 20:25:00 2007 From: godzillaismad at gmail.com (Godzilla) Date: Fri, 10 Aug 2007 00:25:00 -0000 Subject: Deleting objects on the fly Message-ID: <1186705500.227658.163170@q3g2000prf.googlegroups.com> Hello, I wish to know whether I should delete objects created on the fly via the "del obj" statement. I noticed the RAM usage increased whenever the application is being run for a long time. I am creating lots of objects (messages) on the fly for communication between threads. Rather than having python's gc to do the work, does it make a difference if I force a deletion? Thanks. From python at jayloden.com Wed Aug 1 18:13:16 2007 From: python at jayloden.com (Jay Loden) Date: Wed, 01 Aug 2007 18:13:16 -0400 Subject: Filemaker interactions In-Reply-To: <1186004514.108975.119380@e9g2000prf.googlegroups.com> References: <1186004514.108975.119380@e9g2000prf.googlegroups.com> Message-ID: <46B1057C.8090207@jayloden.com> Ian Witham wrote: > Hello, > > I'm hoping someone here can put me on the right track with some broad > concepts here. > > What I am hoping to achieve is a simple HTML page to be served over > our company LAN, into which the users (Real Estate Agents) can enter a > property address or reference number. > > My next thought was to have a Python CGI script query our filemaker > database of property listings, construct a PDF from the relevant > information, and finally return this PDF to the user. > > At no stage do I want the user to have unfettered access to the > database or the ability to alter/delete records. > > My question is: what is the most appropriate way for my script to > interact with Filemaker? Can this be done with Filemaker Pro 6? > > According to the Filemaker Help, the "Local Data Access Companion" > shares the FileMaker Pro database with ODBC-compliant applications on > the same computer. Is this the right option? > > Can my CGI script be an ODBC client? How? Would it need to be > Filemaker specific code or does ODBC have a standardised format? > > I'm grateful for any advice and a nudge in the right direction. > > Ian. I don't know if this helps, but there is a PyFileMaker module for Python for interacting with FileMaker: http://www.sourcefiles.org/Programming/Development/Modules/Python/PyFileMaker-1.2a4.zip That seems to be the only still working link to the module I can find, so I'm guessing it's not in active development. -Jay From mobilendd at gmail.com Sat Aug 18 04:57:27 2007 From: mobilendd at gmail.com (mobilendd at gmail.com) Date: Sat, 18 Aug 2007 08:57:27 -0000 Subject: Guitars, amps, tabs and more!! Message-ID: <1187427447.182008.26540@w3g2000hsg.googlegroups.com> Reviews of latest models of best guitars, fender, gibson, yamaha, and many more, with pictures and prices. http://pro-guitars.blogspot.com/ And if you want to win a free guitar go here http://freeguitars.blogspot.com/ From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Aug 14 03:37:05 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 14 Aug 2007 09:37:05 +0200 Subject: Module imports during object instantiation In-Reply-To: References: <46c00f2d$0$298$426a34cc@news.free.fr> Message-ID: <46c15b9e$0$433$426a34cc@news.free.fr> Ritesh Raj Sarraf a ?crit : > Bruno Desthuilliers wrote: > >> Ritesh Raj Sarraf a ?crit : >>> if lock is None or lock != 1: >>> self.DispLock = False >>> else: >>> self.DispLock = threading.Lock() >>> self.lock = True >>> >>> if os.name == 'posix': >>> self.platform = 'posix' >>> self.color = get_colors() >>> >>> elif os.name in ['nt', 'dos']: >>> self.platform = 'microsoft' >>> >>> try: >>> import SomeModule >>> except ImportError: >>> self.Set_Flag = None >>> >>> if self.Set_Flag is not None: >>> self.color = SomeModule.get_colors_windows() >>> >>> else: >>> self.platform = None >>> self.color = None >>> >>> When I create an object the "import" part never gets executed. Is there a >>> reason behind it ? >> what does "print os.name" yields ? > > On Windows: nt > On Linux: posix Mmm... I guess you didn't understood my question. I do know the os module. You assert the "import" is never executed. Since it's only executed on a non-posix platform, I asked on what platform you where testing. > >>> I mean I'd like to keep my class as independent as I want. So that when >>> later I need to use it somewhere else, I don't need to know if it depends >>> on any modules. >> > >> >> Then pass the module to the initializer. Python's modules are objects... >> > > Yes, that's an option. But is that the only one? No. > To me it looks like an ugly way of doing. Really ? Why so ? You say you want to keep your class "as independant" (you don't say from what, but...). Can you imagine a way to get less coupling than passing appropriate parameters to the initializer ? From Dominic at PLEASEASK.co.uk Tue Aug 14 08:59:16 2007 From: Dominic at PLEASEASK.co.uk (special_dragonfly) Date: Tue, 14 Aug 2007 13:59:16 +0100 Subject: Class problems. Message-ID: <46c1a34a$0$54289$7b0f0fd3@mistral.news.newnet.co.uk> Hello, I'm having problems retrieving data I think I've put into my program. I have a class and a function. I'm reading in from a personally made text file of the data needed for the class. The FieldsDictionary needs to be accesable outside the function, but my problem is this: the print FieldsDictionary[key].Fieldname (which I should have just created because of the line above), returns: AttributeError: 'list' object has no attribute 'Fieldname' am I just accessing it wrongly? I was under the impression that Fields Dictionary should contain a key referencing to a list of instances of the class. i.e. FieldsDictionary{key:[instance1, instance2, instance 3]} Is this not what I've programmed? class FieldClass(object): def __init__(self,Fieldname="",Fieldlength=0,Type=["A","S","N"],Location=["D","C","L","H","TBA"]): self.Fieldname=Fieldname self.Fieldlength=Fieldlength self.Type=Type self.Location=Location def EnterDictionary(FieldsDictionary,key,myfile,FIELD_QUANTITY_OFFSET,LINE_START,LINE_END): data=myfile.readline().strip() for i in range(int(data[FIELD_QUANTITY_OFFSET:])): args =myfile.readline().strip()[LINE_START:LINE_END].split(",") print args FieldsDictionary.setdefault(key, []).append(FieldClass(*args)) print FieldsDictionary[key].Fieldname From steve at holdenweb.com Sun Aug 12 17:14:36 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 12 Aug 2007 17:14:36 -0400 Subject: cgi and headers In-Reply-To: <49261.74.2.36.140.1186952205.squirrel@mail.el.net> References: <49261.74.2.36.140.1186952205.squirrel@mail.el.net> Message-ID: kalin mintchev wrote: > hi there... > > i'm starting to work with python cgi scripts using ajax. > one problem i have is that the cgi module doesn;t do (apparently) anything > without the -- print "Content-type: text/html\n" -- line in the script. > > the issue is that the output of the script has to be an xml file and not > an html. it's not really a problem for any normal browser but the retarded > explorer thing doesn;t process the xml unless it gets back the xml header. > > so my scripts work fine on mozilla but not in explorer because of the > missing xml header. > > what would be the correct solution for this? > > thanks.... > > > try "text/xml" or "text/html+xml" as content type. FWIW IE 6 actually required an extension of ".xml" on the output page to consider the page content to be XML, IIRC. IE 7 may be less broken, I haven't tried it much yet. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From DustanGroups at gmail.com Thu Aug 9 18:33:52 2007 From: DustanGroups at gmail.com (Dustan) Date: Thu, 09 Aug 2007 22:33:52 -0000 Subject: programmatically define a new variable on the fly In-Reply-To: <1186698608.818912.180370@e16g2000pri.googlegroups.com> References: <1186697500.024593.303820@x35g2000prf.googlegroups.com> <1186698608.818912.180370@e16g2000pri.googlegroups.com> Message-ID: <1186698832.142206.301310@i13g2000prf.googlegroups.com> On Aug 9, 5:30 pm, Dustan wrote: > given the > variables data (the dictionary), name (in your example, 'g') and > *size* (in your example, 99), you can add it data as shown: erm... make that: given the variables data (the dictionary), name (in your example, 'g') and size (in your example, 99), you can add it to data as shown: From ptmcg at austin.rr.com Tue Aug 7 09:24:24 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 07 Aug 2007 06:24:24 -0700 Subject: step through .py file in a .NET application written in C# in Visual Studio In-Reply-To: <1186438925.541501.235800@g4g2000hsf.googlegroups.com> References: <1186438925.541501.235800@g4g2000hsf.googlegroups.com> Message-ID: <1186493064.496160.296460@b79g2000hse.googlegroups.com> On Aug 6, 5:22 pm, Bo wrote: > Hello All, > > I am experimenting IronPython in Visual Studio. Here is what I have, > what I did and what I want > > 1. I have installed Visual Studio SDK 4.0 according to this bloghttp://blogs.msdn.com/aaronmar/archive/2006/02/16/a-bit-more-on-ironp... > > If I run Visual Studio under Experimental Hive, a Python file opened > is color coded. > > 2. Also, my computer has apparently installed some IronPython DLL > because my Visual Studio can recoginize the following class: > IronPython.Hosting.PythonEngine. > > If I declare something like the following in Visual Studio: > > public static class MyPythonClass { > private static IronPython.Hosting.PythonEngine MY_ENGINE; > //suppose I have created an instance of PhythonEngine and assigned > to MY_ENGINE > ............ > > } > > If I do "Go to Definition" of PythonEngine, I can navigate to the > Definition of PythonEngine, but it is from MetaData. > > 3. In my .NET application (written in C#) , I can invoke the > execution of an external python file using something like: > MyPythonClass.MY_ENGINE.ExecuteFile("myPythonFileWithAbsolutePath.py") > > The python file (myPythonFileWithAbsolutePath.py) can be executed all > right, but I want to step through it to debug it. Any suggestions on > how to do it? > > Thanks a bunch. > > Bo Um, make sure you compile with debug? I have coded in Boo, which is very Python-like, and it will step through the debugger just fine, so IP should do the same in theory. But I've not used IP, so all I can give are generic "are you sure it's plugged in?" type of suggestions. Hmm, upon rereading your post, I see that you want the debugger to step through a separate file that was executed using ExecuteFile. Unless there are some debug options on ExecuteFile, I'd say your chances are slim, since the file being executed is not really part of the image being debugged. You could also try explicitly invoking the debugger from within the file that you are loading, using (this works from Boo): System.Diagnostics.Debugger.Launch() System.Diagnostics.Debugger.Break() -- Paul From http Mon Aug 20 23:48:10 2007 From: http (Paul Rubin) Date: 20 Aug 2007 20:48:10 -0700 Subject: Retrieving a variable's name. References: <1187658202.236626.93600@50g2000hsm.googlegroups.com> Message-ID: <7xk5rpblad.fsf@ruckus.brouhaha.com> rodrigo writes: > How would I go about retrieving a variable's name (not its value)? I > want to write a function that, given a list of variables, returns a > string with each variable's name and its value, like: > > a: 100 > b: 200 > > I get the feeling this is trivial, but I have been unable to find an > answer on my own. Why do you want to do that? The reason you haven't found an answer is that it's almost certainly not the right solution to whatever problem you're trying to solve. '\n'.join('%s: %s'%(k,v) for k,v in locals().iteritems()) (untested) does something like what you're asking but I don't advise it. You should probably use a dictionary object instead. From fabioztessitore at libero.it Wed Aug 29 16:44:23 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 29 Aug 2007 20:44:23 GMT Subject: cgi References: <46d5c01b$0$36438$4fafbaef@reader5.news.tin.it> Message-ID: <46d5daa7$0$36441$4fafbaef@reader5.news.tin.it> Are you sure your script is in the right dir? On my home computer, php script will work in /var/www but my python script need an other dir to work properly (i don't remember which now ;-)) bye From aleax at mac.com Sat Aug 11 01:17:09 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 10 Aug 2007 22:17:09 -0700 Subject: Something in the function tutorial confused me. References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <1186424693.529497.217040@w3g2000hsg.googlegroups.com> <46B8626A.2070303@bigfoot.com> <5hsoi3F3mlni2U1@mid.individual.net> <5hv705F3mk67nU1@mid.individual.net> Message-ID: <1i2nhnv.2y00l5173lfbbN%aleax@mac.com> greg wrote: > Steve Holden wrote: > > > For some reason your reply got right up my nose, > > I'm sorry about that. Sometimes it's hard to judge the > level of experience with Python that a poster has. In Because of this, a Google search for " " python may sometimes help; when you get 116,000 hits, as for "Steve Holden" python, that may be a reasonable indication that the poster is one of the world's Python Gurus (in fact, the winner of the 2007 Frank WIllison Award -- congratulations, Steve!!!). Alex From martin at v.loewis.de Sun Aug 5 17:20:14 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 05 Aug 2007 23:20:14 +0200 Subject: Misleading wikipedia article on Python 3? In-Reply-To: <877io9soa1.fsf@pobox.com> References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> Message-ID: <46B63F0E.8030208@v.loewis.de> >> I think you misunderstood. It's not a design goal that code works >> without modifications, yet most reasonable code will even without >> that being an explicit goal. > > I think the design goals have been fairly clear. What hasn't been > clear (to me, at least) is the practical question of the feasibility > of code working unchanged on both 2.6 and 3.0. > > http://www.python.org/dev/peps/pep-3000/ > > """There is no requirement that Python 2.6 code will run unmodified on > Python 3.0. Not even a subset. (Of course there will be a tiny subset, > but it will be missing major functionality.)""" That's a different statement, though: It is likely that code will not run unmodified on 3k. For example, print is now a statement, and many many modules use that statement somewhere; they break in 3k. However, it *is* a design goal to make 2.6 so that transition to 3k becomes simpler. That's not a 3k feature, but a 2.6 one. > Though certainly neither quote is precise enough to pin it down > formally, certainly the tone of the first quote (from the Wikipedia > article) to my ear makes it sound like (at minimum!) it will be > practical for most projects, if they do the work to support both 3.0 > and 2.6, to run simultaneously on 2.6 and 3.0 without use of a > translation tool. The second quote makes it sound like that will be > highly impractical. That picture is reinforced by what follows (in > PEP 3000): > > """ > The recommended development model for a project that needs to support > Python 2.6 and 3.0 simultaneously is as follows: That's Guido's recommendation, yes: use the 2to3 tool. There are certainly projects for which this might be the only reasonable strategy. However, whether that will be the *common* strategy remains to be seen. I personally believe that many projects won't need the 2to3 tool, if they are willing to compromise on the notations used in the source code. > So which is it? Both. > That is, will it be practical for most projects to > support 2.6 and 3.0 simultaneously, from the same codebase, without > relying on translation tools? That remains to be seen. I believe it will be, yes. Only when people start trying we will actually know. Personal preference will vary across projects; some will use the conversion tool even though they could have come up with a single-source solution, others will fight for a single-source solution even though life would have been much simpler with the conversion tool. > I'm assuming the practicalities of this > *are* clear by now to the Python 3 developers -- is that right? Not at all (at least now to me). I know what kind of changes *I* regularly do to make code run in 3k, namely, put parentheses around into the print statements. I can live with that. Whether it is practical to run, say, Django unmodified, I don't know - I have not looked into Django with that much detail, let alone tested whether it will work. Note that I'm primarily talking about pure Python here; for C code, you can get a single-source version only with a lot of #ifdefs (but again, I believe it is practical to make it work that way). > It > seems to me that if I don't understand what the Python 3 developers > expect the practicalities to be, most other interested people won't > either ("interested" in the opposite sense to "disinterested" rather > than to "uninterested"). I think comp.lang.python is then the wrong place to find out; the py3k list likely reaches more of these developers. OTOH, I don't know whether they all want to participate in a survey of their expectations... Rather than studying people's opinions, why don't you try to port your own projects to 3k, and report whether you found it practical to use a single source (assuming you would prefer such a solution for your own project)? Regards, Martin From ianare at gmail.com Mon Aug 13 01:06:51 2007 From: ianare at gmail.com (=?iso-8859-1?B?aWFuYXLp?=) Date: Mon, 13 Aug 2007 05:06:51 -0000 Subject: wx.ListBox drag and drop Message-ID: <1186981611.589404.117770@l70g2000hse.googlegroups.com> Hey all, I see plenty of drag and drop examples but they are all for wx.ListCtrl. Anyone know of examples or tutorials for wx.ListBox? Specifically, I would like to be able to drag a selection from one ListBox to another. Thanks in advance, - ianar? From bbxx789_05ss at yahoo.com Thu Aug 9 12:03:58 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 09 Aug 2007 09:03:58 -0700 Subject: wxPython before MainLoop In-Reply-To: <13bl9a75laqcm70@corp.supernews.com> References: <13bl9a75laqcm70@corp.supernews.com> Message-ID: <1186675438.241975.292360@b79g2000hse.googlegroups.com> On Aug 8, 11:25 pm, "[david]" wrote: > I'd like to refresh the display before I start the main loop. > > I have code like this: > > app = App() > app.Show() > app.long_slow_init() > app.MainLoop() > > The main frame partly loads at Show, but because the mainloop has not > started yet, the display does not update until long_slow_init() finishes. > > Alternatively, I could code > > app = App() > app.long_slow_init() > app.Show() > app.MainLoop() > > Which would give me a crisp Show, but there would be a long slow wait > before the app showed any activity at all. I would need a splash screen. > > I'd rather not have a splash screen (and I don't know how anyway). I'd > like to just make app.Show() finish correctly before running > long_slow_init. > > Is there a wx internal method that I can use to give Windows the > opportunity to finish painting the frame before I run long_slow_init()? > > Or is there a better idea? > > (david) I don't see my original post, so here it is again.... You can use another thread to execute long_slow_init(): -------------- import wx import threading import time class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "My Window") panel = wx.Panel(self, -1) button = wx.Button(panel, -1, "click me, quick!", pos=(40, 40)) self.Bind(wx.EVT_BUTTON, self.onclick) def onclick(self, event): print "button clicked" def receive_result(self, result): print "Hey, I'm done with that long, slow initialization." print "The result was:", result class MyApp(wx.App): def __init__(self): wx.App.__init__(self, redirect=False) def OnInit(self): #called by wx.Python the_frame = MyFrame() the_frame.Show() t = MyThread(the_frame) t.start() #calls t.run() return True class MyThread(threading.Thread): def __init__(self, a_frame): threading.Thread.__init__(self) self.frame_obj = a_frame def run(self): result = self.long_slow_init() wx.CallAfter(self.frame_obj.receive_result, result) #CallAfter() calls the specified function with the #specified argument when the next pause in execution #occurs in this thread: def long_slow_init(self): print "starting long_slow_init()..." time.sleep(6) result = 20.5 return result app = MyApp() app.MainLoop() From tooru_honda at fast-mail.org Fri Aug 24 03:38:51 2007 From: tooru_honda at fast-mail.org (tooru honda) Date: Fri, 24 Aug 2007 15:38:51 +0800 Subject: Does shuffle() produce uniform result ? Message-ID: Hi, I have read the source code of the built-in random module, random.py. After also reading Wiki article on Knuth Shuffle algorithm, I wonder if the shuffle method implemented in random.py produces results with modulo bias. The reasoning is as follows: Because the method random() only produces finitely many possible results, we get modulo bias when the number of possible results is not divisible by the size of the shuffled list. 1. Does shuffle() produce uniform result ? 2. If not, is there a fast and uniform shuffle() available somewhere ? Thanks ! -tooru honda From ocollioud at gmail.com Wed Aug 22 03:11:39 2007 From: ocollioud at gmail.com (olive) Date: Wed, 22 Aug 2007 07:11:39 -0000 Subject: Server-side scripting in python In-Reply-To: <1187755436.972359.293360@i13g2000prf.googlegroups.com> References: <1187614732.519547.296020@j4g2000prf.googlegroups.com> <1187755436.972359.293360@i13g2000prf.googlegroups.com> Message-ID: <1187766699.291306.3490@z24g2000prh.googlegroups.com> On 22 ao?t, 06:03, Nagarajan wrote: > I wanted to explore web programming facet of python. The problem at my > hand is to develop an email web client. I would do that with the help of Django (www.djangoproject.com groups.google.com/group/django-users) for the server side and JQuery (www.jquery.com groups.google.com/group/jquery-en) for the client side. Olive. From samushack at gmail.com Sat Aug 25 21:36:15 2007 From: samushack at gmail.com (samushack at gmail.com) Date: Sat, 25 Aug 2007 18:36:15 -0700 Subject: simple spider in python In-Reply-To: <1187902164.596545.101050@q3g2000prf.googlegroups.com> References: <1187876014.845912.236690@e9g2000prf.googlegroups.com> <1187879398.007797.128510@i13g2000prf.googlegroups.com> <1187880988.813113.20350@l22g2000prc.googlegroups.com> <1187890751.871660.275320@z24g2000prh.googlegroups.com> <1187902164.596545.101050@q3g2000prf.googlegroups.com> Message-ID: <1188092175.007320.271800@57g2000hsv.googlegroups.com> On Aug 23, 4:49 pm, gmcalen... at gmail.com wrote: > well, i think that they deserve people moving toward yahoo's API... > check this out:http://pysearch.sourceforge.net/ > it's basically the same thing as pygoogle BUT working with google's > competitor. it seems like internet has its own built-in antibodyes! > ^__^ > > cheers! Had not seen this project before. Looks helpful, thanks! (If only Yahoo! Search did not suck in comparison to Google's..., but better than nothing:-) From skip.montanaro at gmail.com Tue Aug 14 06:46:55 2007 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Tue, 14 Aug 2007 03:46:55 -0700 Subject: Best programs written completly in Python In-Reply-To: References: Message-ID: <1187088415.483615.114170@m37g2000prh.googlegroups.com> On Aug 5, 5:14 am, Franz Steinh?usler wrote: > Hello NG, > > wWhat are the best programs in your opinion, written entirly > in pyhton, divided into categories like: > a) Games > b) Utilities/System > c) Office > d) Web/Newsreader/Mail/Browser > ... Not mentioned so far, here or on the Applications wiki page, is SpamBayes, an excellent spam filter: . It supports POP3 and IMAP, and has a plugin for Outlook. Another group has improved SpamBayes integration with Thunderbird by developing a TBird extension called ThunderBayes. Skip From pkharpenn at shaw.ca Mon Aug 6 21:50:21 2007 From: pkharpenn at shaw.ca (Karin and Patrick) Date: Mon, 06 Aug 2007 20:50:21 -0500 Subject: The Secret Way To Get Wealthy Message-ID: <000201c7d895$50ab9fa0$6501a8c0@wp.shawcable.net> Please send me the information on this program. Thanks Patrick -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Mon Aug 27 14:44:18 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 27 Aug 2007 18:44:18 GMT Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com> <1187898049.734696.9500@l22g2000prc.googlegroups.com> <13csoronscqp7d2@corp.supernews.com> <1188090322.663217.102750@22g2000hsm.googlegroups.com> <13d4bucfm4m1lc4@corp.supernews.com> <13d4gjm3qq0lt7c@corp.supernews.com> Message-ID: On 2007-08-27, Neil Cerutti wrote: > This sort of suggests a direct solution: > > for i in xrange(self.parent.GetPageCount()): > if i >= self.parent.GetPageCount(): > break > # do stuff > > At least that way you're spared the manual manipulation of i. On second thought, that last suggestion is flawed, as a growing page count would be ignored. Please ignore. -- Neil Cerutti Whenever I see a homeless guy, I always run back and give him money, because I think: Oh my God, what if that was Jesus? --Pamela Anderson From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Aug 9 06:50:50 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 09 Aug 2007 12:50:50 +0200 Subject: Help with Dictionaries and Classes requested please. In-Reply-To: <46bacf1b$0$54289$7b0f0fd3@mistral.news.newnet.co.uk> References: <46bacae3$0$89254$7b0f0fd3@mistral.news.newnet.co.uk> <46bacf1b$0$54289$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <46baf183$0$433$426a74cc@news.free.fr> special_dragonfly a ?crit : (snip) > I've managed to solve the problem, I really was just being a dunce. Here's > how incase anyone is wondering: > > class MyClass: > def __init__(self): > name="" > dict={} > dict[0]=[] > dict[0].append(MyClass()) > dict[0][0].name="Hello" > print dict[0][0].name > > I'm sorry if I've wasted anyones time, although if there's a better way of > doing the above I'd still be interested to know. # unless you need pre 2.3.x compat, better to use newstyle classes class MyClass(object): # use the initializer to initialize your instance def __init__(self, name=''): # the use of 'self' is mandatory, else you only have a local var self.name = name # don't use builtin names as identifiers - unless you really want to # shadow the builtins d = {0:[MyClass('hello')} d[0].append(MyClass('goodbye')) d.setdefault(1, []).append(MyClass('Yo')) print d HTH From http Mon Aug 6 11:20:20 2007 From: http (Paul Rubin) Date: 06 Aug 2007 08:20:20 -0700 Subject: Tkinter or wxpython? References: <1186410331.905174.21370@q3g2000prf.googlegroups.com> <7xps204tin.fsf@ruckus.brouhaha.com> Message-ID: <7xlkcopu4r.fsf@ruckus.brouhaha.com> "Chris Mellon" writes: > No native look and feel - constrained by the browser. Might or might not matter for the application, especially considering that tkinter is part of the discussion. > No control over browser UI idioms. I had to write this post twice > because the text control lost focus and I hit backspace, going back in > the history and losing my work. Sounds weird, I'm used to having stuff in text boxes stay in the browser, and why did backspace have that effect anyway? > No native integration - no "open file", no "browse the filesystem", no > rich drag and drop, no copy/paste. File i/o and file system browsing are available from javascript if the user grants permission. File system browsing for the limited purpose of file upload is available in regular html. Copy/paste of ordinary text is always available. However, this type of requirement is what I mean by a "good reason" to write a desktop gui. It applies to some applications, not all. > No or poor dialogs. Poor multiple window support. Might or might not matter depending on the application. Most dialogs can be done with html. Multiple windows are evil most of the time, and should instead by done with multiple panes or cells in a single window. > More platforms to develop on and test with. Compared to a desktop app? I don't think so. > Limited to CSS box model for layout. Might or might not matter depending on the application. If you're doing a consumer app that has to look slick, you have no choice but to use something like wxwidgets (tkinter won't cut it either). If you're doing a special purpose office or industrial app, slickness isn't important. > The web is a terrible application platform. There is not a single web > application in existence which has even half the UI functionality of a > rich client application. Some of us consider simple interfaces with consistent, familiar (i.e. web) elements to be a good thing. Fancy client interfaces are ok if you feel you need to make a style statement, but are often unnecessary if you just want to get something done. > There are some (even many) applications for which the benefit of > global access and easy deployment makes up for the lack in > functionality, but statements like "At this point I think nobody > should write desktop gui apps without a good reason" are simply > ludicrously misguided. Well, I don't say that good reasons don't exist, I just see a lot of desktop apps that could be done just as well as web apps, i.e. for those, the good reason didn't exist. From khemkaamit at gmail.com Tue Aug 21 09:28:25 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Tue, 21 Aug 2007 18:58:25 +0530 Subject: Logging module gives duplicate log entries In-Reply-To: <1187702248.203917.188570@k79g2000hse.googlegroups.com> References: <1187702248.203917.188570@k79g2000hse.googlegroups.com> Message-ID: <1360b7230708210628q3b6adad1xbea25ac06b5e1cfd@mail.gmail.com> On 8/21/07, Shiao wrote: > Hi, > I am getting duplicate log entries with the logging module. > > The following behaves as expected, leading to one log entry for each > logged event: > > logging.basicConfig(level=logging.DEBUG, filename='/tmp/foo.log') > > But this results in two entries for each logged event: > > applog = logging.getLogger() > applog.setLevel(logging.DEBUG) > hdl = logging.FileHandler('/tmp/foo.log') > applog.addHandler(hdl) > You need to remove the handler from the logging object # remove the handler once you are done applog.removeHandler(hdl) Cheers, amit. ---- Amit Khemka website: www.onyomo.com wap-site: www.owap.in Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From kyosohma at gmail.com Mon Aug 6 14:43:36 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 06 Aug 2007 18:43:36 -0000 Subject: Importing * From a Package In-Reply-To: References: Message-ID: <1186425816.527991.204760@i13g2000prf.googlegroups.com> On Aug 6, 9:06 am, "Patrick Doyle" wrote: > Reading through the Python tutorial, I got to section 6.4.1, > "Importing * From a Package", which states: > > "If __all__ is not defined, the statement from Sound.Effects import * > does not import all submodules from the package Sound.Effects into the > current namespace; ..." > > It then goes on to state: > > "[It] imports whatever names are defined in the package [including] > any submodules of the package that were explicitly loaded by previous > import statements." > > I am curious to learn the rationale for this behavior, since it just > caught me by surprise (hence the reason I was pouring over the > tutorial document in such detail :-)) > > Thus far, everything in Python has seemed very intuitive to me, > however the behavior of "from package import *" baffles me. > > So I figured I'd ask -- why does Python behave this way. > > (And now, I'm going to do some code cleanup :-)) > > --wpd The only module I know of that most people tell you to do a "from x import *" is Tkinter. I think that's pretty dumb myself. If you don't want to type some module's name out, then do something like "import Tkinter as tk". Mike From jeremy+complangpython at jeremysanders.net Fri Aug 17 12:08:29 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Fri, 17 Aug 2007 17:08:29 +0100 Subject: best GUI library for vector drawing program References: <1187357244.883516.79840@j4g2000prf.googlegroups.com> Message-ID: chewie54 wrote: > What would be the best cross-platform GUI library to use for a vector > based CAD program ( something like Visio on Windows ) WxWidgets, > Tk, PyQt, Java Swing, Java SWT,???? I need the capibility to > draw and edit in a window that looks like a page of paper so WYSIWYG > is very important, and I need to save the drawings in vector based > file formats like PS, EPS, SVG, as well as image formats like jpg, > png, and gif. Also, the images need to be high resolution so that > they can be pasted into various other programs in Windows OS, and > Linux OS, and the Mac OS. PyQt/Qt4 is capable of that (SVG export was added in Qt4.3). I have a graph drawing application based around it (Veusz). If you base everything around QPainter, you'll be able to write to any of those output formats (including eps and pdf), and bitmaps. Antialiasing is optional for bitmap formats. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From steveo at syslang.net Thu Aug 23 16:48:51 2007 From: steveo at syslang.net (Steven W. Orr) Date: Thu, 23 Aug 2007 16:48:51 -0400 (EDT) Subject: Problem with dynamic creation of classes. Message-ID: I have a base class B and a derived class D which inherits from B. I also have a D2 class which inherits from D. D is used as a base class for most of my generated classes. I have a "special" class which inherits from D2 because I need to override a couple of its methods. Anything based on D2 will inherit Encode and Decode from B. class D(b.B): def __init__(self, data, timestamp = None): b.B.__init__(self, data) self.timestamp = timestamp class D2( D ): def __init__(self, data, timestamp = None): DS.__init__(self, data, timestamp) def Decode(self): pass def Encode(self): pass The generated classes come from this loop: for m in mdefs: mdef = mdefs[m] name = mdef['name'] + fbase if mdef.has_key('baseclass'): base_class_seq = mdef['baseclass'] else: base_class_seq = DEFAULT_BASE_CLASS nclass = new.classobj( name, base_class_seq, globals() ) base_class_seq is either going to be (D,) or (D2,) After I get through the class generation, I want to say globals()['IFRAMED2'].Decode = dynDecode globals()['IFRAMED2'].Encode = dynEncode for the one class that inherited from D2. If I do that, I find that *all* classes that call Encode or Decode are all calling dyn{En,De}code (which is exactly what I *don't* want). So I looked at the id values after class generation. print 'IFRAMED2.Encode = ', IFRAMED2.Encode, id(IFRAMED2.Encode) print 'SNRMD.Encode = ', SNRMD.Encode, id(SNRMD.Encode) print 'IFRAMED2 = ', IFRAMED2, id(IFRAMED2) print 'SNRMD = ', SNRMD, id(SNRMD) IFRAMED2.Decode = dynDecode IFRAMED2.Encode = dynEncode print 'IFRAMED2.Encode = ', IFRAMED2.Encode, id(IFRAMED2.Encode) print 'SNRMD.Encode = ', SNRMD.Encode, id(SNRMD.Encode) Here's the output: IFRAMED2.Encode = 1100623660 SNRMD.Encode = 1100623660 IFRAMED2 = d.IFRAMED2 1076299644 SNRMD = d.SNRMD 1103202364 IFRAMED2.Encode = 1100623660 SNRMD.Encode = 1100623660 So it looks like the IFRAMED2 class which inherits from D2 is starting out with the same id value for Encode as SNRMD which inherits from D, even though D2 defines its own Encode method. Is it me of is it the interpreter doing something wrong? -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From erik at myemma.com Tue Aug 28 11:08:06 2007 From: erik at myemma.com (Erik Jones) Date: Tue, 28 Aug 2007 10:08:06 -0500 Subject: Python Classes In-Reply-To: References: Message-ID: <8AC0DE08-89C7-4647-93FE-CC9ED6102C98@myemma.com> On Aug 28, 2007, at 12:04 AM, Lamonte Harris wrote: > How come you have to set the initialized created variables to equal > the parameters, shouldn't that be default? > > class testing: > def __init__(self,testing): > self.testing = testing > x = testing("testing") > print x.testing > > > How come self.testing = testing > > Can someone explain that in more detail, just confused on why you > have to set it up like that. > -- Simple Answer: Because language should never set variable values "by default". That's what programmers are for. There may be application domains where *some* defaulting behavior makes sense, but that's what frameworks and DSLs are for. Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From borreguero at gmail.com Thu Aug 23 14:46:47 2007 From: borreguero at gmail.com (jmborr) Date: Thu, 23 Aug 2007 18:46:47 -0000 Subject: how to select between two file libraries with same name? Message-ID: <1187894807.228812.266270@q5g2000prf.googlegroups.com> Imagine my file one.py contains the statement import two If there's a two.py in same directory as one.py, then this file will be loaded. However, I want to load a different file named also two.py, say file ~username/mypythonlib/two.py How can I select between the two two.py files ? -jose From arkanes at gmail.com Wed Aug 1 12:16:21 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 1 Aug 2007 11:16:21 -0500 Subject: What is the "functional" way of doing this? In-Reply-To: <46AF80AA.7030809@bigfoot.com> References: <1185835690.530367.66600@m37g2000prh.googlegroups.com> <1185838434.596591.132640@d30g2000prg.googlegroups.com> <7x3az5wjfa.fsf@ruckus.brouhaha.com> <1185839713.412656.242950@i13g2000prf.googlegroups.com> <46AF80AA.7030809@bigfoot.com> Message-ID: <4866bea60708010916p6d8b89e7x447ff78a827c2af0@mail.gmail.com> On 7/31/07, Ricardo Ar?oz wrote: > Steven D'Aprano wrote: > > On Tue, 31 Jul 2007 09:01:42 -0300, Ricardo Ar?oz wrote: > > > >> Considering I am a beginner I did a little test. Funny results too. The > >> function I proposed (lists1.py) took 11.4529998302 seconds, while the > >> other one (lists2.py) took 16.1410000324 seconds, thats about 40% more. > >> They were run in IDLE from their own windows (F5). > > > > [snip code] > > > > You may find that using the timeit module is better than rolling your own > > timer. > > > >>>> def recursive_func(n): > > ... if n > 0: > > ... return [n % 26] + recursive_func(n/26) > > ... else: > > ... return [] > > ... > >>>> def generator_func(n): > > ... def mseq(n): > > ... while n > 0: > > ... n, a = divmod(n, 26) > > ... yield a > > ... return list(mseq(n)) > > ... > >>>> import timeit > >>>> N = 10**6+1 > >>>> timeit.Timer("recursive_func(N)", > > ... "from __main__ import N, recursive_func").repeat() > > [16.48972487449646, 17.000514984130859, 16.520529985427856] > >>>> timeit.Timer("generator_func(N)", > > ... "from __main__ import N, generator_func").repeat() > > [27.938560009002686, 28.970781087875366, 23.977837085723877] > > > > > > If you're going to compare speeds, you should also test this one: > > > >>>> def procedural_func(n): > > ... results = [] > > ... while n > 0: > > ... n, a = divmod(n, 26) > > ... results.append(a) > > ... return results > > ... > >>>> timeit.Timer("procedural_func(N)", > > ... "from __main__ import N, procedural_func").repeat() > > [15.577107906341553, 15.60145378112793, 15.345284938812256] > > > > > > I must admit that I'm surprised at how well the recursive version did, and > > how slow the generator-based version was. But I'd be careful about drawing > > grand conclusions about the general speed of recursion etc. in Python from > > this one single example. I think this is simply because the examples tried > > make so few recursive calls. Consider instead an example that makes a few > > more calls: > > > >>>> N = 26**100 + 1 > >>>> > >>>> timeit.Timer("recursive_func(N)", > > ... "from __main__ import N, recursive_func").repeat(3, 10000) > > [7.0015969276428223, 7.6065640449523926, 6.8495190143585205] > >>>> timeit.Timer("generator_func(N)", > > ... "from __main__ import N, generator_func").repeat(3, 10000) > > [3.56563401222229, 3.1132731437683105, 3.8274538516998291] > >>>> timeit.Timer("procedural_func(N)", > > ... "from __main__ import N, procedural_func").repeat(3, 10000) > > [3.3509068489074707, 4.0872640609741211, 3.3742849826812744] > > > > > > Yup! As soon as the size of the list increases the generator function > gets better (50% in my tests). But it's interesting to note that if the > list is within certain limits (I've tested integers (i.e. 2,100,000,000 > => 7 member list)) and you only vary the times the funct. is called then > the recursive one does better. > > Not especially surprising. Suspending and resuming a generator is naturally more expensive than a single function call. The advantages of generators are time/space tradeoffs, greater expressiveness, and state preservation (not used here). From horpner at yahoo.com Tue Aug 7 14:18:43 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 07 Aug 2007 18:18:43 GMT Subject: re.sub does not replace all occurences References: <1186507704.440408.20630@57g2000hsv.googlegroups.com> Message-ID: On 2007-08-07, Christoph Krammer wrote: > Hello everybody, > > I wanted to use re.sub to strip all HTML tags out of a given string. I > learned that there are better ways to do this without the re module, > but I would like to know why my code is not working. I use the > following: > > def stripHtml(source): > source = re.sub("[\n\r\f]", " ", source) > source = re.sub("<.*?>", "", source, re.S | re.I | re.M) > source = re.sub("&(#[0-9]{1,3}|[a-z]{3,6});", "", source, re.I) > return source > > But the result still has some tags in it. When I call the > second line multiple times, all tags disappear, but since HTML > tags cannot be overlapping, I do not understand this behavior. > There is even a difference when I omit the re.I (IGNORECASE) > option. Without this option, some tags containing only capital > letters (like ) were kept in the string when doing one > processing run but removed when doing multiple runs. > > Perhaps anyone can tell me why this regex is behaving like > this. >>> import re >>> help(re.sub) Help on function sub in module re: sub(pattern, repl, string, count=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a callable, it's passed the match object and must return a replacement string to be used. And from the Python Library Reference for re.sub: The pattern may be a string or an RE object; if you need to specify regular expression flags, you must use a RE object, or use embedded modifiers in a pattern; for example, "sub("(?i)b+", "x", "bbbb BBBB")" returns 'x x'. The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous match, so "sub('x*', '-', 'abc')" returns '-a-b-c-'. In other words, the fourth argument to sub is count, not a set of re flags. -- Neil Cerutti From cai.haibin at gmail.com Thu Aug 2 04:27:02 2007 From: cai.haibin at gmail.com (james_027) Date: Thu, 02 Aug 2007 08:27:02 -0000 Subject: a dict trick In-Reply-To: References: <1186036331.304916.304020@e9g2000prf.googlegroups.com> Message-ID: <1186043222.732234.152550@d30g2000prg.googlegroups.com> Hi, what if we're not dealing with dict? is there a pythonic way of doing ternary? the bool ? x:y Thanks james From bbxx789_05ss at yahoo.com Fri Aug 17 01:30:19 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 16 Aug 2007 22:30:19 -0700 Subject: using super() to call two parent classes __init__() method Message-ID: <1187328619.039289.244900@g4g2000hsf.googlegroups.com> When I run the following code and call super() in the Base class's __init__ () method, only one Parent's __init__() method is called. class Parent1(object): def __init__(self): print "Parent1 init called." self.x = 10 class Parent2(object): def __init__(self): print "Parent2 init called." self.y = 15 class Base(Parent1, Parent2): def __init__(self): super(Base, self).__init__() self.z = 20 b = Base() --output:-- Parent1 init called. From arkanes at gmail.com Mon Aug 6 10:58:34 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 6 Aug 2007 09:58:34 -0500 Subject: Tkinter or wxpython? In-Reply-To: <7xps204tin.fsf@ruckus.brouhaha.com> References: <1186410331.905174.21370@q3g2000prf.googlegroups.com> <7xps204tin.fsf@ruckus.brouhaha.com> Message-ID: <4866bea60708060758t634d7b87va03213e85b6b0c90@mail.gmail.com> On 06 Aug 2007 07:39:12 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > kyosohma at gmail.com writes: > > I've read that Tkinter doesn't scale well if you're writing complex > > GUIs. I haven't been able to test this hypothesis though. However, > > since I had to rewrite VBA apps into Python, to get the right "look > > and feel" I needed the widgets that wxPython provided. Since I started > > out with C++, I find wxPython better than Tkinter, but it's all pretty > > subjective. Try them both! > > Tkinteger (dang, I always end up typing it that way, I won't even > bother fixing the error) is easy to use for simple gui's, and it's > part of the standard python distro which for me is a big advantage (no > extra crap to download). However, the widget set is rather ugly and > doesn't blend in well with anyone's native widgets; the widget > selection itself is rather narrow, and I think kyosohma may be right > that it doesn't scale well to complex gui's. I've looked at the code > for IDLE's gui and it's terrifying. > > At this point I think nobody should write desktop gui apps without a > good reason. There is a fairly flexible and easy to program gui > already running on almost every desktop, namely the web browser. > Before you write a gui using some client side toolkit, ask yourself > whether you can instead embed a web server in your application and > write an HTML gui. That approach is not always the answer, but it has > considerable advantages when you can do it that way. Some disadvantages of the web based platform: No native look and feel - constrained by the browser. No control over browser UI idioms. I had to write this post twice because the text control lost focus and I hit backspace, going back in the history and losing my work. No native integration - no "open file", no "browse the filesystem", no rich drag and drop, no copy/paste. No or poor dialogs. Poor multiple window support. More platforms to develop on and test with. Limited to CSS box model for layout. You can mitigate some of these constraints if you *require* the local web browser technique, rather than supporting local or remote access. You can mitigate more if you write your own browser host (along the lines of the dashboard in OS X), but then you get to write 3 applications instead of one. The web is a terrible application platform. There is not a single web application in existence which has even half the UI functionality of a rich client application. There are some (even many) applications for which the benefit of global access and easy deployment makes up for the lack in functionality, but statements like "At this point I think nobody should write desktop gui apps without a good reason" are simply ludicrously misguided. From ptmcg at austin.rr.com Tue Aug 28 23:06:47 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 28 Aug 2007 20:06:47 -0700 Subject: Newbie question - sorting a slice In-Reply-To: <1188355395.424913.90480@19g2000hsx.googlegroups.com> References: <1188355395.424913.90480@19g2000hsx.googlegroups.com> Message-ID: <1188356807.796673.231820@y42g2000hsy.googlegroups.com> On Aug 28, 9:43 pm, hwg wrote: > I've searched the group and didn't see the answer to this... > > Why doesn't this work?: > > >>> letters = ['d', 'a', 'e', 'c', 'b'] > >>> letters[1:3].sort() > > This returns None. > > Why? letters[1:3] is ['a', 'e', 'c'] Sorting that should return > ['a', 'c', 'e'] > > hwg There are a couple of flaws in your example. letters[1:3] is not ['a', 'e', 'c'], but is just ['a','e']. The elements of a slice start with the lower-bound INclusive (zero-based, so this is 'a'), up to the upper bound EXclusive (up to, but NOT INCLUDING 'c'). The slice returns a copy of the selected elements. .sort() does an in-place sort, and returns None. You may instead use the builtin function sorted(), as in: sorted(letters[1:4]) which in fact DOES return ['a', 'c', 'e']. What your example had done was: 1. choose 2 elements of a list and copy them to a temporary list 2. sort the list in place 3. return None 4. discard the temporary list, since all references to it were gone For remedial study: - study notation for slices - study the difference between list.sort() and sorted() -- Paul From richardjones at optushome.com.au Mon Aug 20 05:52:45 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Mon, 20 Aug 2007 19:52:45 +1000 Subject: Call for advice on how to start PyOpenGL! References: <1187589198.616866.280500@j4g2000prf.googlegroups.com> <5it40oF3qmpojU1@mid.uni-berlin.de> Message-ID: <46c9646d$0$31115$afc38c87@news.optusnet.com.au> Diez B. Roggisch wrote: > math2life wrote: > >> I work with python for two years, are familiar with image processing, >> but beginner on PyOpenGL and OpenGL. >> >> Any advice appreciated! > > You should check out the pyweek (http://www.pyweek.org/). There you find > pygame & OpenGL-based games, of a comprehensible size. Also, there's plenty of good opengl tutorials on the web. They all translate pretty easily into Python if they're not in Python already. For example: http://nehe.gamedev.net I highly recommend pyweek as a way of focusing on your learning task :) Richard From andrewbl at aughr.com Fri Aug 17 00:34:35 2007 From: andrewbl at aughr.com (Andrew Bloomgarden) Date: Thu, 16 Aug 2007 21:34:35 -0700 Subject: Subprocess & ffmpeg Message-ID: Hi, I'm having a problem with the subprocess module. I'm using it to run ffmpeg with the following command, where a_cmd is the command string. proc = subprocess.Popen (a_cmd,shell=True,stdout=subprocess.PIPE,universal_newlines=True,stderr= subprocess.STDOUT,stdin=subprocess.PIPE) Then, I'm trying to have access to the output while it's running. Just as a test, I used the following: for line in proc.stdout: print line It doesn't print out anything until ffmpeg is done executing. Now, this works with mencoder, but I have no idea why it won't work with ffmpeg. Does anyone know why this is happening? -- Andrew Bloomgarden -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Mon Aug 6 22:33:30 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 07 Aug 2007 14:33:30 +1200 Subject: regexp problem in Python References: <1186177312.117581.129910@d55g2000hsg.googlegroups.com> Message-ID: In message <1186177312.117581.129910 at d55g2000hsg.googlegroups.com>, Ehsan wrote: > I use this pattern : > "http.*?\.(wmv|3gp).*"" > > but it returns only 'wmv' and '3gp' instead of "http://www.2shared.com/ > download/1716611/e2000f22/Jadeed_Mlak14.wmv? > tsid=20070803-164051-9d637d11" What's the actual Python code that uses this regexp? My guess is, you're not using the "group" method correctly in the returned match object . From kirby.urner at gmail.com Sun Aug 5 17:04:45 2007 From: kirby.urner at gmail.com (kirby.urner at gmail.com) Date: Sun, 05 Aug 2007 21:04:45 -0000 Subject: Google message munging (was: Live editing...) In-Reply-To: <87r6moc4il.fsf@benfinney.id.au> References: <1185914335.472511.172040@m37g2000prh.googlegroups.com> <87r6moc4il.fsf@benfinney.id.au> Message-ID: <1186347885.245805.314690@q3g2000prf.googlegroups.com> > What the blazes is Google doing with messages that such a high > proportion of them come through in this painful-to-read double-wrapped > format? I'm referring to the fact that the lines appear to have been > wrapped at one length, and then each line broken again into a long and > a short line. > I entirely agree with Ben Finney's remarks. Painful for an author to see a post mangled that way too, writers being also readers. Back to the original thread (sort of): I think the deeper issue is the relationship between "shell" (REPL), "debugger" (per WingIDE 101 for example) and "runtime" ala Python just crunching through a .py file. The OLPC people are pushing for exotic "live debugging" and think Python is deficient in this regard, not as a language so much as an environment (which Guido need take no responsibility for, though he often has and does). My tossing out of some ZODB-based solutions was mostly just an ice-breaker. I don't mind that it ended up prompting discussions of formatting. Anyway, back to thinking about iterator types: http://mail.python.org/pipermail/edu-sig/2007-August/008168.html ( python.next() might trigger a fork/jump to a next "live" interpreter, leaving behind "snake skin" or "ghost" interpreter available for "live" interventions? ). Kirby From joel.granados at gmail.com Tue Aug 21 06:00:52 2007 From: joel.granados at gmail.com (Joel Andres Granados) Date: Tue, 21 Aug 2007 12:00:52 +0200 Subject: IDE for Python Message-ID: <46CAB7D4.5070308@gmail.com> Hello list: I have tried various times to use an IDE for python put have always been disapointed. I haven't revisited the idea in about a year and was wondering what the python people use. I have also found http://pida.co.uk/main as a possible solution. Anyone tried it yet? suggestions. Regards Joel Andres Granados -------------- next part -------------- A non-text attachment was scrubbed... Name: joel.granados.vcf Type: text/x-vcard Size: 150 bytes Desc: not available URL: From half.italian at gmail.com Fri Aug 10 19:25:02 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Fri, 10 Aug 2007 23:25:02 -0000 Subject: Threaded Design Question In-Reply-To: References: <1186683909.797328.68770@i13g2000prf.googlegroups.com> Message-ID: <1186788302.998913.76720@d30g2000prg.googlegroups.com> On Aug 9, 9:45 pm, "Mark T" wrote: > wrote in message > > news:1186683909.797328.68770 at i13g2000prf.googlegroups.com... > > > > > Hi all! I'm implementing one of my first multithreaded apps, and have > > gotten to a point where I think I'm going off track from a standard > > idiom. Wondering if anyone can point me in the right direction. > > > The script will run as a daemon and watch a given directory for new > > files. Once it determines that a file has finished moving into the > > watch folder, it will kick off a process on one of the files. Several > > of these could be running at any given time up to a max number of > > threads. > > > Here's how I have it designed so far. The main thread starts a > > Watch(threading.Thread) class that loops and searches a directory for > > files. It has been passed a Queue.Queue() object (watch_queue), and > > as it finds new files in the watch folder, it adds the file name to > > the queue. > > > The main thread then grabs an item off the watch_queue, and kicks off > > processing on that file using another class Worker(threading.thread). > > > My problem is with communicating between the threads as to which files > > are currently processing, or are already present in the watch_queue so > > that the Watch thread does not continuously add unneeded files to the > > watch_queue to be processed. For example...Watch() finds a file to be > > processed and adds it to the queue. The main thread sees the file on > > the queue and pops it off and begins processing. Now the file has > > been removed from the watch_queue, and Watch() thread has no way of > > knowing that the other Worker() thread is processing it, and shouldn't > > pick it up again. So it will see the file as new and add it to the > > queue again. PS.. The file is deleted from the watch folder after it > > has finished processing, so that's how i'll know which files to > > process in the long term. > > > I made definite progress by creating two queues...watch_queue and > > processing_queue, and then used lists within the classes to store the > > state of which files are processing/watched. > > > I think I could pull it off, but it has got very confusing quickly, > > trying to keep each thread's list and the queue always in sync with > > one another. The easiset solution I can see is if my threads could > > read an item from the queue without removing it from the queue and > > only remove it when I tell it to. Then the Watch() thread could then > > just follow what items are on the watch_queue to know what files to > > add, and then the Worker() thread could intentionally remove the item > > from the watch_queue once it has finished processing it. > > > Now that I'm writing this out, I see a solution by over-riding or > > wrapping Queue.Queue().get() to give me the behavior I mention above. > > > I've noticed .join() and .task_done(), but I'm not sure of how to use > > them properly. Any suggestions would be greatly appreciated. > > > ~Sean > > Just rename the file. We've used that technique in a similar application at > my work for years where a service looks for files of a particular extension > to appear in a directory. When the service sees a file, in renames it to a > different extension and spins off a thread to process the contents. > > -Mark T. I ended up taking this route for the most part. The worker thread first moves the file to be processed into a temp directory, and the watch thread never knows about it again. I still had to implement my StateQueue(Queue.Queue) so I could implement a function to return all the items on the queue without popping them off. Thanks all for your great ideas. My current response to multi- threading... PITA! ~Sean From gagsl-py2 at yahoo.com.ar Fri Aug 24 00:14:04 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 24 Aug 2007 01:14:04 -0300 Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com> <1187898049.734696.9500@l22g2000prc.googlegroups.com> <13csi2tn49esmc3@corp.supernews.com> Message-ID: En Thu, 23 Aug 2007 23:54:14 -0300, bambam escribi?: > After examining your suggestion, I realised that another thing > I am interested in could be generalised: I want the complement > of the set of ports in pages, given a universal set in tempList. > Ignoring the break condition for the moment, and my problem > with int(port)/str(port), would you have offered a different solution > if I had asked for the relative complement of a small set? > > a= ['a','b','c'] > b= ['b'] > c= a-b #set theoretic difference, a\b, a.~b, ['a','c'] If you want a set - just use a set: py> a = set(['a','b','c']) py> b = set(['b']) py> c = a-b py> c set(['a', 'c']) -- Gabriel Genellina From aboudouvas at panafonet.gr Sat Aug 4 19:11:30 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Sat, 04 Aug 2007 16:11:30 -0700 Subject: Eclipse/PyDev question. In-Reply-To: <1186268730.360593.160410@22g2000hsm.googlegroups.com> References: <1186153119.391091.275860@r34g2000hsd.googlegroups.com> <1186268730.360593.160410@22g2000hsm.googlegroups.com> Message-ID: <1186269090.403527.168030@22g2000hsm.googlegroups.com> Ah, and i think that the working set of Eclipse is smaller now... From prey at cesga.es Thu Aug 30 09:20:15 2007 From: prey at cesga.es (Pablo Rey) Date: Thu, 30 Aug 2007 15:20:15 +0200 Subject: SAXParseException: not well-formed (invalid token) In-Reply-To: <46D6B9F6.2010402@web.de> References: <46D6B9F6.2010402@web.de> Message-ID: <46D6C40F.4060105@cesga.es> Hi Stefan, The xml has specified an encoding (). About the possibility that you mention to recoding the input, could you let me know how to do it?. I am sorry I am starting with Python and I don't know how to do it. Thanks by your help. Pablo On 30/08/2007 14:37, Stefan Behnel wrote: > Pablo Rey wrote: >> I am getting the following error with a XML page: >> >>> File "/home/prey/RAL-CESGA/bin/voms2users/voms2users.py", line 69, >>> in getItems >>> d = minidom.parseString(xml.read()) >>> File "/usr/lib/python2.2/site-packages/_xmlplus/dom/minidom.py", >>> line 967, in parseString >>> return _doparse(pulldom.parseString, args, kwargs) >>> File "/usr/lib/python2.2/site-packages/_xmlplus/dom/minidom.py", >>> line 954, in _doparse >>> toktype, rootNode = events.getEvent() >>> File "/usr/lib/python2.2/site-packages/_xmlplus/dom/pulldom.py", >>> line 265, in getEvent >>> self.parser.feed(buf) >>> File "/usr/lib/python2.2/site-packages/_xmlplus/sax/expatreader.py", >>> line 208, in feed >>> self._err_handler.fatalError(exc) >>> File "/usr/lib/python2.2/site-packages/_xmlplus/sax/handler.py", >>> line 38, in fatalError >>> raise exception >>> xml.sax._exceptions.SAXParseException: :553:48: not >>> well-formed (invalid token) >> >>> def getItems(page): >>> opener =urllib.URLopener(key_file=HOSTKEY,cert_file=HOSTCERT) ; >>> try: >>> xml = opener.open(page) >>> except: >>> return [] >>> >>> d = minidom.parseString(xml.read()) >>> items = d.getElementsByTagName('item') >>> data = [] >>> for i in items: >>> data.append(getText(i.childNodes)) >>> >>> return data >> The page is >> https://lcg-voms.cern.ch:8443/voms/cms/services/VOMSCompatibility?method=getGridmapUsers >> and the line with the invalid character is (the invalid character is the >> final ? of Universit?): >> >> /C=BE/O=BEGRID/OU=Physique/OU=Univesit? Catholique de >> Louvain/CN=Roberfroid >> >> >> I have tried several options but I am not able to avoid this >> problem. Any idea?. > > Looks like the page is not well-formed XML (i.e. not XML at all). If it > doesn't specify an encoding (), you can try recoding the > input, possibly decoding it from latin-1 and re-encoding it as UTF-8 before > passing it to the SAX parser. > > Alternatively, tell the page authors to fix their page. > > Stefan From ndbecker2 at gmail.com Fri Aug 31 15:13:04 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 31 Aug 2007 15:13:04 -0400 Subject: code check for modifying sequence while iterating over it? Message-ID: After just getting bitten by this error, I wonder if any pylint, pychecker variant can detect this error? From bbxx789_05ss at yahoo.com Thu Aug 30 14:25:35 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 30 Aug 2007 11:25:35 -0700 Subject: gc.garbage In-Reply-To: <46D692FC.4030805@v.loewis.de> References: <1188467173.708043.44800@w3g2000hsg.googlegroups.com> <46D692FC.4030805@v.loewis.de> Message-ID: <1188498335.633506.90050@q4g2000prc.googlegroups.com> On Aug 30, 3:50 am, "Martin v. L?wis" wrote: > > gc.set_debug(gc.DEBUG_LEAK) > > print gc.garbage > > > --output:-- > > [] > > gc: uncollectable > > gc: uncollectable > > gc: uncollectable > > gc: uncollectable > > gc.garbage is filled only after these messages > are printed, not before. You need to add an explicit > call to gc.collect() if you want to see what > uncollectable garbage you have. > > Regards, > Martin Hi, Thanks for the response. I had a cut and paste error in my reply, so here it is again with the corrections... Now, if I run the code: ------------ import gc class Cat(object): def __del__(): pass class Dog(object): def __del__(): pass def some_func(): the_dog = Dog() the_cat = Cat() the_dog.cat = the_cat the_cat.dog = the_dog some_func() gc.set_debug(gc.DEBUG_LEAK) gc.collect() print gc.garbage ----------- I get this output: ---------- gc: uncollectable gc: uncollectable gc: uncollectable gc: uncollectable [<__main__.Dog object at 0x56e10>, <__main__.Cat object at 0x56e30>, {'cat': <__main__.Cat object at 0x56e30>}, {'dog': <__main__.Dog object at 0x56e10>}] ----------- Why are there two entries in the list for each uncollectable object(same addresses)? Also, I haven't bound the names "cat" or "dog" anywhere in my program. What do those names mean in the list? Doing some further testing, if I eliminate the __del__ methods: ----------- import gc class Cat(object): pass class Dog(object): pass def some_func(): the_dog = Dog() the_cat = Cat() the_dog.cat = the_cat the_cat.dog = the_dog some_func() gc.set_debug(gc.DEBUG_LEAK) gc.collect() print gc.garbage ------------------- I get this output: ----- gc: collectable gc: collectable gc: collectable gc: collectable [<__main__.Dog object at 0x56e10>, <__main__.Cat object at 0x56e30>, {'cat': <__main__.Cat object at 0x56e30>}, {'dog': <__main__.Dog object at 0x56e10>}] ----- The docs say: --------- garbage A list of objects which the collector found to be unreachable but could not be freed (uncollectable objects). -------- Since debugging doesn't show any uncollectable objects, why isn't gc.garbage empty? The docs also say: ---- garbage ...By default, this list contains only objects with __del__() methods. ---- Does set_debug() change the default? From dfabrizio51 at gmail.com Fri Aug 17 10:04:46 2007 From: dfabrizio51 at gmail.com (chewie54) Date: Fri, 17 Aug 2007 14:04:46 -0000 Subject: best GUI library for vector drawing program In-Reply-To: References: <1187357244.883516.79840@j4g2000prf.googlegroups.com> Message-ID: <1187359486.525041.159680@q4g2000prc.googlegroups.com> On Aug 17, 9:45 am, "Victor Bazarov" wrote: > chewie54 wrote: > > What would be the best cross-platform GUI library to use for a vector > > based CAD program ( something like Visio on Windows ) WxWidgets, > > Tk, PyQt, Java Swing, Java SWT,???? I need the capibility to > > draw and edit in a window that looks like a page of paper so WYSIWYG > > is very important, and I need to save the drawings in vector based > > file formats like PS, EPS, SVG, as well as image formats like jpg, > > png, and gif. Also, the images need to be high resolution so that > > they can be pasted into various other programs in Windows OS, and > > Linux OS, and the Mac OS. > > You might actually consider asking in the 'comp.graphics' hierarchy > instead of the language newsgroups. > > V > -- > Please remove capital 'A's when replying by e-mail > I do not respond to top-posted replies, please don't ask That group doesn't seem to be active anymore. From zzbbaadd at aol.com Thu Aug 30 15:00:42 2007 From: zzbbaadd at aol.com (zzbbaadd at aol.com) Date: Thu, 30 Aug 2007 12:00:42 -0700 Subject: subclassing Python types Message-ID: <1188500442.434722.157350@q5g2000prf.googlegroups.com> I have read that you can derive from the base classes such as str, list, dict. I guess this would look like: def MyString(str): def MyList(list): def MyDict(dict): How do you access the data that is contained in the super class? From mgi820 at motorola.com Tue Aug 14 12:18:14 2007 From: mgi820 at motorola.com (Gary Duzan) Date: Tue, 14 Aug 2007 16:18:14 +0000 (UTC) Subject: JPype - passing to Java main References: <1187040070.806416.75090@r34g2000hsd.googlegroups.com> <1187095969.789811.63960@j4g2000prf.googlegroups.com> <1187097639.176267.33050@d55g2000hsg.googlegroups.com> Message-ID: In article <1187097639.176267.33050 at d55g2000hsg.googlegroups.com>, wrote: >Good point Laurent. Here is the error produced when I try to access >main() using >'com.JPypeTest.main("arg")' > >The original code is pasted at the top of this thread. I only added >'com.JPypeTest.main("arg")' which causes the error below > >-------------ERROR_------------- > File "tester.py", line 10, in > com.JPypeTest.main("arg") >RuntimeError: No matching overloads found. at src/native/common/ >jp_method.cpp:121 >----------END ERROR------------- > >Thanks, >Sarah Just a guess, but try com.JPypeTest.main(["arg"]). Gary Duzan Motorola HNM >On Aug 14, 8:03 am, Laurent Pointal wrote: >> unlikeablePorpo... at gmail.com a ?crit : >> >> >> Try this: >> >> com.JPypeTest.main("arg") >> >> >> Ian >> >> > Thanks for your suggestion, but it doesn't work (produces an error). >> >> This is where you should have copy/pasted the error. >> >> ;-) >> >> >> >> > Does anybody else have any ideas? >> >> Sorry, no. > > From jonshan at winlab.rutgers.edu Fri Aug 17 17:06:56 2007 From: jonshan at winlab.rutgers.edu (Jonathan Shan) Date: Fri, 17 Aug 2007 14:06:56 -0700 Subject: Array and floating point Message-ID: <1187384816.251783.95410@19g2000hsx.googlegroups.com> Hello, I'm experiencing a problem where the float being appended to the array is not the same as the result of the appending. >>> from array import * >>> x = array('f') >>> x.append(float("0.1")) >>> x[0] 0.10000000149011612 >>> float("0.1") 0.10000000000000001 I'm expecting x[0] = 0.10000000000000001 Thanks Jonathan Shan From toby at tobiah.org Wed Aug 22 14:25:13 2007 From: toby at tobiah.org (Tobiah) Date: Wed, 22 Aug 2007 11:25:13 -0700 Subject: How do I express a backslash in a string? In-Reply-To: <46cc723c$0$16263$88260bb3@free.teranews.com> References: <46cc723c$0$16263$88260bb3@free.teranews.com> Message-ID: <46cc7382$0$24191$88260bb3@free.teranews.com> Tobiah wrote: >>>> "'" > "'" >>>> "\'" > "'" >>>> "\\'" > "\\'" >>>> "\\\'" > "\\'" >>>> > > This is quite different than any other language > that I am used to. Normally, a double backslash > takes away the special meaning of the last backslash, > and so you are left with a single backslash. > > How do I express the single backslash? > > Thanks, > > Tobiah A little more looking, and I see: >>> "\\'" "\\'" >>> len("\\'") 2 >>> So it was just the console representation that was fooling me into thinking that I had a double backslash. -- Posted via a free Usenet account from http://www.teranews.com From orsenthil at users.sourceforge.net Sun Aug 19 13:52:40 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Sun, 19 Aug 2007 23:22:40 +0530 Subject: yet another indentation proposal In-Reply-To: References: <1187538922.849174.94870@19g2000hsx.googlegroups.com> Message-ID: <20070819175239.GA3437@gmail.com> Hi Aaron, > Finally, just to be clear, I do not want to change the way 99.9% of Python > code is written. I feel that the indentation model is a good one for 99.9% > of users. What I do want to do is simply give the Python interpreter a tiny > bit more flexibility to handle code from users or environments where > indentation is not possible or practical. It never crossed my mind about the problem you have mentioned. The indentation proposal that you have put forth is infact a beaten up one, and I think, python gurus did not subscribe to it. Your requirement, in fact requests to look at it from a new perspective. We got to figure out what the different ways in which this issue can be handled.a) Screen Reader Clients. Can Screen Reader have a plugin, that will overlay a brackets to the indented code. ? b) How does software like voicecode handle the scenario? c) Have you spoken to other python programmers like you? I can remember 'Peter Lundblad' who works on 'svn' and I kind of feel that he must have worked on Python as well. They will be your best guide, IMHO. >From a normal user perspective, I can feel that addition of _{ and _} to the language proper is not going to be acceptable by many users/programmers. -- O.R.Senthil Kumaran http://uthcode.sarovar.org From steve at REMOVE-THIScybersource.com.au Sun Aug 26 12:32:29 2007 From: steve at REMOVE-THIScybersource.com.au (Steven D'Aprano) Date: Sun, 26 Aug 2007 16:32:29 -0000 Subject: lisper learning python, ... could you please comment my first python program? References: <1188143768.742884.38520@r29g2000hsg.googlegroups.com> Message-ID: <13d3aot56lq4l58@corp.supernews.com> On Sun, 26 Aug 2007 15:56:08 +0000, neptundancer wrote: > Hi, > to extend my skills, I am learning python. I have written small > program which computes math expression like "1+2*sin(y^10)/cos(x*y)" and > similar, so far only + - * / ^ sin con tan sqrt are supported. But my > program is quite inextensible, I have to change the code to add new > functions... Could some fellow experienced pythonista give me some tips > how to make my program shorter, and more extensible? Just a few comments at random. This is certainly not meant to be exhaustive: > def normalize(string): > tmp = "".join([c for c in string if c != " "]) > return "(" + tmp + ")" Try this instead: def normalize(astring): return "(" + astring.replace(" ", "") + ")" > def most_nested_expression(string): [snip code] > if level != 0: > raise IOError("mismatched parens") You raise IOError quite often, but that's a misuse of it. IOError is a subclass of EnvironmentError, and is meant to indicate (e.g.) a failed read from a disk. If you execute help(IOError) at the interactive prompt, you will see: class IOError(EnvironmentError) | I/O operation failed. I suggest a better exception to use would be ValueError, or even create your own: class MyCustomError(ValueError): pass would be a minimal example. > def is_reduced_expression(string): > for c in string: > if c == "^" or c == "*" or c == "/" or c == "+" or c == "-": > return False > return True Change that to: for c in string: if c in "^*/+-": return False return True [snip] > def add(a, b): return a + b > def sub(a, b): return a - b > def mul(a, b): return a * b > def div(a, b): return a / b Replace the above four functions with: from operator import add, sub, mul from operator import truediv as div > def translate_function(fn_str): > if fn_str == "+": return add > elif fn_str == "-": return sub > elif fn_str == "*": return mul > elif fn_str == "/": return div > elif fn_str == "^": return math.pow > elif fn_str == "sin": return math.sin elif fn_str == "cos": return > math.cos elif fn_str == "tan": return math.tan elif fn_str == > "sqrt": return math.sqrt else: raise IOError("unknown function %s" % > fn_str) fn_map = {"+": add, "-": sub, "*": mul, "/": div, "^": math.pow, "sin": math.sin } # etc. def translate_function(fn_str): try: return fn_map[fn_str] except KeyError: raise ValueError("unknown function '%s'" % fn_str) Hope that helps. -- Steven. From paddy3118 at googlemail.com Wed Aug 8 13:29:40 2007 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 08 Aug 2007 17:29:40 -0000 Subject: Doctest in Python implementations Message-ID: <1186594180.976905.24930@l70g2000hse.googlegroups.com> Hi, I'm wanting to update the Wikipedia entry on doctest with information on which current python implementations support the doctest module. So, does Doctest come with ironpython, jython, python for Nokia phones (what is that called)? Thanks. From jeff.fw at gmail.com Wed Aug 29 09:25:25 2007 From: jeff.fw at gmail.com (Jeff) Date: Wed, 29 Aug 2007 13:25:25 -0000 Subject: Creating a multi-tier client/server application In-Reply-To: <46d54ed8$0$429$426a34cc@news.free.fr> References: <1188360460.838635.186930@w3g2000hsg.googlegroups.com> <7xbqcqhqbw.fsf@ruckus.brouhaha.com> <46d54ed8$0$429$426a34cc@news.free.fr> Message-ID: <1188393925.007952.313110@r29g2000hsg.googlegroups.com> Thanks for the quick responses. I was really hoping to avoid an entirely web-based app, for a few reasons, not the least of which is that I've been working almost entirely on web apps for the past few years, and I am getting mighty sick of it. A lot of that is due to the language (PHP, which I have since grown to hate) I had to use. I've worked on a site for my self in Python (using Pylons, actually--which is excellent) which was vastly easier and more fun. But I'd really like to try something different. Now, of course, that's not enough reason to force such a thing onto my clients (when I say clients, I mean the ones that are paying for this, but they're really within my same department, so they actually have working technical knowledge.) Some reasons for them would be (in no particular order): 1) More responsive and user-friendly interfaces, 2) Much better ability to sort, export, import, and print data (very important), 3) Easier to "lock down" who's using the program by only installing it on certain machines. Paul, I've read through a bunch your conversation with Chris--for simple applications, yes, you're right, why not use the browser? But for a lot of this I have to agree with him (although I don't particularly agree with his tone, but that's irrelevant.) This will be a complex enough application that certainly simple HTML & CSS won't be enough, and the thought of the sheer amount of AJAX trickery (yes, trickery) that I'll need to use just to get it even *close* to the usability of a desktop app is rather frightening. I've done plenty of stuff with AJAX, and it certainly has its purpose, but it gets incredibly bloated and fragile *very* quickly. This application will be used by hundred of people (some of them will be using it more or less constantly) across several departments in a large university (Rutgers, if you're interested.) Because of that, it needs to work, and last for years--with changes over that time, of course, but no rewrites--a lot of their current systems are FileMaker Pro databases... all I can say is, "the horror". They've used some of these systems for the past *ten* years with their "databases" breaking several times a *week*. Now, they want something that *works*. Which leads me to the discussion of planning: if this were a basic application for myself, I'd plan out the basic objects and database tables I'd need, and how they should interact--maybe to some extent what the user interface should work/look like. But I'd certainly be flexible. In this situation, however, I have no such luxury. This system will be used, often, to figure out how much people should be paid (and then interface directly with the University's payroll system), and store lovely things like SSNs, and will also have to have somewhat crazy business logic to track when hourly workers are eligible for raises, if they took enough training classes, etc. There are a lot of people with a stake in this system, and I will need to work with them very closely on how this should work, and they sure as hell don't want any surprises. My manager even wants use cases (if you've never had to deal with use cases, consider yourself a lucky, lucky person) which I am going to attempt to argue as that is even going *too* far. So, long story short (too late), no Extreme Programming for me. Hopefully, the amount of planning will be somewhere in between that and the bureaucratic nightmare of documenting up front what each module, class and function will do. Thanks again for your advice--I really appreciate it. From horpner at yahoo.com Tue Aug 7 07:40:52 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 07 Aug 2007 11:40:52 GMT Subject: seeking tinter module References: <46b849cf$0$21841$426a74cc@news.free.fr> Message-ID: On 2007-08-07, Jean-Fran?ois Pi?ronne wrote: > I'm looking for a module name tinter (not tkinter...) > > from http://www.vex.net/parnassus/apyllo.py?i=97497223 > status: Dead and Gone > > Google return no location to download it, only a few > articles mentionned it, for example: > http://www.ibm.com/developerworks/linux/library/l-python6.html > > Does someone has still a copy of this module? Here's a Google Cache of the source code I managed to dig up: http://64.233.169.104/search?q=cache:wRcuIGPk-yYJ:svn.wishy.org/svn/repos/geezer/trunk/boss3client/geezer/widgets/tinter.py+tinter.py&hl=en&ct=clnk&cd=1&gl=us -- Neil Cerutti From deets at nospam.web.de Thu Aug 30 04:54:09 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 30 Aug 2007 10:54:09 +0200 Subject: Python doesn't see the directories I create In-Reply-To: References: Message-ID: <5jnetnFdvvgU1@mid.uni-berlin.de> mr_gadget schrieb: > When I create a subfolder, python is not seeing it. Can someone please > explain this behaviour ? I just started with python, read the tutorial over > the weekend and am writing my very first script. So I may not be seeing > something. Both os.path and glob.glob seem not to see a folder I created. > Other sibling folders seem to work fine. On a whim I tried paths with \\ > double slashes and that worked. But why should single slashes work for some > folders and not for others ?? > > What I need is to match a bunch of files in a folder with > glob.glob(C:\enhancement\rawfiles\*.bin.gz) and send them to a function that > unzips them. But I always get []. Yes the folder does have my files, and I > checked all permissions etc, everything looks identical to the other folders > which python IS seeing. Same problem on my vista pc too. > > Behaviour reproduced below. > > C:\Enhancement>dir /ad > > Volume in drive C has no label. > > Volume Serial Number is 8056-41E7 > > Directory of C:\Enhancement > > 08/28/2007 06:15 PM . > > 08/28/2007 06:15 PM .. > > 08/28/2007 06:07 PM BSA Documentation > > 08/28/2007 05:56 PM output > > 08/29/2007 07:08 PM rawfiles > > 08/23/2007 04:38 PM SnapCell2.3.2 > > 08/28/2007 06:15 PM test > > 0 File(s) 0 bytes > > 7 Dir(s) 35,703,283,712 bytes free > > C:\>python -V > > Python 2.5.1 > > C:\>python -c "import os; print os.path.exists('C:\enhancement\output')" > > True > > C:\>python -c "import os; print os.path.exists('C:\enhancement\rawfiles')" > > False > > C:\>python -c "import os; print os.path.exists('C:\\enhancement\\rawfiles')" > > True > > C:\>python -c "import glob; print glob.glob('C:\enhancement\rawfiles\*')" > > [] > > C:\>python -c "import os; print os.path.exists('C:\enhancement\test')" > > False > > C:\>python -c "import os; print > os.path.exists('C:\enhancement\snapcell2.3.2')" I'm pretty sure it's a missing backslash escape thingy. Either use \\ for a backslash in paths, or just the forward slash, it works as well. And case-sensitivity might be an issue as well. Diez From kyosohma at gmail.com Fri Aug 24 12:12:33 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 24 Aug 2007 09:12:33 -0700 Subject: How to replace a method in an instance. In-Reply-To: References: Message-ID: <1187971953.261328.219000@q3g2000prf.googlegroups.com> On Aug 24, 11:02 am, "Steven W. Orr" wrote: > In the program below, I want this instance to end up calling repmeth > whenever inst.m1 is called. As it is now, I get this error: > > Hello from init > inst = <__main__.CC instance at 0x402105ec> > Traceback (most recent call last): > File "./foo9.py", line 17, in ? > inst.m1() > TypeError: repmeth() takes exactly 1 argument (0 given) > > #! /usr/bin/python > def repmeth( self ): > print "repmeth" > > class CC: > def __init__( self ): > self.m1 = repmeth > print 'Hello from init' > > def m1 ( self ): > print "m1" > > inst = CC() > inst.m1() > > TIA > > -- > Time flies like the wind. Fruit flies like a banana. Stranger things have .0. > happened but none stranger than this. Does your driver's license say Organ ..0 > Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 > individuals! What if this weren't a hypothetical question? > steveo at syslang.net Remove "self" from repmeth as it's not required in a function, only in functions that are defined within a class. Of course, a function in a class is also know as a method. Mike From p at ulmcnett.com Mon Aug 20 13:26:36 2007 From: p at ulmcnett.com (Paul McNett) Date: Mon, 20 Aug 2007 10:26:36 -0700 Subject: Mouse control with ctypes in OS X In-Reply-To: <20070820135358.0B3052303D@atmail.b-one.net> References: <20070820135358.0B3052303D@atmail.b-one.net> Message-ID: <46C9CECC.6010401@ulmcnett.com> Niklas Ottosson wrote: > I need to get hold of the mouse position and also need to be able to > change it. In windows I have used ctypes.windll.user32.getCursorPos() > and ctypes.windll.user32.setCursorPos() with great success in my program > but now I also need to make a Mac OS X version of the program. > > Does anyone know what the above libraries and functions are called in OS > X? Any help is greatly appreciated. All I can offer you is the knowledge that OS X will probably not let you set the mouse position, as it is a gross violation of the HIG (The user is in charge of where the mouse appears, not the application). But, I'm sure someone will chime in on how to get the mouse position. -- pkm ~ http://paulmcnett.com From python at jayloden.com Thu Aug 2 15:06:52 2007 From: python at jayloden.com (Jay Loden) Date: Thu, 02 Aug 2007 15:06:52 -0400 Subject: XML Processing In-Reply-To: <496954360708021153l2b20f522ia690707a8fdd7aa3@mail.gmail.com> References: <1186080339.344993.167670@z24g2000prh.googlegroups.com> <496954360708021153l2b20f522ia690707a8fdd7aa3@mail.gmail.com> Message-ID: <46B22B4C.4020705@jayloden.com> Robert Dailey wrote: > Both strings in your example are exactly the same, unless I'm missing > something. > > On 8/2/07, Roman wrote: >> Is there a package that converts a string that contains special >> characters in xml to to literal value. For instance, converts string >> http://myhome/¶m to http://myhome/&param. >> >> Thanks in advance >> >> -- >> http://mail.python.org/mailman/listinfo/python-list Robert, your newsreader/mail program is converting the HTML/XML entity codes into the corresponding character so you're not seeing the plain text version of what the OP posted. He's asking for code to convert XML entities like '&' into their escaped strings. I believe xml.sax.saxutils.encode() is what the OP is looking for: >>> import xml.sax.saxutils >>> xml.sax.saxutils.escape('http://myhome/¶m') 'http://myhome/&param' -Jay From david at boddie.org.uk Mon Aug 13 08:12:02 2007 From: david at boddie.org.uk (David Boddie) Date: Mon, 13 Aug 2007 14:12:02 +0200 Subject: Adventure-Engines in Python Message-ID: <200708131412.02619.david@boddie.org.uk> On Mon Aug 13 11:33:14 CEST 2007, Wildemar Wildenburger wrote: > Are there any? > > I've set out to make an adventure game and now I'm trying to find a set > of python-modules to help me do that. I know of the usual non-python > suspects (AGAST, AGS, Wintermute, ...) and while I they are really good, > I'd like one that is cross platform. > > I've found pyScumm and pyAdv but both don't seem to be ready for use > yet. So are there any "usable" engines written in python? It's been a while since I looked at anything like this, but I seem to remember two Python powered engines: PAWS and PUB. http://py-universe.sourceforge.net/ http://members.nuvox.net/~zt.wolf/PAWS.htm If you want to write adventures with more graphics and less text, you could do worse than looking at existing projects and solutions written with Pygame: http://www.pygame.org/ David From paul at boddie.org.uk Sat Aug 4 09:23:45 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 04 Aug 2007 06:23:45 -0700 Subject: Website data-mining. In-Reply-To: References: <1186207478.055593.107110@z24g2000prh.googlegroups.com> Message-ID: <1186233825.519650.102840@d55g2000hsg.googlegroups.com> Jay Loden wrote: > Miki wrote: > > Have a look at http://www.myinterestingfiles.com/2007/03/playboy-germany-ads.html > > Well, it's certainly interesting, but I'm not sure how it might help the OP get data from a website... A case of the Freudian clipboard, perhaps? ;-) Paul From Michael.J.Fromberger at Clothing.Dartmouth.EDU Mon Aug 6 15:03:23 2007 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Mon, 06 Aug 2007 15:03:23 -0400 Subject: boolean operations on sets References: <1186409631.147290.323400@22g2000hsm.googlegroups.com> <5hotveF3l5gmkU1@mid.uni-berlin.de> Message-ID: In article <5hotveF3l5gmkU1 at mid.uni-berlin.de>, "Diez B. Roggisch" wrote: > Flavio wrote: > > > Hi, I have been playing with set operations lately and came across a > > kind of surprising result given that it is not mentioned in the > > standard Python tutorial: > > > > with python sets, intersections and unions are supposed to be done > > like this: > > [...] > > > > The results are not what you would expect from an AND or OR > > operation, from the mathematical point of view! aparently the "and" > > operation is returning the the second set, and the "or" operation is > > returning the first. > > [...] > > It has nothing to do with sets - it stems from the fact that certain values > in python are considered false, and all others true. And these semantics > were introduced at a point where there was no explicit True/False, so the > operators were defined in exact the way you observed. > > Consider this: > > "foo" or "bar" -> "foo" > > So - nothing to do with sets. In addition to what Diez wrote above, it is worth noting that the practise of returning the value of the determining expression turns out to be convenient for the programmer in some cases. Consider the following example: x = some_function(a, b, c) or another_function(d, e) This is a rather nice shorthand notation for the following behaviour: t = some_function(a, b, c) if t: x = t else: x = another_function(d, e) In other words, the short-circuit behaviour of the logical operators gives you a compact notation for evaluating certain types of conditional expressions and capturing their values. If the "or" operator converted the result to True or False, you could not use it this way. Similarly, x = some_function(a, b, c) and another_function(d, e) ... behaves as if you had written: x = some_function(a, b, c) if x: x = another_function(d, e) Again, as above, if the results were forcibly converted to Boolean values, you could not use the shorthand. Now that Python provides an expression variety of "if", this is perhaps not as useful as it once was; however, it still has a role. Suppose, for example, that a call to some_function() is very time-consuming; you would not want to write: x = some_function(a, b, c) \ if some_function(a, b, c) else another_function(d, e) ... because then some_function would get evaluated twice. Python does not permit assignment within an expression, so you can't get rid of the second call without changing the syntax. Also, it is a common behaviour in many programming languages for logical connectives to both short-circuit and yield their values, so I'd argue that most programmers are proabably accustomed to it. The && and || operators of C and its descendants also behave in this manner, as do the AND and OR of Lisp or Scheme. It is possible that beginners may find it a little bit confusing at first, but I believe such confusion is minor and easily remedied. Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From frank.wilder at gmail.com Tue Aug 21 15:33:51 2007 From: frank.wilder at gmail.com (franko353) Date: Tue, 21 Aug 2007 19:33:51 -0000 Subject: py2app and eggs Message-ID: <1187724831.764958.24150@g4g2000hsf.googlegroups.com> This may be common information, but I had trouble finding it. I was getting an ImportError whenever I tried to run a built app from py2app. It turns out that using py2app version "0.3.6", it was having trouble with zipped egg installs. I had to move my zipped egg file to a temporary location (from sitepackages) and issue a ``easy_install -Z somepackage.egg``. Once I did this, I stopped getting the ImportError and everything worked. From joshua at eeinternet.com Thu Aug 2 17:44:38 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Thu, 02 Aug 2007 13:44:38 -0800 Subject: Bug in time, part 2 Message-ID: Or could I entitle this, "A Wrinkle in time.py," with apologies to Madeleine L'Engle. Either I've found a bug (or rather room for improvement) in time.py, or I *really* need a time module that doesn't assume so much. After the suggestions to try setting the dst flag to zero, I did some more experimentation, and here is what I came up with: >>> import os >>> import time >>> os.environ['TZ'] = 'GMT' >>> time.tzset() >>> time.tzname ('GMT', 'GMT') >>> time.mktime((2007, 3, 11, 2, 30, 0, 6, 70, 0)) 1173580200.0 >>> time.mktime((2007, 3, 11, 3, 30, 0, 6, 70, 0)) 1173583800.0 OK, so far I'm seeing a one hour difference. >>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1173580200.0)) '2007-03-11 02:30:00' >>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1173583800.0)) '2007-03-11 03:30:00' Yay! it works! But, let's do this: >>> import time >>> time.tzname ('AKST', 'AKDT') >>> int(time.mktime(time.strptime('2007-03-11 2:30:00','%Y-%m-%d %H:%M:%S' [0:8] + (0,))) 1173612600 >>> int(time.mktime(time.strptime('2007-03-11 3:30:00','%Y-%m-%d %H:%M:%S' [0:8] + (0,))) 1173616200 >>> OK, that looks good, a one hour difference, and I told it not to figure in dst (the last 0). BUT: >>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1173612600)[0:8] + (0,)) '2007-03-11 03:30:00' >>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1173616200)[0:8] + (0,)) '2007-03-11 04:30:00' So, apparently localtime assumes DST (since we're in DST right now) and there is no way to tell it the unixtime given to it was calculated under the assumption of no daylight savings. And would this particular test case work if I told it to use DST? Yes, but then I'd have several hundred other test cases failing. I think localtime needs to have a parameter to tell it not to assume DST, even if DST would normally be active in that date range. So, at any rate, my fix/workaround is to manually set time.py to use UTC to convert to and from, and then deal with the times I have from there. All I wanted to do was convert an 18 or 19 byte character string (ISO date/time) to a four byte character string (key in a dict, can't use ints in a shelve db), and I end up spending HOURS trying to figure out 1) why I was getting duplicate keys, then 2) why mktime was generating duplicate unix times, and finally 3) why localtime wasn't converting back correctly. Sigh. Some days I hate DST. :) Thanks to all for the pointers and help. In other news, setting time.tzname = ('GMT', 'GMT') does nothing. You have to set the environment variable, then call tzset. Is there a rational for this? Seems odd. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE From max at alcyone.com Tue Aug 14 21:49:27 2007 From: max at alcyone.com (Erik Max Francis) Date: Tue, 14 Aug 2007 18:49:27 -0700 Subject: Retry: Question about FutureWarning In-Reply-To: References: Message-ID: Steven W. Orr wrote: > M1.py:268: FutureWarning: hex/oct constants > sys.maxint will > return positive values in Python 2.4 and up > StartTime = safe_dict_get ( dic, 'starttime', 0xFFFFFFFF ) ... > import warnings > warnings.filterwarnings('ignore', category=FutureWarning) > > My question is this: Why can the warning not be shut off by putting the > two lines in M1 where the reference exists to 0xFFFFFFFF ? You really don't want to shut off the warning; it means just what it says: Python 2.3.5 (#1, Feb 8 2005, 23:36:23) [GCC 3.2.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 0xffffffff :1: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up -1 Python 2.4.3 (#1, Mar 29 2006, 17:16:11) [GCC 3.2.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 0xffffffff 4294967295L -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis Black vinyl man with black plasticized imagination -- Nik Kershaw From aleax at mac.com Sun Aug 19 12:22:04 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 19 Aug 2007 09:22:04 -0700 Subject: yet another indentation proposal References: <1187538922.849174.94870@19g2000hsx.googlegroups.com> Message-ID: <1i335jn.g5ymo519vckxfN%aleax@mac.com> Paddy wrote: ... > Can screen reaaderss be customized? Open-source ones surely can (e.g., NVDA is an open-source reader for Windows written in Python, -- alas, if you search for NVDA Google appears to be totally convinced you mean NVidia instead, making searches pretty useless, sigh). > Maybe their is a way to get the screen reader to say indent and dedent > at thee appropriate places? There definitely should be. > Or maybe a filter to put those wordds into the source? .../Tools/scripts/pindent.py (comes with the Python source distribution, and I hope that, like the whole Tools directory, it would also come with any sensible packaged Python distribution) should already be sufficient for this particular task. The "indent" always happens (in correct Python sources) on the next line after one ending with a colon; pindent.py can add or remove "block-closing comments" at each dedent (e.g., "# end for" if the dedent is terminating a for-statement), and can adjust the indentation to make it correct if given a Python source with such block-closing comments but messed-up indentation. Alex From ars at iki.fi Fri Aug 10 07:51:56 2007 From: ars at iki.fi (Antti Rasinen) Date: Fri, 10 Aug 2007 14:51:56 +0300 (EEST) Subject: Question about properties. In-Reply-To: <1186741289.074717.174370@e16g2000pri.googlegroups.com> References: <1186741289.074717.174370@e16g2000pri.googlegroups.com> Message-ID: <1510.194.137.123.216.1186746716.squirrel@mail.kapsi.fi> > Hi, > > i read in a book the following code snippet that is dealing with > properties: > > class ProtectAndHideX(object): > def __init__(self, x): > assert isinstance(x, int), '"x" must be an integer!"' > self.__x = ~x > > def get_x(self): > return ~self.__x > > x = property(get_x) > > > Can anyone please help me understand what the symbol "~" does here ?? My guess is that the example tries to show that it does not matter how the property computes the value. You can -- if you want -- to store integers as their bit-inverted versions (the ~ operator) and then do the conversion when getting the property value. Assume you initialized the object with ProtectAndHideX(4). Outside the object you don't have access to the original __x. And! Even if you changed the name of the variable name to y, you'd have hidden_x.y == -5 instead of 4. The example is very contrived. There might be some security related cases where you need to hide what you store in memory, though. (Hopefully they do more than just invert the bits! :) NB: I don't know what the original author was thinking here -- my telepathy isn't what it used to be. -- [ Antti Rasinen <*> ars at iki.fi ] From mikael at isy.liu.se Thu Aug 16 04:57:24 2007 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 16 Aug 2007 10:57:24 +0200 Subject: Combinatorial of elements in Python? In-Reply-To: <9e2f512b0708151011mc86ede7o68a92515c4cf3017@mail.gmail.com> References: <9e2f512b0708142203m782b0e10s817fb4d061ba0e46@mail.gmail.com> <46C2F538.8000900@isy.liu.se> <9e2f512b0708150651g7a9834cdm2db874d84804e362@mail.gmail.com> <46C32D6E.7070804@isy.liu.se> <9e2f512b0708151011mc86ede7o68a92515c4cf3017@mail.gmail.com> Message-ID: <46C41174.9060909@isy.liu.se> Sebastian Bassi wrote: > On 8/15/07, Mikael Olofsson wrote: > >> What is unclear here is in what order the keys should be visited. The >> following assumes that the keys should be considered in alphanumeric order. >> > > Yes, my fault. The orden should be given by a string, like: > > DCDBA > Using this dictionay. > A={'A':['1','2'],'B':['4','5'],'C':['6','7','8'],'D':['9']} > > Should return: > > '96941' > '97941' > '97942' > '96942' > '98941' > '98942' > '96951' > '97951' > '97952' > '96952' > '98951' > '98952' OK, seems like you need to add a second argument to the function specifying this order. I leave that to you. /MiO From steve at holdenweb.com Wed Aug 1 19:45:02 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 01 Aug 2007 19:45:02 -0400 Subject: Wing IDE for Python v. 3.0 beta1 released In-Reply-To: <1186008687.142015.55060@q75g2000hsh.googlegroups.com> References: <46AF8ED7.2070206@wingware.com> <20070801212840.GA25065@spookie1.spookiegate> <496954360708011453h2a68dee4x48dcb15bb25ea717@mail.gmail.com> <1186008687.142015.55060@q75g2000hsh.googlegroups.com> Message-ID: Paul Boddie wrote: > Steve Holden wrote: >> I can't think of any other products I use where you can contact the >> support team from right inside the software. And get answers without >> paying per-incident support fees! > > Proprietary products, right? A lot of KDE applications have a "Report > Bug..." item in the "Help" menu, for example. Perhaps you're thinking > of the same kind of thing. > > Paul > Just "products I use". I'm not currently a KDE user, but I do use a lot of open source on Windows. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From gagsl-py2 at yahoo.com.ar Wed Aug 22 10:13:21 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 22 Aug 2007 07:13:21 -0700 Subject: advice about `correct' use of decorator In-Reply-To: References: <46C4B097.4080309@fmed.uba.ar> <740c3aec0708170529s6f7e7fe2l8c92771c2d0a51d4@mail.gmail.com> <46C5C9AE.5020508@fmed.uba.ar> Message-ID: <1187792001.935204.42330@e9g2000prf.googlegroups.com> On 22 ago, 10:00, "BJ?rn Lindqvist" wrote: > On 8/17/07, Gerardo Herzig wrote: > > > BJ?rn Lindqvist wrote: > > >def is_logued_in(): > > > if not user.is_logged_in(): > > > raise NotLoggedInError > > > >It costs you one more line, but reduces complexity. And if you are > > >worried about that extra line you can put it in a function. > > > As far as i know (by the way, AFAK is the shortcut?, and BTW means `by > > the way'? ), decorators are not indispensable. I mean, all that you can > > do with python, you can doit without decorators. And from my point of > > view, this hides the complexity for the other developers of my group, > > hiding is not the same thing as reducing. By hiding the code behind a > decorator, you are increasing the complexity by adding another layer > that the programmer has to look through to see your control flow. > > > since all they have to do is add the @is_logged_in line at the top of > > the cgi script, and not to worrie about exceptions, not even how the > > decorator is implemented (i may log the error in some file). All they > > have to know is that any abnormal situation will redirect to the `login' > > screen. > > As I said, you can accomplish the exact same thing by calling a > function from within the function that requires the user to be logged > in. > > def change_pass(): > check_user_logged_in() > ... more stuff here... > > is less complex (and therefore preferable) than: > > @check_user_logged_in > def change_pass(): > ... more stuff here... > > An important principle in engineering is that you should always strive > to make your design as simple as possible. If you have two equal > designs, you should always choose the one that is simpler because > simple things are easier to understand than complex things. I don't see the complexity in this case - both are a single line of code. Any internal complexity is hidden by the language. In fact, I consider the decorated function simpler than the other: its body represents exactly what the function does, without any distracting precondition calls. The decorator has some advantages: can have syntax support on your editor, can perform some registering/logging, it's even easier to quickly check visually if it's here. -- Gabriel Genellina From claird at lairds.us Tue Aug 7 09:53:19 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 7 Aug 2007 13:53:19 +0000 Subject: Which GUI toolkit (was: Tkinter or wxpython?) References: <7x3aywr4tc.fsf@ruckus.brouhaha.com> <4866bea60708061043x34fb94edg8b675eb1608af9b1@mail.gmail.com> Message-ID: In article , Bryan Hepworth wrote: . [waaaaaaay too much quoted text for my taste] . . >> I'm not trying to claim that there are no benefits to web >> applications. But I often see people touting the web as a *superior >> application platform*, which is simply false, and as innately simpler >> to develop for, which is also false. >> >I'm also in a similar predicament starting to look at Python for the >first time. > >I'd be curious to know peoples take on other GUI's like pygtk and pyqt >for example to get a fuller picture. As a total newbie the list seems >daunting so taking advantage of other peoples experiences seems like a >good idea. > >Bryan The traditional answer is, "We've already discussed that far too often; go search the comp.lang.python archive on your own, because all the answers are there." I regard that as unhelpful. *could* be a good answer, but it's not, at least not yet. Perhaps the best immediate help is . Even better, maybe: read through these materials, start to integrate your own findings into what the Wiki already makes available, and likely others of us will pitch in. From gagsl-py2 at yahoo.com.ar Mon Aug 20 03:59:46 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 20 Aug 2007 04:59:46 -0300 Subject: passing arguments with ampersands References: <20070818112913.GA3632@gmail.com> Message-ID: En Sat, 18 Aug 2007 09:24:35 -0300, SHY escribi?: > theres no special portion of code, just the one that handles filenames > with > spaces. > the problem is that when i associate a file extension to my application > and > i open it, the filename is not quoted before passed as an arguement. i > dont > know if its the problem of windows or something, or it was just my fault > when i incorrectly associated the extension. How did you associate it? Usually the registry entries are: HKCR\.ext = filetype HKCR\filetype = File Description HKCR\filetype\shell\open\command = "path\to\your\program" "%1" (Note the double quotes around %1) Get it right at the registry, and forget all that trickery joining sys.argv parts -- Gabriel Genellina From dstromberg at datallegro.com Wed Aug 29 17:54:50 2007 From: dstromberg at datallegro.com (Dan Stromberg - Datallegro) Date: Wed, 29 Aug 2007 21:54:50 GMT Subject: re compiled object result caching? References: <1188417101.936530.182480@50g2000hsm.googlegroups.com> Message-ID: On Wed, 29 Aug 2007 17:45:36 -0400, Steve Holden wrote: > Dan wrote: >> foo_re = re.compile(r"foo(bar)") >> # . . . >> if foo_re.search(line): >> foo_re.last_result().group(1) >> > If you wanted to implement this I don't really see why a method call is > necessary. It would surely only need to be a simple attribute? > > Of course you then introduce the possibility that someone will reference > if before using the RE in a search, plus it still requires separate > storage if you want the ability to use the same RE for two different > matches and compare the match results. I've long felt that publicly accessible attributes probably should be syntactic sugared to look like accessor methods, a bit like how __add__ ends up being + - so that if your attribute ever needs to become methods (say, it started out life as a unidimensional thing, but later needs to be a flattening of 3 dimensions or something), you won't necessarily need to change depenent code. But are methods a lot more expensive in python than referencing other kinds of attributes? From martin at v.loewis.de Wed Aug 29 10:40:49 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 29 Aug 2007 16:40:49 +0200 Subject: strange list comprehension on generator In-Reply-To: References: Message-ID: <46D58571.7090204@v.loewis.de> > #this does not return the way I would expect. why? You yield the very same list object all the times. So when you make a later change, all earlier results will get changed, too (since they are the same object). Of course, it won't affect the terminal output, so you don't see that the older values changed in the example that you think works as expected. HTH, Martin From navidearr at yahoo.com Thu Aug 9 14:22:30 2007 From: navidearr at yahoo.com (Naveen kumar) Date: Thu, 9 Aug 2007 11:22:30 -0700 (PDT) Subject: how to call file from Jython? Message-ID: <579774.52462.qm@web52803.mail.re2.yahoo.com> Hi I want to excute a .cmd file on windows through jython.. How can i do that? I am using following code import os os.system("C:/testfile/anotherfolder/Startserver.cmd") can any body let me know how can excute Startserver.cmd from jython?? thanks, Naveen --------------------------------- Be a better Globetrotter. Get better travel answers from someone who knows. Yahoo! Answers - Check it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: From zondo42 at googlemail.com Fri Aug 3 02:28:25 2007 From: zondo42 at googlemail.com (Glenn Hutchings) Date: Fri, 03 Aug 2007 06:28:25 -0000 Subject: Tkinter or wxpython? In-Reply-To: References: Message-ID: <1186122505.996640.262520@d55g2000hsg.googlegroups.com> On Aug 3, 1:00 am, "wang frank" wrote: > I want to build a GUI to execut python script. I found TKinter and > wxpython. Which one is easier for a newbie? and which one is better? Well, Tkinter comes with Python, so newbies can get up and running straight away without having to download and install anything else. And there are probably lots more examples out there that a newbie can look at and learn from. As for *better*, wxPython has a lot more kinds of widgets in it, which will make writing GUIs less tedious in the long run, and the widgets look a lot nicer too. Glenn From vedrandekovic at v-programs.com Sat Aug 11 06:09:40 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Sat, 11 Aug 2007 03:09:40 -0700 Subject: python 2.5 bug In-Reply-To: <5i5fktF3ml00gU1@mid.uni-berlin.de> References: <1186825286.493878.80380@l70g2000hse.googlegroups.com> <5i5fktF3ml00gU1@mid.uni-berlin.de> Message-ID: <1186826980.346619.287670@r34g2000hsd.googlegroups.com> On 11 kol, 11:59, Marc 'BlackJack' Rintsch wrote: > On Sat, 11 Aug 2007 02:41:26 -0700, vedrandekovic wrote: > > I was install Python 2.5 and uninstall Python 2.4 now I cannot run my > > scripts, only from idle > > > What should I do? > > Install 2.4 again. Both can be installed in parallel. > > Ciao, > Marc 'BlackJack' Rintsch I need python 2.5 for work becose python 2.4 module tokenizer has no attribute "untokenize" Regards, Vedran From thomas at jollans.com Tue Aug 14 19:38:50 2007 From: thomas at jollans.com (Thomas Jollans) Date: Wed, 15 Aug 2007 01:38:50 +0200 Subject: buggie in else syntax ? In-Reply-To: <46C21D70.8000409@gmail.com> References: <46C21D70.8000409@gmail.com> Message-ID: <200708150138.57816.thomas@jollans.com> On Tuesday 14 August 2007, stef mientki wrote: > hello, > > I've the idea that the "else" syntax is not always handled correctly, > or I'm overlooking something. > > This pieces of code are automatic translation from another language, > sometimes it works, sometimes it doesn't ??? > > This piece of code works nice: > > a = 2 > > def JSM (line_nr): > print line_nr > > if a>3: > print 'asddas' > else: JSM(230) ; \ <== this is the problem line, that's ok here > print 'aaps' > > While this piece of code gives a syntax error: > > #Function button_antidender(bit in pin,sbyte in out > Button_Counter_Temp,byte in demp) return bit is > def button_antidender ( pin, button_counter_temp, demp ): > #serial_hw_write(counter) > Serial_HW_Write ( button_counter_temp ) ;JSM(226) > if JSM(227) and ( button_counter_temp >= 0 ): > if JSM(228) and ( pin == on ): > button_counter_temp = button_counter_temp + 1 > ;JSM(229) > else: JSM(230) ; > \ <=== SYNTAX ERROR is there a newline before the backslash ? Or a space after the backslash but before the newline ? -- Regards, Thomas Jollans GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu Hacker key : v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part. URL: From uymqlp502 at sneakemail.com Wed Aug 29 01:21:49 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Tue, 28 Aug 2007 22:21:49 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> Message-ID: <1188364909.397692.209170@q4g2000prc.googlegroups.com> On Aug 28, 9:35 pm, Steven Bethard wrote: > Russ wrote: > > I just stumbled onto PEP 316: Programming by Contract for Python > > (http://www.python.org/dev/peps/pep-0316/). This would be a great > > addition to Python, but I see that it was submitted way back in 2003, > > and its status is "deferred." I did a quick search on > > comp.lang.python, > > but I don't seem to see much on it. Does anyone know what the real > > status is of getting this into standard Python? Thanks. > > PEP's with "deferred" status typically aren't going into Python any time > soon, if ever. Since the due date for all Python 3 core changes is long > past due, you won't even be seeing it in Python 3. > > Steve Thanks for that information. That's too bad, because it seems like a strong positive capability to add to Python. I wonder why the cold reception. Were there problems with the idea itself or just the implementation? Or is it just a low priority? In any case, I guess it is still perfectly usable even if it isn't part of the core Python. Has anyone used it? If so, how well did it work? Thanks. From steve at holdenweb.com Wed Aug 1 12:45:58 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 01 Aug 2007 12:45:58 -0400 Subject: Time object? In-Reply-To: <496954360708010918n22e525f8y1f453714a7d1155c@mail.gmail.com> References: <496954360708010918n22e525f8y1f453714a7d1155c@mail.gmail.com> Message-ID: Robert Dailey wrote: > Hi, > > I'm well aware of the datetime module, however it is really inconsistent > and useless to me. In order to do any arithmetic on time objects, I have > to use the 'timedelta' class, which doesn't even allow me to do all the > math I want to do. > > For example, I want to do "1 / timeobj", where timeobj might represent a > time in the format of "00:00:00.000000". Do I have to code my own class > for this, or is there some other third party library out there that will > allow me to do this? > > Thanks. > But surely all you really need is a function to convert a timedelta to seconds. Like: secs(td): return (td.days*24*3600)+td.seconds+(td.microseconds/1000000.0) So I don't really see the need for a third party library. It may be useless to you: have you considered that your use case might be non-standard? Or perhaps you just like to make things difficult. Once you have your times in seconds then rate calculations are a piece of cake. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From ptmcg at austin.rr.com Thu Aug 16 23:25:13 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 16 Aug 2007 20:25:13 -0700 Subject: defaultdict of arbitrary depth Message-ID: <1187321113.841198.195100@22g2000hsm.googlegroups.com> In responding to another post on defaultdict, I posted an implementation of a 2-level hashtable, by creating a factory method that returned a defaultdict(dict). The OP of that other thread was trying to build a nested tree from a set of n-tuples, in which the first (n-1) values in each tuple were the keys for navigating down the tree, and the final n'th value was the value for to be assigned to the leaf node. My post worked only if n=2, which fortunately was the test case that the OP gave. But it annoyed me that this required advance knowledge of the number of keys. I've hacked out this recursivedefaultdict which is a defaultdict(defaultdict(defaultdict(...))), arbitrarily deep depending on the keys provided in the reference. Please comment. -- Paul from collections import defaultdict data = [ ('A','B','Z',1), ('A','C','Y',2), ('A','C','X',3), ('B','A','W',4), ('B','B','V',5), ('B','B','U',6), ('B','D','T',7), ] class recursivedefaultdict(object): def __init__(self): self.__dd = defaultdict(recursivedefaultdict) def __getattr__(self,attr): return self.__dd.__getattribute__(attr) def __getitem__(self,*args): return self.__dd.__getitem__(*args) def __setitem__(self,*args): return self.__dd.__setitem__(*args) table = recursivedefaultdict() for k1,k2,k3,v in data: table[k1][k2][k3] = v for kk in sorted(table.keys()): print "-",kk for jj in sorted(table[kk].keys()): print " -",jj for ii in sorted(table[kk][jj].keys()): print " -",ii,table[kk][jj][ii] prints: - A - B - Z 1 - C - X 3 - Y 2 - B - A - W 4 - B - U 6 - V 5 - D - T 7 From rgrdev at gmail.com Sat Aug 4 18:08:22 2007 From: rgrdev at gmail.com (rgrdev at gmail.com) Date: Sun, 05 Aug 2007 00:08:22 +0200 Subject: the one python book References: <1186240249.433185.291390@r34g2000hsd.googlegroups.com> Message-ID: <86vebvx8a1.fsf@googlemail.com> Michael Tobis writes: > On Aug 4, 9:32 am, Neil Cerutti wrot > >> With Python, you won't find anything like that. Python is too >> huge. > > That's silly. Python is small in the sense that C is small. The Python > standard library is probably much bigger than the C standard library, > but Kernghan and Richie don't cover it. > > K&R is a unique book. I have never seen anything comparable for any That's very true. > language. The closest Python equivalent is the official docs: > > http://docs.python.org/ > > I think the core Python bookshelf is: > > Learning Python (Lutxz & Ascher) and/or > Dive Into Python (Pilgrim) for tutorial I can recommend (for a big fat reference at a good price) "Programming Python" by Mark Lutz from O'Reilly. > > Python in a Nutshell (Martelli) AND > Python Essential Reference (Beazley) for reference > > The latter two books are not perfect (both indexes are infuriating) > but I usually find that I can find what I am looking for in one or the > other. > > Like most people I eventually plan to read Moby Dick, War and Peace, > and Lutz's Programming Python. Maybe when I retire. Aha. You heard of it :-; > > mt > -- From nytrokiss at gmail.com Wed Aug 29 17:32:44 2007 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 29 Aug 2007 14:32:44 -0700 Subject: Thread issue Message-ID: <8a6b8e350708291432vcd444bfre769fcf07f60d2b2@mail.gmail.com> Hi I have a program that downloads webpages. The webpages are stored in a list and i make each has it's own thread that downloads it. Sometimes the threads exit (because urlopen() throws an exception) Now the question is how can i recover from this thread failing Example Code from urllib import urlopen import threading threaded_object = [] urls= [url1,url2....] for i in urls: do_thread = threading.Thread(target=urlopen,args=(url,)) threaded_object.append(do_thread) for i in threaded_object: i.start() for i in threaded_object: i.join() Thanks James -- http://www.goldwatches.com/ http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From byte8bits at gmail.com Tue Aug 7 17:45:46 2007 From: byte8bits at gmail.com (brad) Date: Tue, 07 Aug 2007 17:45:46 -0400 Subject: passing vars to py scipts in cron jobs Message-ID: What's the proper way to call a py script and pass in variables while doing cron jobs? I can run the scripts fine from idle, python, etc using raw_input() to prompt users. The scripts have classes with methods that need arguments. Here's an example... I want to run c1.d1(v,v,v) then c2.d2(v,v,v) class c1: # User defined vars def d1(var1, var2, var3): pass class c2: # User defined vars def d2(var1, var2, var3): pass Thanks, Brad From horpner at yahoo.com Mon Aug 20 13:01:26 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 20 Aug 2007 17:01:26 GMT Subject: Newbee Question References: Message-ID: On 2007-08-20, HD1956 wrote: > This is probably a simple code. I am a truck driver who gets > paid by stops and cases. I am trying to figure out how to code > my stop pay. I get 40 cents per stop up to 22 stops, and $1.40 > per stops after that. I wish *I* could make a deal like that. I stop working all the time! -- Neil Cerutti Customers who consider our waitresses uncivil ought to see the manager --sign at New York restaurant From http Thu Aug 16 02:15:23 2007 From: http (Paul Rubin) Date: 15 Aug 2007 23:15:23 -0700 Subject: ElementTree surprise References: <7xd4xoxf16.fsf@ruckus.brouhaha.com> <87bqd89gkd.fsf@wilson.homeunix.com> Message-ID: <7x4pj0xax0.fsf@ruckus.brouhaha.com> Torsten Bronger writes: > > > Technically, text is nodes as all other element nodes. In the > parrot example, there is no empty textnode but no textnode at all. That is required by the xml standard? If yes, elementtree is doing the right thing, but it surprises me, I would have expected an empty string. Thanks. From david at nospam.spam Mon Aug 13 22:26:31 2007 From: david at nospam.spam (david) Date: Tue, 14 Aug 2007 12:26:31 +1000 Subject: pyserial win32 port numbering Message-ID: <13c24mlatu3kuef@corp.supernews.com> http://pyserial.sourceforge.net/ "port numbering starts at zero, no need to know the port name in the user program" But the implementation in SerialWin32 is just (Portnum +1) So there is no 'start' to the port numbering at all: there is no assurance that you will have a pySerial serial port Zero, even if you have 57 Windows Serial ports. Renumbering the serial ports to start at zero would sort of make sense if it was done in a semi-portable way - so you could move from one machine with two serial ports to another machine with two serial ports. In Windows, that requires enumerating the serial ports, and assigning a logical pySerial port number to each. This is going to become more of a problem, because Windows logo compliant PC's by definition do not have a serial port 1 or 2 so the pySerial logical port numbers are likely to start at 2 or 4. It's already a problem on PC's that have PCI serial port cards (not ISA serial port cards). The pySerial logical port numbering typically goes something like 0, 4,5, mapping the Windows serial ports 1,5,6 (david) From iclark at mail.ewu.edu Wed Aug 1 12:54:22 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Wed, 01 Aug 2007 09:54:22 -0700 Subject: Awkward format string In-Reply-To: <1185984697.605529.157110@g12g2000prg.googlegroups.com> References: <1185984697.605529.157110@g12g2000prg.googlegroups.com> Message-ID: beginner wrote: > Hi, > > In order to print out the contents of a list, sometimes I have to use > very awkward constructions. For example, I have to convert the > datetime.datetime type to string first, construct a new list, and then > send it to print. The following is an example. > > x=(e[0].strftime("%Y-%m-%d"), e[1].strftime("%Y-%m-%d"))+e[2:] > print >>f, "%s\t%s\t%d\t%f\t%f\t%f\t%d" % x > > e is a tuple. x is my new tuple. > > Does anyone know better ways of handling this? > > Thanks, > Geoffrey > >>> import datetime >>> old_tuple = ( ... datetime.datetime(2007, 8, 1), ... datetime.datetime(2007, 8, 2), ... 1, ... 2.0, ... 3.0, ... 4 ... ) >>> first_date = old_tuple[0].strftime('%Y-%m-%d') >>> second_date = old_tuple[1].strftime('%Y-%m-%d') >>> new_tuple = (first_date, second_date) + old_tuple[2:] >>> print '\t'.join(str(i) for i in new_tuple) 2007-08-01 2007-08-02 1 2.0 3.0 4 Without more information that's the best I can think of. Ian From steve at holdenweb.com Fri Aug 31 14:37:40 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 31 Aug 2007 14:37:40 -0400 Subject: strings (dollar.cents) into floats In-Reply-To: <4866bea60708310928nf54e60dqdd207ccafa8b8a6e@mail.gmail.com> References: <877incd20i.fsf@benfinney.id.au> <46d75cf3$0$7698$9b4e6d93@newsspool2.arcor-online.net> <1188575044.874256.42960@50g2000hsm.googlegroups.com> <4866bea60708310928nf54e60dqdd207ccafa8b8a6e@mail.gmail.com> Message-ID: Chris Mellon wrote: > On 8/31/07, Steve Holden wrote: >> sturlamolden wrote: >>> On 31 Aug, 02:12, Wildemar Wildenburger >>> wrote: >>> >>>> I've heard (ok, read) that several times now and I understand the >>>> argument. But what use is there for floats, then? When is it OK to use them? >>> There are fractions that can be exactly represented by floats that >>> cannot be exactly represented by decimals. >> Would you care to give an example? >> >>> There are fractions that >>> can be exactly represented by decimals that cannot be exactly >>> represented by floats. >>> >>> Which one is better? Which do we prefer? >>> >>> What a float cannot do is to represent a decimal fractional number >>> (e.g. 1.1) exactly. If we need that, we cannot use floats. A notable >>> example is monetary computations, it covers 99% of the use for decimal >>> numbers in computers. For this reason, we should never use floats to >>> add 10 cents to a dollar. The use of decimals for monetary >>> calculations is mandatory. >>> >> That last sentence is patent nonsense, and completely untrue. Many >> satisfactory financial applications have been written using only >> floating-point arithmetic. Indeed I believe the accountant's Swiss army >> knife, the Excel spreadsheet, uses floating-point numbers exclusively. >> > This is true, although Excel munges it's FP to provide "expected" results. > > It depends on what you consider a "financial" application though. > Excel, while in extremely broad use, is not used to implement any of > the systems which actually "define" money, like the back end financial > systems at banks and credit unions. > > In my experience, by far the most common method of calculating > financial numbers is actually using integer amounts, and then applying > well-defined rounding rules which I can't be bothered to look up the > name for. > > For what it's worth, the work that I do with money (which is > middleware doing data transport, not calculations or billing) uses > either string representations or fixed point. > >> What you say about floating-point have speed advantages is true, but you >> go too far in claiming that decimal arithmetic is mandatory for monetary >> calculations. That's about as sensible as saying that base 12 and base >> 20 arithmetic units were required to calculate in pounds, shillings and >> pence. >> > > I believe that to the degree that "real" accounting was done in those > currencies it did in fact use non-decimal bases. Just as people don't > use decimal time values (except us crazy computer folk), you're write > 1 pound 4 shillings, not 1.333... pounds. There is much in what you say (which, I am happy to note, doesn't really contradict much of what I wrote). While I agree that Excel isn't a fundamental component of back-end financial systems you might be surprised at just how many people rely on its "currency" cells for financial applications, albeit of a more lightweight kind. You let yourself down just a little right at the end by not knowing the intricacies of the old sterling currency - since there were twenty shillings to the pound and twelve pennies to a shilling that would have been ?1.2. However, you are correct in assuming that nobody tried to represent ?1 3s. 4d. as 23.333... shillings. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From vedrandekovic at v-programs.com Wed Aug 22 09:04:36 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Wed, 22 Aug 2007 06:04:36 -0700 Subject: redirect or cover .bat log In-Reply-To: <5j2br6F3r2avsU1@mid.uni-berlin.de> References: <1187764689.836375.212730@z24g2000prh.googlegroups.com> <5j26bvF3s7lbpU2@mid.uni-berlin.de> <1187767578.925671.107000@q4g2000prc.googlegroups.com> <5j2br6F3r2avsU1@mid.uni-berlin.de> Message-ID: <1187787876.962883.66970@r34g2000hsd.googlegroups.com> On 22 kol, 10:52, "Diez B. Roggisch" wrote: > vedrandeko... at v-programs.com wrote: > > On 22 kol, 09:19, "Diez B. Roggisch" wrote: > >> vedrandeko... at v-programs.com schrieb: > > >> > Hello, > > >> > e.g I need run my my_scripts_setup.bat that contain: > > >> > python myscript_setup.py py2exe > > >> > Can I cover or redirect log of that process into my wx program? > >> > I'am using Windows XP SP2, and Python 2.5. > > >> Who's running the bat, and who's running the wx program? > > >> Diez > > > Hi, > > > First I convert my main wx program to exe with my py2exe setup,then > > under my main program (exe), > > I must run that .bat file and redirect or cover that process. > > Still not very clear. But running a bat-file should be possible with the > subprocess module that also has facilities to grab stdout of the child > process. > > Diez Hi, Can I execute one .bat file (without opening .bat window) just execute commands and log process redirect with sys.stdout or something in my wx window? Is this clear enough? Have you any other solutions for this? Regards, Vedran From eggie5 at gmail.com Thu Aug 9 21:13:24 2007 From: eggie5 at gmail.com (eggie5) Date: Fri, 10 Aug 2007 01:13:24 -0000 Subject: beginner whitespace question In-Reply-To: <1186707164.095766.243480@q3g2000prf.googlegroups.com> References: <1186703261.136506.208660@x35g2000prf.googlegroups.com> <1186703525.591462.122140@m37g2000prh.googlegroups.com> <1186704161.334597.218750@z24g2000prh.googlegroups.com> <1186707164.095766.243480@q3g2000prf.googlegroups.com> Message-ID: <1186708404.901323.204730@g12g2000prg.googlegroups.com> But this still isn't valid: from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField() def __unicode__(self): return self.choice On Aug 9, 5:52 pm, Dan Bishop wrote: > On Aug 9, 7:02 pm, eggie5 wrote: > > > > > On Aug 9, 4:52 pm, Dan Bishop wrote: > > > > On Aug 9, 6:47 pm, eggie5 wrote: > > > > > I keep getting an error for line 7, what's wrong with this? > > > > > from django.db import models > > > > > class Poll(models.Model): > > > > question = models.CharField(max_length=200) > > > > pub_date = models.DateTimeField('date published') > > > > > def __unicode__(self): > > > > return self.question > > > > The "def" statements have to be at the same indentation level as > > > what's before it. > > > will they still be a part of the classes? > > If you indent them twice, it's a syntax error. > If you indent them once, they'll be methods of the class. > If you don't indent them at all, they'll be global functions. From erfc at caballista.org Sat Aug 18 10:41:43 2007 From: erfc at caballista.org (Art Deco) Date: Sat, 18 Aug 2007 08:41:43 -0600 Subject: What does this thread have to do with classical music, References: <7nnh7350b5h25ghocra72b23mmsnnkj8bh@4ax.com> <469392cd$0$97226$892e7fe2@authen.yellow.readfreenews.net> <469445b3$0$4819$8f2e0ebb@news.shared-secrets.com> <4694e124$0$97214$892e7fe2@authen.yellow.readfreenews.net> <46957ef1$0$10227$8f2e0ebb@news.shared-secrets.com> <46963170$0$97261$892e7fe2@authen.yellow.readfreenews.net> <46981df7$0$12095$8f2e0ebb@news.shared-secrets.com> <46990784$0$97223$892e7fe2@authen.yellow.readfreenews.net> <4699297c$0$4706$4c368faf@roadrunner.com> <140720071431044860%erfc@caballista.org> <46a3a1a7$0$15115$8f2e0ebb@news.shared-secrets.com> <220720072148091069%erfc@caballista.org> <46a5385d$0$4832$8f2e0ebb@news.shared-secrets.com> <250720071834457296%erfc@caballista.org> <46aceaa5$0$13281$8f2e0ebb@news.shared-secrets.com> <290720071853200863%erfc@caballista.org> <46b12539$0$4807$8f2e0ebb@news.shared-secrets.com> <010820072033374341%erfc@caballista.org> <46c63474$0$4844$8f2e0ebb@news.shared-secrets.com> Message-ID: <180820070841431634%erfc@caballista.org> ah wrote: >Art Deco wrote: >> ah wrote: >>>Art Deco wrote: >>>> ah wrote: >>>>>Art Deco wrote: >>>>>> ah wrote: >>>>>>>Art Deco wrote: >>>>>>>> ah wrote: >>>>>>>>>Art Deco wrote: >>>>>>>>>> Who wrote? >>>>>>>>>> >>>>>>>>>> >>>>>>>>>>>What does that have to do with classical music, snuhwolf? >>>>>>>>>> >>>>>>>>>>>What does that have to do with classical music, snuhwolf? >>>>>>>>>> >>>>>>>>>> How many more times will you be asking the same tired, lame >>>>>>>>>> questions, >>>>>>>>>> Tholen? >>>>>>>>> >>>>>>>>>Till 2056? >>>>>>>> >>>>>>>> At that point, he will have made the Thirty Years Pset War look like >>>>>>>> 1967 in the Sinai. >>>>>>> >>>>>>>It must have been Hell to keep a garden during those times. >>>>>>> >>>>>>>Did they all eat jerky, or what? >>>>>> >>>>>> Worse -- worm-laden hardtack. >>>>> >>>>>Luxury! >>>>> >>>>>Why, I remember when I was a lad . . . we used to watch the local churls >>>>>across the fences eating that well. >>>>> >>>>>We only had millings (and (occasionally) water) on Tuesdays and Fridays. >>>> >>>> Grog and hardtack, life is good! >>> >>>?Viva la basura! >> >> Vivat les ordures! > >Vivara los trunctiato! das Leben ist gut! -- Official Overseer of Kooks and Saucerheads for alt.astronomy Trainer and leash holder of: Honest "Clockbrain" John nightbat "fro0tbat" of alt.astronomy Tom "TommY Crackpotter" Potter "You really are one of the litsiest people I know, Mr. Deco." --Kali, quoted endlessly by David Tholen as evidence of "something" "I am claiming that you believe ah's family name is "ah", Deco, and I substantiated that claim." --David Tholen "Quite a kook-out, Deco. You've been frothing even more ever since I demonstrated how you believe that ah's family name is "ah"." --David Tholen From pyth0nc0d3r at gmail.com Thu Aug 23 16:09:15 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Thu, 23 Aug 2007 15:09:15 -0500 Subject: Putting #'s and variables together in 1 variable Message-ID: File "Desktop\python\newsystem\init.py", line 51, in random_n random_name = a+b+c+d+e+ 'temp.txt' TypeError: unsupported operand type(s) for +: 'int' and 'str' import random def random_name(): a = random.randint(0,9) b = random.randint(0,9) c = random.randint(0,9) d = random.randint(0,9) e = random.randint(0,9) random_name = a+b+c+d+e+ 'temp.txt' return random_name print random_name How can i make it so that it adds the random numbers and the temp.txt to random_name variable w/out causing any error? -------------- next part -------------- An HTML attachment was scrubbed... URL: From seancron at gmail.com Fri Aug 31 19:06:22 2007 From: seancron at gmail.com (seancron) Date: Fri, 31 Aug 2007 23:06:22 -0000 Subject: parsing response from SOAPpy request Message-ID: <1188601582.917623.122890@r29g2000hsg.googlegroups.com> I'm using SOAPpy to access weather data from the NOAA National Digital Forecast Database XML Web Service [1] and I've been having trouble figuring out how to parse the data. The response comes back as XML document but when I check it with type(result) it shows the the response is a string. Does anyone have any suggestions on getting relevant data? Thanks, -Sean [1] http://www.weather.gov/forecasts/xml/ From llasram at gmail.com Wed Aug 15 18:37:53 2007 From: llasram at gmail.com (Marshall T. Vandegrift) Date: Wed, 15 Aug 2007 18:37:53 -0400 Subject: Coroutines and argument tupling References: <5ih63mF3pvnt7U1@mid.individual.net> Message-ID: <87k5rwo24e.fsf@seneca.iss.local> Bjoern Schliessmann writes: >> I'm trying to write a decorator which allows one to produce simple >> coroutines by just writing a function as a generator expression >> which re-receives it's arguments as a tuple from each yield. > > May I ask why? Passing it the same arguments over and over is no > use; and there is the send method. That's what I meant. The wrapper produced by the decorator passes the arguments back into the generator as a tuple via the `send' method. >> The ugliness of the ArgPacker class makes me suspect that I should >> perhaps just manually create and track a generator when I need a >> function with generator-like properties. > > What do you mean? I don't quite understand why you'd have to "track" > a generator for getting generator-like properties. Using the trivial `nextn' example from my original post with my decorator lets you do just: print nextn(2) # => [0, 1] print nextn(3) # => [2, 3, 4] print nextn() # => [5] Without the decorator that becomes: gen = nextn(2) print gen.next() # => [0, 1] print gen.send(3) # => [2, 3, 4] print gen.send(1) # => [5] The former is just that smidgen nicer, and allows you to continue to make use of argument defaults and varadic arguments if so desired. -Marshall From deets at nospam.web.de Fri Aug 10 06:41:46 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 10 Aug 2007 12:41:46 +0200 Subject: Smoother Lines in Turtle Graphics References: <1186703789.695265.52390@e9g2000prf.googlegroups.com> Message-ID: <5i2tnaF3mgsofU1@mid.uni-berlin.de> tomy wrote: > Hi All > I am a newbie to turtle graphics in python, so sorry if you find this > question too easy. > How can I get smoother lines in turtle graphics? > I am using python on windows. What turtle graphics? I'm not aware that there is some standard-turtle-graphics available, so it might be a problem of your turtle-graphics-package. Diez From robert.kern at gmail.com Mon Aug 20 17:34:14 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 20 Aug 2007 16:34:14 -0500 Subject: datetime in microseconds In-Reply-To: <496954360708201401p2ffcc37fjc24aabfb95224ec2@mail.gmail.com> References: <1187610776.755796.170990@r29g2000hsg.googlegroups.com> <1187615746.655162.295570@z24g2000prh.googlegroups.com> <1187619423.715120.293660@o80g2000hse.googlegroups.com> <1187621922.387688.77090@50g2000hsm.googlegroups.com> <496954360708201401p2ffcc37fjc24aabfb95224ec2@mail.gmail.com> Message-ID: Robert Dailey wrote: > A small off topic question. Why use divmod() instead of the modulus > operator? Because he needed both the quotient and the remainder. % only gives you the remainder. -- 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 greg at cosc.canterbury.ac.nz Fri Aug 10 04:28:52 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 10 Aug 2007 20:28:52 +1200 Subject: Misleading wikipedia article on Python 3? In-Reply-To: References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <7xzm15q8fy.fsf@ruckus.brouhaha.com> <1186583168.447608.114040@d55g2000hsg.googlegroups.com> <5hv7jeF3m75aqU1@mid.individual.net> Message-ID: <5i2m5bF3mfk4rU1@mid.individual.net> Evan Klitzke wrote: > You can easily modify print in a safe way. Yes, but you'd still have to replace the builtin print function with your own to get it used by non-cooperative code. That doesn't seem to gain you much over replacing sys.stdout with something that intercepts and logs stuff written to it. > What do you find wrong with this sort of "monkeypatching"? At least sys.stdout was designed somewhat with the possibility of replacing it in mind. It's not an entirely unexpected thing to do. Replacing something in the builtin namespace seems like a more drastic step, somehow. -- Greg From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Aug 7 03:28:21 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 07 Aug 2007 09:28:21 +0200 Subject: help with flexible decorators In-Reply-To: <1186452596.052963.136840@e9g2000prf.googlegroups.com> References: <1186452596.052963.136840@e9g2000prf.googlegroups.com> Message-ID: <46b81efd$0$21527$426a74cc@news.free.fr> james_027 a ?crit : > Hi, > > I want to write a flexible decorators to edit a function that may have > 1 or more arguments... > > def enhance(func): > def new(x): > #do something ... > return func(x) > return new > > @enhance > def method_a(x): > #do something ... > > While the enhance decorator work with functions of 1 argument, how do > I make it to work with more than one arguments. Use *args (for positional args) and **kw (for keyword args): def enhance(func): def new(*args, **kw): #do something ... return func(*args, **kw) return new @enhance def method_a(x): #do something ... HTH From rcdailey at gmail.com Mon Aug 20 12:05:31 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 20 Aug 2007 11:05:31 -0500 Subject: str().join() isn't working Message-ID: <496954360708200905i2100b32ag5983ab729e5d216f@mail.gmail.com> Hi, First have a look at the following code: In main.py: ----------------------------------------------------------------------------------- space = " " includes = space.join( system._user_includes ) + " " + space.join( system._system_includes ) In system.py: ----------------------------------------------------------------------------------- _user_includes = [ ] _system_includes = [ ] The above does not work. The interpreter states: "TypeError: sequence item 0: expected string, list found". I'm not sure what this means. Can anyone help me figure out what I'm doing wrong? Thanks. PS: I've also tried putting strings in the lists above just to make sure that them being empty wasn't the problem. I got no different results. -------------- next part -------------- An HTML attachment was scrubbed... URL: From raims at dot.com Sun Aug 26 12:58:41 2007 From: raims at dot.com (Lawrence Oluyede) Date: Sun, 26 Aug 2007 18:58:41 +0200 Subject: New UI Toolkit References: <1188146822.129605.160560@22g2000hsm.googlegroups.com> Message-ID: <1i3gv8x.nexgi71dartryN%raims@dot.com> Gerdus van Zyl wrote: > Please reply and let your thoughts be known. Is there a need for a new > GUI library for python? I think there's no real point in answering this question. You developed a new toolkit because, I'm guessing, you are not fully satisfied by the current ones. In my personal opinion there's no *need* for another toolkit but there is *room* for one, two, hundreds of new toolkits. That's what freedom is for. :-) -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From fred.sells at adventistcare.org Tue Aug 28 13:51:19 2007 From: fred.sells at adventistcare.org (Sells, Fred) Date: Tue, 28 Aug 2007 13:51:19 -0400 Subject: Filemaker interactions In-Reply-To: <46D092AF.80800@egenix.com> Message-ID: <0A53725C4A497848A7B3A0874B2598313D3879@acesxch01.ADVENTISTCORP.NET> filemaker 8.0 (Pro I think) has a web page generator. That's all I know, since I didn't really need it. > -----Original Message----- > From: python-list-bounces+frsells=adventistcare.org at python.org > [mailto:python-list-bounces+frsells=adventistcare.org at python.org]On > Behalf Of M.-A. Lemburg > Sent: Saturday, August 25, 2007 4:36 PM > To: Ian Witham > Cc: python-list at python.org > Subject: Re: Filemaker interactions > > > On 2007-08-01 23:41, Ian Witham wrote: > > Hello, > > > > I'm hoping someone here can put me on the right track with > some broad > > concepts here. > > > > What I am hoping to achieve is a simple HTML page to be served over > > our company LAN, into which the users (Real Estate Agents) > can enter a > > property address or reference number. > > > > My next thought was to have a Python CGI script query our filemaker > > database of property listings, construct a PDF from the relevant > > information, and finally return this PDF to the user. > > > > At no stage do I want the user to have unfettered access to the > > database or the ability to alter/delete records. > > > > My question is: what is the most appropriate way for my script to > > interact with Filemaker? Can this be done with Filemaker Pro 6? > > > > According to the Filemaker Help, the "Local Data Access Companion" > > shares the FileMaker Pro database with ODBC-compliant > applications on > > the same computer. Is this the right option? > > > > Can my CGI script be an ODBC client? How? Would it need to be > > Filemaker specific code or does ODBC have a standardised format? > > > > I'm grateful for any advice and a nudge in the right direction. > > You could try our mxODBC extension for Python which will > likely just work out of the box: > > https://www.egenix.com/products/python/mxODBC/ > > with the Filemaker ODBC driver. > > Or give this module a try (if you have more time at hand > and can do without a DB-API interface): > > http://www.lfd.uci.edu/~gohlke/code/filemaker.py.html > > It uses Filemaker's XML interface. > > -- > Marc-Andre Lemburg > eGenix.com > > Professional Python Services directly from the Source (#1, > Aug 25 2007) > >>> Python/Zope Consulting and Support ... > http://www.egenix.com/ > >>> mxODBC.Zope.Database.Adapter ... > http://zope.egenix.com/ > >>> mxODBC, mxDateTime, mxTextTools ... > http://python.egenix.com/ > ______________________________________________________________ > __________ > > :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for > free ! :::: > > > eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 > D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg > Registered at Amtsgericht Duesseldorf: HRB 46611 > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Wed Aug 22 23:46:46 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 23 Aug 2007 00:46:46 -0300 Subject: ctypes and unsigned char* References: <1187545486.797017.308720@a39g2000hsc.googlegroups.com> <1187548845.674582.69630@w3g2000hsg.googlegroups.com> <1187609450.542644.50430@w3g2000hsg.googlegroups.com> Message-ID: En Mon, 20 Aug 2007 08:30:50 -0300, oliver.andrich at gmail.com escribi?: > On 19 Aug., 20:40, Gabriel Genellina wrote: >> In the first case, use a plain c_char_p - the individual "chars" are >> already unsigned in Python (that is, ord(xxx[i]) is always positive) >> In the second case, first define the pointer type: >> >> c_ubyte_p = POINTER(c_ubyte) >> your_function.restype = c_ubyte_p > > I will have to look into that. My function I want to wrap has the > following signature > > unsigned char *MagickGetImageProfile(MagickWand *wand,const char > *name, > size_t *length) > > Well, the first argument and the second are straight forward, and work > as expected. The last argument also works and it should take up the > length of the string (unsigned char *). If I now do So, if I understand correctly, after the call, *length will contain the length of the buffer pointed by the function result. > dll.MagickGetImageProfile.restype = c_char_p > result = dll.MagickGetImageProfile(wand, "8bim", byref(length)) > > result is either an empty string or a 3 bytes long string, while > length containes the correct length of 1086 bytes for example. I also > tried If the result can contain nul bytes, you have to specify its size explicitely (else it will be truncated at the first zero). Use the string_at utility function: result_str = string_at(result, length) (That should work fine, I presume...) -- Gabriel Genellina From thorsten at thorstenkampe.de Sat Aug 11 01:32:24 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 11 Aug 2007 13:32:24 +0800 Subject: python 2.5 bug References: <1186825286.493878.80380@l70g2000hse.googlegroups.com> Message-ID: * (Sat, 11 Aug 2007 02:41:26 -0700) > I was install Python 2.5 and uninstall Python 2.4 now I cannot run my > scripts, only from idle > > What should I do? 1. read "How To Ask Questions The Smart Way"[1] 2. read "How to Report Bugs Effectively"[2] 3. don't call something a "bug" if the "bug" is likely the person sitting in front of your computer 4. don't do something you don't fully understand (in this case installing Python 2.5 and uninstalling Python 2.4) Thorsten [1] http://catb.org/~esr/faqs/smart-questions.html [2] http://www.chiark.greenend.org.uk/~sgtatham/bugs.html From unlikeablePorpoise at gmail.com Mon Aug 13 17:21:10 2007 From: unlikeablePorpoise at gmail.com (unlikeablePorpoise at gmail.com) Date: Mon, 13 Aug 2007 14:21:10 -0700 Subject: JPype - passing to Java main Message-ID: <1187040070.806416.75090@r34g2000hsd.googlegroups.com> I am trying to get JPype to pass a String into a Java class main function. Demonstration code below: =============JAVA============ package com; public class JPypeTest { public static void main(String args[]) { System.out.println(args[0]); } public void printArgument(String arg) { System.out.println(arg); } } ===========PYTHON=========== from jpype import * startJVM("C:/Program Files/Java/jdk1.5.0_12/jre/bin/server/jvm.dll","- Djava.class.path=C:/jpypetest/test/") com = JPackage("com"); jp = com.JPypeTest(); jp.printArgument('XXXX'); #WANT TO CALL main("arg") HERE!!!! shutdownJVM() =============================== What I want is to be able to call main() with an argument from the python file (using JPype) and have it echo args[0]. I can get this to work for printArgument(), but not for main(). Thanks, Sarah From deets at nospam.web.de Wed Aug 29 04:48:25 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 29 Aug 2007 10:48:25 +0200 Subject: encoding problems References: <46d5215b$0$411$426a74cc@news.free.fr> Message-ID: <5jkq6pF27cfU1@mid.uni-berlin.de> tool69 wrote: > Hi, > > I would like to transform reST contents to HTML, but got problems > with accented chars. > > Here's a rather simplified version using SVN Docutils 0.5: > > %------------------------------------------------------------- > > #!/usr/bin/env python > # -*- coding: utf-8 -*- This declaration only affects unicode-literals. > from docutils.core import publish_parts > > class Post(object): > def __init__(self, title='', content=''): > self.title = title > self.content = content > > def _get_html_content(self): > return publish_parts(self.content, > writer_name="html")["html_body"] > html_content = property(_get_html_content) Did you know that you can do this like this: @property def html_content(self): ... ? > # Instanciate 2 Post objects > p1 = Post() > p1.title = "First post without accented chars" > p1.content = """This is the first. > ...blabla > ... end of post...""" > > p2 = Post() > p2.title = "Second post with accented chars" > p2.content = """Ce poste poss?de des accents : ? ? ? ?""" This needs to be a unicode-literal: p2.content = u"""Ce poste poss?de des accents : ? ? ? ?""" Note the u in front. > for post in [p1,p2]: > print post.title, "\n" +"-"*30 > print post.html_content > > %------------------------------------------------------------- > > The output gives me : > > First post without accented chars > ------------------------------ >
>

This is the first. > ...blabla > ... end of post...

>
> > Second post with accented chars > ------------------------------ > Traceback (most recent call last): > File "C:\Documents and > Settings\kib\Bureau\Projets\python\dbTest\rest_error.py", line 30, in > > print post.html_content > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in > position 39: > ordinal not in range(128) You need to encode a unicode-string into the encoding you want it. Otherwise, the default (ascii) is taken. So print post.html_content.encodec("utf-8") should work. Diez From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Aug 24 03:48:24 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 24 Aug 2007 09:48:24 +0200 Subject: beginner, idomatic python 2 In-Reply-To: <13csjmeaoqh9le3@corp.supernews.com> References: <13csjmeaoqh9le3@corp.supernews.com> Message-ID: <46ce8d0c$0$410$426a74cc@news.free.fr> bambam a ?crit : > Would someone like to suggest a replacement for this? This is a > function that returns different kinds of similar objects, depending > on what is asked for. PSP and PWR are classes. I don't really > want to re-write the calling code very much: I'm just wondering > if the function can be replaced with some kind of OOP pattern. Dan already answered to this. Just as a side note, and since you're trying to be "idiomatic", Python's naming convention is to use all_lower for functions, MixedCaps for classes (except - mostly for historical reasons - the builtin types...), and ALL_LOWER for symbolic (pseudo) constants. > def Device(DeviceType): > if DeviceType=='PSP': > return PSP() > elif DeviceType=="Power Supply" > return PWR() > etc... > > > Thanks! > > From wojciech_mula at poczta.null.onet.pl.invalid Thu Aug 2 15:16:39 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?iso-8859-2?Q?Mu=B3a?=) Date: Thu, 2 Aug 2007 19:16:39 +0000 (UTC) Subject: Memory Leak with Tkinter Canvas (Python 2.5 Win32) References: <1186068851.011344.322980@i13g2000prf.googlegroups.com> Message-ID: frikk wrote: > [...] > As you can see- I am doing nothing other than drawing a lot of > rectangles on the canvas. You aren't drawing, but **creating** rectangle objects, as a meth. name suggests. You find more info at tkinter.effbot.org. > [...] > > def clear_grid(): canv.delete(ALL) > for i in range(0,HEIGHT/10): > for j in range(0, HEIGHT/10): > canv.create_rectangle(i*10,j*10, \ > i*10+10, j*10+10, \ > fill = "white") w. From mark at mailinator.com Sun Aug 26 06:23:05 2007 From: mark at mailinator.com (Mark) Date: 26 Aug 2007 10:23:05 GMT Subject: Using Regular Expresions to change .htm to .php in files References: <1187896823.843419.53220@q3g2000prf.googlegroups.com> <46cdd386$0$27392$88260bb3@free.teranews.com> Message-ID: On Thu, 23 Aug 2007 12:27:10 -0700, Tobiah wrote: > sed "s/.htm/.php/g" < $each > /tmp/$$ This line should be: sed "s/\.htm$/.php/g" < $each > /tmp/$$ From bj_666 at gmx.net Tue Aug 7 02:11:28 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Aug 2007 06:11:28 GMT Subject: How to use C enum in Python CTypes? References: <1186462639.872254.25660@z24g2000prh.googlegroups.com> Message-ID: <5hqgogF3ldifeU1@mid.uni-berlin.de> On Tue, 07 Aug 2007 04:57:19 +0000, rozniy wrote: > typedef enum olss_tag > { > OLSS_AD, > OLSS_DA, > OLSS_DIN, > OLSS_DOUT, > OLSS_SRL, > OLSS_CT > } > OLSS; > > I managed to fudge the HDEV, UINT and PHDASS types as CTypes c_long(), > but I am not sure how translate a C enum into Python... > > This site > http://python.net/crew/theller/ctypes/tutorial.html#bugs-todo-and-non-implemented-things > > says that enumeration types is not implemented, > "Enumeration types are not implemented. You can do it easily yourself, > using c_int as the base class." I would just define constants: (OLSS_AD, OLSS_DA, OLSS_DIN, OLSS_DOUT, OLSS_SRL, OLSS_CT) = map(ctypes.c_int, xrange(6)) Ciao, Marc 'BlackJack' Rintsch From paul at boddie.org.uk Thu Aug 2 18:58:08 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 02 Aug 2007 15:58:08 -0700 Subject: __call__ considered harmful or indispensable? In-Reply-To: <46b24200$0$19638$426a74cc@news.free.fr> References: <46b24200$0$19638$426a74cc@news.free.fr> Message-ID: <1186095488.781935.313350@e16g2000pri.googlegroups.com> Bruno Desthuilliers wrote: > > Most of what you can do with a callable instance can be done with > closures (and is usually done so in FPLs), but given Python's OO nature, > it's sometimes clearer and simpler to use callable instances than > closures. Indeed. I think __call__ has been neglected as closures have become more widely used. In all cynicism, however, I'd argue that with Python's very usable implementation of object-orientation, classes with __call__ methods frequently make for clearer demonstrations of solutions than closures do, despite requiring slightly more characters of source code, and in contrast to the apparent fashion for using closures for showing off more or less everything these days (despite various pitfalls which may seem counter-intuitive to the beginner). Paul From carsten at uniqsys.com Fri Aug 31 07:35:52 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 31 Aug 2007 07:35:52 -0400 Subject: list index() In-Reply-To: <1188534823.558722.212480@l22g2000prc.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188495863.242815.236900@o80g2000hse.googlegroups.com> <87bqcod2gq.fsf@benfinney.id.au> <1188517370.998114.119940@q4g2000prc.googlegroups.com> <1188530220.815429.281380@i38g2000prf.googlegroups.com> <1188534823.558722.212480@l22g2000prc.googlegroups.com> Message-ID: <20070831112153.M28189@uniqsys.com> On Thu, 30 Aug 2007 21:33:43 -0700, TheFlyingDutchman wrote > On Aug 30, 9:06 pm, "Carsten Haese" wrote: > > On Thu, 30 Aug 2007 20:17:00 -0700, zzbbaadd wrote > > > > > Well IN was what I was looking for and would have saved this thread. > > > However I don't believe IN showed up on the doc web page that has > > > list methods, where I found index(). > > > > They're not on the exact same page, but index() is in section 3.6.4 of the > > library reference (http://docs.python.org/lib/typesseq-mutable.html), whereas > > "in" is in section 3.6 of the library reference > > (http://docs.python.org/lib/typesseq.html). I'm wondering how you managed to > > find subsection 3.6.4 without finding section 3.6. > > www.google.com > > search "python list methods" > > first search find: > > 5. Data Structures > The list methods make it very easy to use a list as a stack, where > the last element added .... Another useful data type built into > Python is the dictionary. ... http://docs.python.org/tut/node7.html > > "The list data type has some more methods. Here are all of the > methods of list objects:" Fair enough, but that's a tutorial. It would be foolish to demand that a tutorial be a complete reference for everything that can be done with a list. The page lists all methods of list objects, but there are more things one can do with lists that don't look like method calls. For example, it doesn't say that you can compare lists. It doesn't say that you can read and write elements in the lists. Would you automatically assume that those things aren't possible? I hope not. (Of course, those operations are handled by the magical methods __eq__, __setitem__, __getitem__ etc, but I think one can forgive the tutorial for not mentioning those in the interest of not confusing beginners.) By your logic, no web page would be allowed to say anything about lists unless it says *everything* about lists, and that wouldn't be very useful. -- Carsten Haese http://informixdb.sourceforge.net From arkanes at gmail.com Wed Aug 8 09:50:00 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 8 Aug 2007 08:50:00 -0500 Subject: This bit of code hangs Python Indefinitely In-Reply-To: References: Message-ID: <4866bea60708080650w59e30402sc934336ed95b098@mail.gmail.com> On 8/8/07, brad wrote: > url_queue = Queue.Queue(256) > for subnet in subnets: > url_queue.put(subnet) > > The problem is that I have 512 things to add to the queue, but my limit > is half that... whoops. Shouldn't the interpreter tell me that I'm an > idiot for trying to do this instead of just hanging? A message such as > this would be more appropriate: > > "Hey fool, you told me to only accept 256 things and you're trying to > give me 512... what's up with that?" You should have read the Queue documentation first. Queues, by design, are producer/consumer streams and the producer is designed to block if the queue is full. You can use the put_nowait method to have it raise an exception instead of blocking. From gdonald at gmail.com Wed Aug 1 20:46:49 2007 From: gdonald at gmail.com (Greg Donald) Date: Wed, 1 Aug 2007 19:46:49 -0500 Subject: Wing IDE for Python v. 3.0 beta1 released In-Reply-To: <20070801212840.GA25065@spookie1.spookiegate> References: <46AF8ED7.2070206@wingware.com> <20070801212840.GA25065@spookie1.spookiegate> Message-ID: <15e66e4e0708011746v1bd74935t9b617f72af1bebe8@mail.gmail.com> On 8/1/07, John K Masters wrote: > If their support for paid customers is anything like their support for > prospective customers then I would leave well alone. I had no problems with their support whatsoever, really good in my opinion. They were very responsive and addressed all my questions over about a 3 or 4 day email conversation. -- Greg Donald http://destiney.com/ From bj_666 at gmx.net Wed Aug 8 06:45:15 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 8 Aug 2007 10:45:15 GMT Subject: Seek the one billionth line in a file containing 3 billion lines. References: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> <46b977e9$0$27390$ba4acef3@news.orange.fr> Message-ID: <5htl5qF3md0abU1@mid.uni-berlin.de> On Wed, 08 Aug 2007 09:54:26 +0200, M?ta-MCI \(MVP\) wrote: > Create a "index" (a file with 3,453,299,000 tuples : > line_number + start_byte) ; this file has fix-length lines. > slow, OK, but once. Why storing the line number? The first start offset is for the first line, the second start offset for the second line and so on. Ciao, Marc 'BlackJack' Rintsch From Shawn at Milochik.com Mon Aug 20 13:16:46 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Mon, 20 Aug 2007 13:16:46 -0400 Subject: I Need help from all the group participants In-Reply-To: References: <1187629313.357121.196370@q4g2000prc.googlegroups.com> Message-ID: <2dc0c81b0708201016h79b0ca5bp4a7e12fc2dee3ba9@mail.gmail.com> On 8/20/07, Boris Ozegovic wrote: > mensanator at aol.com wrote: > > > The only sentence that comes to mind is: > > > > "I hope I never find myself in a hospital that uses your system." > > You are not funny. The system isn't for hospitals, it is for university > purposes. > > -- > Ne dajte da nas la?ljivac Bandi? truje: > http://cnn.blog.hr/arhiva-2007-06.html#1622776372 > -- > http://mail.python.org/mailman/listinfo/python-list > I disagree. He is funny. Sorry you can't appreciate the humor -- it must be the language barrier. Lighten up and enjoy this life -- it's the only one we have. From steve at holdenweb.com Sun Aug 12 12:59:59 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 12 Aug 2007 12:59:59 -0400 Subject: Puzzled by "is" In-Reply-To: <20070812163657.2F8F41E400B@bag.python.org> References: <20070809194105.39BD11E400A@bag.python.org> <87zm1042f0.fsf@benfinney.id.au> <87ir7l5bv4.fsf@benfinney.id.au> <20070812163657.2F8F41E400B@bag.python.org> Message-ID: Dick Moores wrote: > At 08:23 AM 8/12/2007, Steve Holden wrote: >> Dick Moores wrote: >>> So would a programmer EVER use "is" in a script? >> Sure. For example, the canonical test for None uses >> >> x is None >> >> because there is only ever one instance of type Nonetype, so it's the >> fastest test. Generally speaking you use "is" to test for identity (do >> these two expressions reference the same object) rather than equality >> (do these two expressions evaluate to equivalent objects). > > Off the top of your head, could you or others give me as many > examples as you can think of? > Occasionally it's necessary to test for a specific type (though in Python this is usually bad practice). Since types are also singletons the best way to do this is (e.g.): type(x) is type([]) # test specifically for a list If you want to know whether you have been told to write to standard output, one possible test is if f is not sys.stdout Similarly, of course, you can test for the other standard IO channels. The imputil module contains the test if importer is not self to determine whether a reload() should be performed in the context of the current package. When you need to establish a specific sentinel value that can never be provided by an outside caller it's normal to create an instance of object (the simplest possible thing you can create in a Python program) and test for that instance, as in sentinel = object() ... if value is sentinel: You can test whether a class is new-style as opposed to old-style, which can help to unify old-style and new-style objects: class MetaProperty(type): def __new__(cls, name, bases, dct): if bases[0] is object: # allow us to create class Property return type.__new__(cls, name, bases, dct) return property(dct.get('get'), dct.get('set'), dct.get('delete'), dct.get('__doc__')) def __init__(cls, name, bases, dct): if bases[0] is object: return type.__init__(cls, name, bases, dct) That gets you started ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From gdonald at gmail.com Mon Aug 27 16:29:30 2007 From: gdonald at gmail.com (Greg Donald) Date: Mon, 27 Aug 2007 15:29:30 -0500 Subject: some problems with mod_python In-Reply-To: <1188245587.129794.258250@z24g2000prh.googlegroups.com> References: <1188245587.129794.258250@z24g2000prh.googlegroups.com> Message-ID: <15e66e4e0708271329l1fd9e4a0p905b4380178b70af@mail.gmail.com> On 8/27/07, Johan wrote: > This I added to httpd.conf > > AllowOverride All > AddHandler mod_python .py > PythonHandler mptest > PythonDebug On > This is the syntax I have working locally: # mod_python AddHandler python-program .py PythonHandler test PythonDebug On In particular my AddHandler directive is different from yours. -- Greg Donald http://destiney.com/ From python at jayloden.com Tue Aug 14 20:08:01 2007 From: python at jayloden.com (Jay Loden) Date: Tue, 14 Aug 2007 20:08:01 -0400 Subject: Python script for mobile platforms -- suggested? In-Reply-To: <496954360708140842s2e5b7c6ctb7a40aa4099719db@mail.gmail.com> References: <496954360708121958m170b6cd2j8419802dcdd35482@mail.gmail.com> <496954360708131727o5276d5a5w57baff6cbea4c34c@mail.gmail.com> <46C12274.2070705@jayloden.com> <496954360708140842s2e5b7c6ctb7a40aa4099719db@mail.gmail.com> Message-ID: <46C243E1.5020004@jayloden.com> Robert Dailey wrote: > Hi Jay, > > I apologize for not having been detailed enough. Right now I'm using a > C++ library known as TinyXML to parse my XML files. When a menu is to be > displayed, the XML is parsed and the appropriate images, text, etc that > will display on the menu is loaded based on the data in that XML. Note > that the XML parsing happens before the menu is drawn and only happens > once per menu as to avoid performance overhead during the menu drawing. TinyXML is pretty fast, and I'd wager to say that even without knowing what the Python code would be that replaces the XML, my guess is you'll take a performance (mem/cpu or both) hit, if for no other reason than introducing the Python interpreter overhead. > For example, to create a menu that has an image in the center of the > screen, the XML would be this: > > > > > > > > > > > The "Origin" and "Justification" elements act sort of like function > calls, and the "Frame" element defines an "Object" kind of. Each Frame > is a visual element in the Menu. > > I'm not sure if you'll agree or not, but even in this simple example > it's very hard to read just given the nature of the XML syntax. > Secondly, I'm not using XML as it was intended to be used. I'm using it > as a script instead of a representation of data. Most of the real menus > are 600+ lines of XML much like above, however it is not nearly as > simplistic. I will paste a real example of a menu below this email for > those curious to look at it. XML is first and foremost a machine-parseable language, and a human-readable one second ;) I don't think this is particularly hard to read, but then I work with XML configuration files on a daily basis at work, so I may just be a terrible person to ask... I'm not sure I agree that you're not using XML as it was intended; you're mixing data and presentation, but it's still a document containing data. That's what XHTML is, and what the XML document definitions like OOXML are all about. Anyway, that's neither here nor there. My question would be a much simpler "why is this XML?". XML makes sense when you need a structured document, and sometimes that makes sense for configuration options or defining a structure, but it's not clear why you'd need it here. Is this something you're intending to make editable by the end user? If you're willing to replace it with Python scripts instead of XML documents, it sounds like maybe you're not worried about letting users edit the menus. If so, why not code the menus direct into the main C++ code? This would be faster, unless you need to frequently edit these menus. > I haven't decided on what the Python version of the example above would > look like, that would probably happen sometime after I decided to go > with Python for a menu scripting replacement (If I do, that is). I might > mix XML and Python much like World of Warcraft mixes XML with LUA > script. Again, this all depends on design. The important points I wanted > to get across is that the Python script wont' be executed past the > construction of a menu. The Python/XML script would be simply there to > allow the game to create the menu and other important things. I think the best thing to do would be to take a step back and ask what it is that you're trying to do as the end result. What are your requirements; can you expect that Python will be installed already? Is the choice between parsing XML once with C++ or having to ship a Python interpreter with associated overhead? Once you have a set of requirements and determine what's most important to you it should make it easier to pick a solution. For instance, on a mobile device, you might simply not have the spare cycles that embedding a python interpreter would require versus a lightweight lib like TinyXML. Similarly, you'd have to ask yourself if the data is always static, or if you have a need for dynamic content (i.e. embedded scripting) within the menu definition. -Jay From david at nospam.spam Tue Aug 21 03:58:40 2007 From: david at nospam.spam (david) Date: Tue, 21 Aug 2007 17:58:40 +1000 Subject: wxPython before MainLoop In-Reply-To: References: <13bl9a75laqcm70@corp.supernews.com> <6a6dnfbbFJNzcCbbnZ2dnUVZ_oudnZ2d@comcast.com> Message-ID: <13cl6pgi23gp7a3@corp.supernews.com> > Looking at the Chandler code suggests a solution > ... he may need to call Update to finish painting > the display. Yes, and thank you to Chandler for pointing that out. Without the splash screen there was no need to call Yield or use a generator. (david) samwyse wrote: > Chris Mellon wrote: >> On 8/9/07, Heikki Toivonen wrote: >> >>> [david] wrote: >>> >>>> I'd like to refresh the display before I start the main loop. > > If your window isn't able to interact with the user, then I'd consider > it a splash screen, no matter if it does look exactly like your main > application interface. > >>> We have this kind of situation in Chandler, where we display and update >>> the splash screen before we enter MainLoop. >>> > [...] >>> 3. The splash screen refresh is basically: draw new stuff, >>> self.Layout(), self.Update(), wx.Yield() >>> http://lxr.osafoundation.org/source/chandler/application/Application.py#1421 >>> > > Looking at the Chandler code suggests a solution to [david]'s original > problem. It is possible that, on Windows only, he may need to call > Update to finish painting the display. > > 1432 self.Layout() > 1433 if wx.Platform == '__WXMSW__': > 1434 self.Update() > 1435 wx.GetApp().Yield(True) > >> wxYield spins the event loop in place. This can have some serious >> consequences if you aren't very careful with your usage, like >> recursively entering event handlers. I generally consider it an >> experts only interface, and avoid it. > > I'll confess to being one of those old-school programmers who, back in > the day, wrote his code around big select loops instead of using > threads, but I'm intriged by the "experts only" designation. Can > someone explain further? Thanks! From oliver at obeattie.com Sat Aug 4 18:52:06 2007 From: oliver at obeattie.com (oliver at obeattie.com) Date: Sat, 04 Aug 2007 15:52:06 -0700 Subject: Encoding DeprecationWarning In-Reply-To: <1186267419.999613.209480@q75g2000hsh.googlegroups.com> References: <1186254427.792114.173170@q75g2000hsh.googlegroups.com> <1186267419.999613.209480@q75g2000hsh.googlegroups.com> Message-ID: <1186267926.233392.238460@w3g2000hsg.googlegroups.com> On Aug 4, 11:43 pm, "oli... at obeattie.com" wrote: > >>> from wt.lib.misc_lists import all_countries > > __console__:1: DeprecationWarning: Non-ASCII character '\xc3' in file / > Django/wt/../wt/lib/misc_lists.py on line 141, but no encoding > declared; seehttp://www.python.org/peps/pep-0263.htmlfor details OK, well; no matter. Perhaps I should try actually reading the article it recommended and add: # -*- coding: utf-8 -*- To the file! What a doofus! Thanks, Oliver From ziade.tarek at gmail.com Sat Aug 11 10:06:12 2007 From: ziade.tarek at gmail.com (Tarek) Date: Sat, 11 Aug 2007 14:06:12 -0000 Subject: A new french book on Python Message-ID: <1186841172.271039.168200@22g2000hsm.googlegroups.com> Hello, A new french book is coming out on the 16th of august. It's focused on Python good practices, agility, and all the things that makes a Python developer loves the language. If you are interested, the web page is here : http://programmation-python.org/guide Regards Tarek From willmaier at ml1.net Tue Aug 7 18:02:09 2007 From: willmaier at ml1.net (Will Maier) Date: Tue, 7 Aug 2007 17:02:09 -0500 Subject: passing vars to py scipts in cron jobs In-Reply-To: References: Message-ID: <20070807220209.GX22017@lass.lfod.us> On Tue, Aug 07, 2007 at 05:45:46PM -0400, brad wrote: > What's the proper way to call a py script and pass in variables > while doing cron jobs? I can run the scripts fine from idle, > python, etc using raw_input() to prompt users. The scripts have > classes with methods that need arguments. This is commonly done with either sys.argv (a list of arguments passed when invoking the script) or os.environ (a dictionary of environment variables and values). Use either to instantiate your classes or run functions. -- [Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/] From greg at cosc.canterbury.ac.nz Fri Aug 10 04:58:40 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 10 Aug 2007 20:58:40 +1200 Subject: pep 3116 behaviour on non-blocking reads In-Reply-To: References: Message-ID: <5i2nt7F3ls70cU1@mid.individual.net> Antoon Pardon wrote: > I would like the developers to reconsider and return 0 bytes when no > bytes are available and let None indicate end of file. That would be a major departure from the way IO has always been handled before in Python, which follows the Unix model. Also, only code that deals with non-blocking streams will ever get None, and such code is relatively rare, so most code won't have to worry about the None case. Even when dealing with a non-blocking stream, usually there will be some other way (such as select) used to determine when there is something to be read from a stream, and it won't be read otherwise. In that case, the code *still* won't ever see a None. So I think the PEP has it right. -- Greg From steve at holdenweb.com Tue Aug 21 12:57:32 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 21 Aug 2007 12:57:32 -0400 Subject: Retrieving a variable's name. In-Reply-To: <1187658202.236626.93600@50g2000hsm.googlegroups.com> References: <1187658202.236626.93600@50g2000hsm.googlegroups.com> Message-ID: rodrigo wrote: > How would I go about retrieving a variable's name (not its value)? I > want to write a function that, given a list of variables, returns a > string with each variable's name and its value, like: > > a: 100 > b: 200 > > I get the feeling this is trivial, but I have been unable to find an > answer on my own. > So what would you want yourfunction(32) to return? None? Names in Python are references to values, and the same value can be reference by zero to many different names, so your request is close to nonsensical. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From toby at tobiah.org Wed Aug 22 14:19:43 2007 From: toby at tobiah.org (Tobiah) Date: Wed, 22 Aug 2007 11:19:43 -0700 Subject: How do I express a backslash in a string? Message-ID: <46cc723c$0$16263$88260bb3@free.teranews.com> >>> "'" "'" >>> "\'" "'" >>> "\\'" "\\'" >>> "\\\'" "\\'" >>> This is quite different than any other language that I am used to. Normally, a double backslash takes away the special meaning of the last backslash, and so you are left with a single backslash. How do I express the single backslash? Thanks, Tobiah -- Posted via a free Usenet account from http://www.teranews.com From steve at holdenweb.com Fri Aug 10 10:48:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 10 Aug 2007 10:48:30 -0400 Subject: wxPython before MainLoop In-Reply-To: <13bnh5bs4b9h427@corp.supernews.com> References: <13bl9a75laqcm70@corp.supernews.com> <13bnh5bs4b9h427@corp.supernews.com> Message-ID: [david] wrote: > [...] I don't think wxPython is really ready for Windows. > I don't think you are really ready to for GUIs ;-) Fortunately, it doesn't matter what *I* think. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From davidsamith at gmail.com Fri Aug 31 02:05:31 2007 From: davidsamith at gmail.com (davidsamith at gmail.com) Date: Fri, 31 Aug 2007 06:05:31 -0000 Subject: Coding Standards Message-ID: <1188540331.961231.36850@r23g2000prd.googlegroups.com> 'Good code' is code that works, is bug free, and is readable and maintainable. Standards need to be followed for coding. Read more... http://brsx.co.uk/SWtesting/FAQs/FAQs012.asp From jstroud at mbi.ucla.edu Fri Aug 3 21:45:59 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 03 Aug 2007 18:45:59 -0700 Subject: How to pass a reference to the current module In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > On Fri, 03 Aug 2007 17:22:40 -0700, James Stroud wrote: > > >>Basically, what I am trying to acomplish is to be able to do this in any >>arbitrary module or __main__: >> >> >>funcname = determined_externally() >>ModuleUser.do_something_with(AModule, funcname) >> >> >>Ideally, it would be nice to leave out AModule if the functions were >>designed in the same namespace in which do_something_with is called. > > > I second Carsten Haese's suggestion that instead of passing function > names, you pass function objects, in which case you don't need the module. > But perhaps you need some way of finding the function, given its name. > > def get_function_from_name(name, module=None): > if module is None: > # use the current namespace > namespace = locals() # or globals() if you prefer > else: > namespace = module.__dict__ > return namespace[name] > > This assumes that get_function_from_name is defined in the same module as the function named by name. However, I want this: Module Behavior ============== ==================================================== UserDefined1 Imports FunctionUser ThirdParty Contains User Functions (May be ==UserDefined1) FunctionUser do_something_with() and/or get_function_from_name() So the name-to-function mapping is done in FunctionUser but the function is actually defined in UserDefined1 (or ThirdParty if ThirdParty is different than UserDefined1). James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From ptmcg at austin.rr.com Thu Aug 30 03:22:27 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 30 Aug 2007 00:22:27 -0700 Subject: Python molecular viewer In-Reply-To: References: Message-ID: <1188458547.056668.177140@d55g2000hsg.googlegroups.com> On Aug 29, 8:31 am, Andy Cheesman wrote: > Dear People, > > I was wondering if people could recommend a simple molecular viewing > package written in python. I'm working in Theoretical chemistry and I'm > not after an all-singing dancing molecular rendering package(pymol does > that rather well) but a program which reads XYZ files and displays > simple structures which can be rotated in 3D > > Thanks > > Andy slut is an OpenGL wrapper that I found to be very intuitive to use, and comes with some simple "moving ball" animations, but the animations also can be panned, zoomed, and rotated. In your case, you wouldn't need to do the animation, just plot the balls in 3D and then pan and zoom to your heart's content. Here is a simple program that plots a series of points on a sphere: from slut import * # points on a sphere data = [ (1.0, 0.0, 0.0), (0.945, 0.0, -0.325), (0.789, 0.0, -0.613), (0.547, 0.0, -0.836), (0.246, 0.0, -0.968), (-0.083, 0.0, -0.997), (-0.402, 0.0, -0.916), (-0.677, 0.0, -0.735), ... (-0.078, 0.027, 0.997), (0.232, -0.080, 0.968), (0.517, -0.177, 0.836), (0.746, -0.256, 0.613), (0.895, -0.307, 0.325), (0.945, -0.325, 0.0) ] from slut import * class SphereViewer(World): def onSetup(self): self.width = 400 self.height = 400 self.name = "Points on a Sphere" def onDraw(self): # draw translucent sphere glColor4f(0.7, 0.7, 0.7, 0.5) sphere(0, 0, 0, 1.0) glColor4f(0.3, 0.3, 0.4, 1.0) # plot points on surface glPointSize(4) for d in data: point(*d) # connect points with path glLineWidth(1.5) lastd = data[-1] for d in data: line( *(lastd + d) ) lastd = d viewer = SphereViewer() viewer.run() And here is a short Wink video showing me working with a simplified version of this sphere: http://www.geocities.com/ptmcg/python/sphere1.htm. If you have your molecules' 3D coordinates, you should be able to just plot them, and then use slut to view the molecule. -- Paul From mail at microcorp.co.za Fri Aug 24 10:44:50 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 24 Aug 2007 16:44:50 +0200 Subject: Socket recv(1) seems to block instead of returning end of file. References: <13cric35jcjp336@corp.supernews.com> Message-ID: <015101c7e65d$843596c0$03000080@hendrik> "Grant Edwards" wrote: > On 2007-08-23, Dan Stromberg - Datallegro wrote: > > > Are you using sock.settimeout()? > > Hey, somebody snuck timeouts into the socket module when I wasn't > looking... > > > I agree with Grant though - posting a minimal snippet of code that > > replicates the problem would help us help you. In fact, it might help you > > help yourself :) > > Yup, in my experience attempting to produce a minimally failing > example will usually reveal what's wrong. > I am now extremely frustrated - I have spent most of the day mucking around with this, and now I have managed to lose the version that was giving me grief, and I can't remember what I have done. At the moment everything works, and detects remote comm loss, no matter what I do. So I must have done something stupid, and destroyed the evidence. Some mothers have children. Others have bad luck. My apologies for chasing you up like that, and thanks to all who responded. - Hendrik From tim.couper at scivisum.co.uk Tue Aug 28 14:14:20 2007 From: tim.couper at scivisum.co.uk (Tim Couper) Date: Tue, 28 Aug 2007 19:14:20 +0100 Subject: Jython 2.2 on Ubuntu In-Reply-To: <-YOdnW_k3p6Fy0nb4p2dnAA@bt.com> References: <-YOdnW_k3p6Fy0nb4p2dnAA@bt.com> Message-ID: <46D465FC.9050300@scivisum.co.uk> you need to ensure that the correct jython executable is in a directory which is on your on your path. I've just successfully test-subscribed to https://lists.sourceforge.net/lists/listinfo/jython-users. Maybe you could try again. Tim Dr Tim Couper CTO, SciVisum Ltd www.scivisum.com Neil Wallace wrote: > Hi all, > > I am a novice Python/Jython programmer, and Ubuntu user. > > Ubuntu still only supports only version 2.1 of Jython. I have used the > GUI installer of Jython 2.2, and installed it to the default > /root/jython2.2 directory. The install went without issues. > > However, typing ............jython --version > in a teminal still gives me ........ Jython 2.1 on java (JIT: null) > > What else do I need to do? > > regards > Neil. > > p.s. I posted this to the jython group hosted by sourceforge, but it > bounced. :-( > From joshua at eeinternet.com Wed Aug 1 19:28:44 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 01 Aug 2007 15:28:44 -0800 Subject: Bug in Time module, or in my understanding? References: <46B10DEA.4050005@jayloden.com> Message-ID: On Wednesday 01 August 2007 14:49, Jay Loden wrote: > Hope some of this helps It did, thanks! j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE From owntheweb at gmail.com Wed Aug 29 19:04:15 2007 From: owntheweb at gmail.com (Ultrus) Date: Wed, 29 Aug 2007 23:04:15 -0000 Subject: replacing xml elements with other elements using lxml In-Reply-To: <46D5A272.2000509@web.de> References: <1188399381.188639.289480@57g2000hsv.googlegroups.com> <46D5A272.2000509@web.de> Message-ID: <1188428655.300330.213430@r29g2000hsg.googlegroups.com> Stefan, I'm honored by your response. You are correct about the bad xml. I attempted to shorten the xml for this example as there are other tags unrelated to this issue in the mix. Based on your feedback, I was able to make following fully functional code using some different techniques: from lxml import etree from StringIO import StringIO import random sourceXml = "\ \ Stefan's fortune cookie:\ \ \ \ \ You will always know love.\ \ \ You will spend it all in one place.\ \ \ \ \ Your life comes with a lifetime warrenty.\ \ \ The end.\ " parser = etree.XMLParser(ns_clean=True, recover=True, remove_blank_text=True, remove_comments=True) tree = etree.parse(StringIO(sourceXml), parser) xml = tree.getroot() def reduceRandoms(xml): for elem in xml: if elem.tag == "random": elem.getparent().replace(elem, random.choice(elem)[0]) reduceRandoms(xml) reduceRandoms(xml) for elem in xml: print elem.tag, ":", elem.text One challenge that I face now is that I can only replace a parent element with a single element. This isn't a problem if an element only has 1 element, or just 1 element (this works above). However, if elements have more than one child element such as a element, followed by a element (like children of ), only the first element is used. Any thoughts on how to replace+append after the replaced element, or clear+append multiple elements to the cleared position? Thanks again :) From steven.bethard at gmail.com Tue Aug 21 13:31:44 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 21 Aug 2007 11:31:44 -0600 Subject: Module level descriptors or properties In-Reply-To: <1187700539.312552.89340@w3g2000hsg.googlegroups.com> References: <1187700539.312552.89340@w3g2000hsg.googlegroups.com> Message-ID: Floris Bruynooghe wrote: > When in a new-style class you can easily transform attributes into > descriptors using the property() builtin. However there seems to be > no way to achieve something similar on the module level, i.e. if > there's a "version" attribute on the module, the only way to change > that to some computation later is by using a getter from the start as > your public API. This seems ugly to me. > > Does anyone know of a better way to handle this? Better is of course subjective, but you can always do something like:: class ModuleWrapper(...): def __init__(self, module): ... ... x = property(...) sys.modules[__name__] = ModuleWrapper(sys.modules[__name__]) STeVe From gmcalendar at gmail.com Thu Aug 23 10:56:28 2007 From: gmcalendar at gmail.com (gmcalendar at gmail.com) Date: Thu, 23 Aug 2007 14:56:28 -0000 Subject: simple spider in python In-Reply-To: <1187879398.007797.128510@i13g2000prf.googlegroups.com> References: <1187876014.845912.236690@e9g2000prf.googlegroups.com> <1187879398.007797.128510@i13g2000prf.googlegroups.com> Message-ID: <1187880988.813113.20350@l22g2000prc.googlegroups.com> thanks everybody, soooo kind. I'll take a look at booth. have a nice day/night (depending on your latitude!) ^_^ ciao! From nikhilketkar at gmail.com Fri Aug 17 12:00:43 2007 From: nikhilketkar at gmail.com (nikhilketkar) Date: Fri, 17 Aug 2007 09:00:43 -0700 Subject: Can python threads take advantage of use dual core ? Message-ID: <1187366443.621295.97020@e9g2000prf.googlegroups.com> What are the implications of the Global Interpreter Lock in Python ? Does this mean that Python threads cannot exploit a dual core processor and the only advantage of using threads is in that computation and IO-bound operations can continue in parallel ? Thanks, Nikhil From uymqlp502 at sneakemail.com Fri Aug 31 16:27:19 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Fri, 31 Aug 2007 13:27:19 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> <1188537516.622167.115080@z24g2000prh.googlegroups.com> <1188585630.539835.242460@i38g2000prf.googlegroups.com> Message-ID: <1188592039.612652.223700@r23g2000prd.googlegroups.com> Steve Holden wrote: > Well that's a healthy attitude, but I am concerned that the Python > community should be as welcoming as possible, so I don't like the fact > that you feel you are being treated differently from anyone else. I certainly appreciate that. And I will try my best to refrain from the little personal zingers (and the big ones too). > > All you really need to test the pre-conditions of a function > > is a call at the top of the function to another function that checks > > the inputs. To test the > > post-conditions, you just need a call at the bottom of the function, > > just before the return, > > that checks the return values. Those functions can also check the > > invariants. Then you > > define a global variable to switch all the self-test functions on or > > off at once. > > > It does constrain functions to return only from the bottom of their > code, though, which not all Python functions currently do. Though > there's nothing to stop you putting the calls before every return. Oops! I didn't think of that. The idea of putting one before every return certainly doesn't appeal to me. So much for that idea. From furkankuru at gmail.com Mon Aug 20 06:30:42 2007 From: furkankuru at gmail.com (Furkan KURU) Date: Mon, 20 Aug 2007 13:30:42 +0300 Subject: building exe from script In-Reply-To: <1187602337.366419.92930@r29g2000hsg.googlegroups.com> References: <1187602337.366419.92930@r29g2000hsg.googlegroups.com> Message-ID: <3a4a8f930708200330v61d0d482o33f6f4a14afc14e6@mail.gmail.com> you can embed py2exe in your program. On 8/20/07, vedrandekovic at v-programs.com wrote: > Hello, > > Is there any solution for building exe file from python script > something like bbfreeze.When user write some script in > my program, it must compile script into exe without opening console > ( cmd ).I'am working on Windows XP SP2 and Python 2.5. > > > > Regards, > Vedran > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru From coyote_x at artcom.pl Fri Aug 31 08:34:46 2007 From: coyote_x at artcom.pl (Adam Kubica) Date: Fri, 31 Aug 2007 14:34:46 +0200 Subject: Pylons, SQLAlchemy, too many connections problem. References: Message-ID: On Fri, 31 Aug 2007 14:03:48 +0200, Adam Kubica wrote: > Hello. > > I have pylons 0.96 (SVN) and current SQLAlchemy (0.3.10), and I have bug > that > doesn't exist earlier. > > My connection code: > > import sqlalchemy.mods.threadlocal > from sqlalchemy import DynamicMetaData, objectstore > > metadata = DynamicMetaData( case_sensitive = False ) > > def db_connect( dsn ): > engine = create_engine( dsn, echo=False, echo_pool=False, > encoding='latin2', convert_unicode=True ) > metadata.connect( engine ) > > > command "netstat -an|grep 5432|grep ESTABLISHED|wc -l" displays one > more connection after each refresh of page until I have exceptions > such as: > > sqlalchemy.exceptions.DBAPIError: (Connection failed) > (OperationalError) FATAL: sorry, too many clients already > > What is wrong? Don't use DynamicMetaData(), use MetaData(), it's the problem. From gagsl-py2 at yahoo.com.ar Sun Aug 19 15:40:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 19 Aug 2007 12:40:25 -0700 Subject: Overriding Thread.join in derived class. In-Reply-To: <1187422280.018913.184990@q3g2000prf.googlegroups.com> References: <1187422280.018913.184990@q3g2000prf.googlegroups.com> Message-ID: <1187552425.752125.302290@a39g2000hsc.googlegroups.com> On 18 ago, 04:31, Graham Dumpleton wrote: > If one creates a thread using threading.Thread and makes it a daemon > by calling setDaemon(), then when Python is exiting it will not > attempt to call join() on that thread and wait for it to complete > first. [...] > End result is that it could result in a Python exception at some > point, evidenced by messages starting with: > Exception in thread Thread-1 (most likely raised during interpreter > shutdown) [...] > > In order to avoid this, do people think that as an alternative to > creating daemonised thread that it would be reasonable to create a > derived Thread class for the particular task which overrides > Thread.join() method to set some flag or otherwise take some action > that the thread would notice to tell it to stop, and then call base > class Thread.join(). > > This way you can flag the thread to shutdown automatically when Python > is going around calling join() on non daemonised threads. > > Or am I missing the obvious as far as ways of flagging threads to tell > them to stop? > > Note that this is where Python is being used embedded in a C program. > There is no Python main function where code can be put to signal > threads to otherwise stop. This last statement is important. You need "some" way to tell the threads to stop working. Usually the thread's run() method is a big loop; you need to tell it somehow to exit the loop. By example, if you are using a Queue, put a sentinel object in it; or use an Event object; or at least a global variable. Overriding thread.join() as you suggest above may be a good place to do that, if you don't have another chance. -- Gabriel Genellina From fabiofz at gmail.com Mon Aug 13 06:37:58 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 13 Aug 2007 07:37:58 -0300 Subject: Eclipse/PyDev question In-Reply-To: <1186998539.030727.279330@g4g2000hsf.googlegroups.com> References: <1186998539.030727.279330@g4g2000hsf.googlegroups.com> Message-ID: On 8/13/07, king kikapu wrote: > > Hi, > > i am using Eclipse (Platform Runtime binary) with PyDev and i was > wondering if someone can help me with this: > > 1. I set breakpoints to a .py file and i have told Eclipse to open the > Debug perspective when it sees that some .py file(s) of my project > indeed contains breakpoints. So, i press F9, Eclipse starts, Debug > perspective opens and i can use the debugger just fine. But when the > app terminates, how can i tell Eclipse to switch automatically to the > PyDev perspective and not remain in the Debug one ? There's no currently no automatic' way to do this (but you can use Ctrl+F8 to iterate your perspectives, Ctrl+F7 for your views and Ctrl+F6 for your editors, so, it should be easy to go to wherever you want in the interface). 2. Let's say we have a project that consists of some .py files. I want > to press F9 when the editor displays anyone of these files but make > Eclipse to run the whole project (that has another .py as "default") > and not the script that i am currently working on, is that possible ?? You should do F9 in you current editor and then Ctrl+F11 to re-run the last run -- so, if you have a main file that you just ran in your project, you can probably just keep to Ctrl+F11 -- note that this behavior changed with Eclipse 3.3, but you can restore it: window > preferences > run/debug > launching > always launch the previously launched application. Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Wed Aug 15 12:14:20 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 15 Aug 2007 09:14:20 -0700 Subject: ctypes windll question In-Reply-To: <1187084704.869276.317030@r34g2000hsd.googlegroups.com> References: <1187084704.869276.317030@r34g2000hsd.googlegroups.com> Message-ID: <1187194460.677426.36950@r34g2000hsd.googlegroups.com> On Aug 14, 11:45 am, Tzury wrote: > I followed the tutorial about ctypes and I still cannot figure out how > to call a method of a calss within the dll. ctypes interfaces with C, not C++. C++ compilers do various forms of name manging, create virtual tables, etc. that are compiler dependent. You cannot call C++ from ctypes. From stargaming at gmail.com Wed Aug 1 12:55:53 2007 From: stargaming at gmail.com (Stargaming) Date: 01 Aug 2007 16:55:53 GMT Subject: Assertion in list comprehension References: <1185982643.001546.138180@e16g2000pri.googlegroups.com> Message-ID: <46b0bb19$0$14060$9b622d9e@news.freenet.de> On Wed, 01 Aug 2007 11:28:48 -0500, Chris Mellon wrote: > On 8/1/07, beginner wrote: >> Hi, >> >> Does anyone know how to put an assertion in list comprehension? I have >> the following list comprehension, but I want to use an assertion to >> check the contents of rec_stdl. I ended up using another loop which >> essentially duplicates the functions of list comprehension. It just >> look like a waste of coding and computer time to me. >> >> I just wish I could put the assertions into list comprehensions. >> >> x=[(rec_stdl[0].st/10000.0, >> rec_stdl[0].cl, >> rec_stdl[0].bb, >> rec_stdl[0].bo, >> rec_stdl[1].bb, >> rec_stdl[1].bo, >> rec_stdl[0].ex >> ) >> for rec_stdl in rec_by_ex if len(rec_stdl)==2 >> ] >> >> #duplicated loop >> if __debug__: >> for rec_stdl in rec_by_ex: >> l=len(rec_stdl) >> assert(l<=2 and l>0) >> if l==2: >> assert(rec_stdl[0].c=="C" and rec_stdl[1].c=="P") >> assert(rec_stdl[0].ex==rec_stdl[1].ex) >> assert(rec_stdl[0].st==rec_stdl[1].st) >> assert(rec_stdl[0].cp==rec_stdl[1].cp) > > First: All your asserts are wrong. Assert is a statement, not a > function. These specific ones will behave as expected, but it's easy to > accidentally write ones that always pass this way. Could you come up with an example? I can only think of accidentally injecting a comma, what would create a (true, in a boolean context) tuple. And, well, if you're only using () for readabilty, this might sometimes look messy when calling assert with the extended syntax:: assert(False), "error text" Where one could expect the construction of a tuple. > Secondly: This is a waste of code, because if __debug__ is not defined > asserts will be skipped by the compiler. You could use the same loop > block for both branches. Well, the `assert` isn't there for no reason, but if you're serious about it, `raise` could be better. > Thirdly: This sort of testing is precisely what unit tests and/or > doctests are for. Huh? What beginner is doing there seems more like input validation than testing. Unit or doctests are meant for testing (and in case of doctests, showing) whether a function works as expected. From robert.kern at gmail.com Fri Aug 24 15:58:01 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 24 Aug 2007 14:58:01 -0500 Subject: Co-developers wanted: document markup language In-Reply-To: <46CEAF71.3050900@freakmail.de> References: <87odgyyx9u.fsf@wilson.homeunix.com> <87tzqpew22.fsf@wilson.homeunix.com> <87tzqp77my.fsf@wilson.homeunix.com> <7xy7g1if24.fsf@ruckus.brouhaha.com> <87mywh717i.fsf@wilson.homeunix.com> <46CEAF71.3050900@freakmail.de> Message-ID: Wildemar Wildenburger wrote: > Torsten Bronger wrote: >> Hall?chen! >> > Yes, you're German. Have you ever noticed that (we) Germans are > virtually the only ones that feel the need to rub our nationality into > everyones faces? ;) Howdy! We Americans do the same. ;-) -- 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 ajmacd at ns.sympatico.ca Sun Aug 12 16:30:45 2007 From: ajmacd at ns.sympatico.ca (Aaron J. M.) Date: Sun, 12 Aug 2007 13:30:45 -0700 Subject: Pausing and Unpausing Threads In-Reply-To: <13bulsklq359q8f@corp.supernews.com> References: <1186883176.319755.304970@d55g2000hsg.googlegroups.com> <13bulsklq359q8f@corp.supernews.com> Message-ID: <1186950645.886995.56060@w3g2000hsg.googlegroups.com> On Aug 12, 3:55 pm, Dennis Lee Bieber wrote: > By this definition, if there is no "action" supplied, a > "DirectedControler" will result in blocking ALL others (directed or not) > in this "server" (as it blocks the entire server thread). > > Is that really the behavior you want? For my particular application, yes. This is exactly what I want. > I'd suggest using a Queue PER directed controller. Initialize > > self._actions = Queue.Queue() > > -=-=-=-=-=- > > def turn(self): > while True: > atn = self._actions.get() #blocks until at least one entry > if atn and atn.execute(): #should be in a try/except if > # action has NO execute method > break #did something, so exit while > > -=-=-=-=-=- > > def setAction(self, action): > self._actions.put(action) #could add code to ensure > #an execute attribute Thank you very much for your help. :) I'll get to work on this now. Cheers, Aaron J. M. From vodela.sai at gmail.com Thu Aug 16 15:07:59 2007 From: vodela.sai at gmail.com (Rohan) Date: Thu, 16 Aug 2007 19:07:59 -0000 Subject: Help me!! Message-ID: <1187291279.545324.205610@i38g2000prf.googlegroups.com> I have the following piece of code a = len(ab_file) b= 0 while(b References: <1188574962.185775.274420@d55g2000hsg.googlegroups.com> Message-ID: <1188578804.717125.121510@r23g2000prd.googlegroups.com> >python has modules for forms and other things... and for it? Check out httplib and urlib2, it might be useful for you. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Aug 1 06:04:41 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 01 Aug 2007 12:04:41 +0200 Subject: standalone process to interact with the web In-Reply-To: <1185909098.952860.217190@j4g2000prf.googlegroups.com> References: <1185899130.331170.151980@e16g2000pri.googlegroups.com> <1185904623.754078.198910@e9g2000prf.googlegroups.com> <1185909098.952860.217190@j4g2000prf.googlegroups.com> Message-ID: <46b05aac$0$31743$426a74cc@news.free.fr> beginner a ?crit : (snip) > Yes exactly. I just don't want to reinvent the wheel as I imagine > there are already tons of libraries and frameworks that support RPC or > the like functions. Why go thru the pain of RPC, SOAP or such bloated horrors ? Why not just use plain old HTTP with a RESTful API ? Then you just need to make your app wsgi compliant. From dwahler at gmail.com Sat Aug 11 17:36:58 2007 From: dwahler at gmail.com (David Wahler) Date: Sat, 11 Aug 2007 16:36:58 -0500 Subject: Something in the function tutorial confused me. In-Reply-To: References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <5hsoi3F3mlni2U1@mid.individual.net> <1186581124.3383.55.camel@dot.uniqsys.com> <1i2nhxn.tme05x17r39odN%aleax@mac.com> Message-ID: On 8/11/07, Gregory D. Weber wrote: > I too thought += was an assignment. And it bit me very painfully a few weeks ago. > > If it's an assignment, then wouldn't "x += y" mean the same thing as "x = x + y"? > > If so, why does an assignment to variable a, below, have the *side effect* of changing variable b ... ? > > >>> a = [1, 2, 3] > >>> b = a > >>> b > [1, 2, 3] > >>> a += [4] > >>> a > [1, 2, 3, 4] > >>> b > [1, 2, 3, 4] > > ... but using the "x = x + y" style, the assignment to variable c, below, does *not* have a side effect on variable d (as indeed it should not!)? > > >>> c = [1, 2, 3] > >>> d = c > >>> d > [1, 2, 3] > >>> c = c + [4] > >>> c > [1, 2, 3, 4] > >>> d > [1, 2, 3] >>> help(list.__iadd__) Help on wrapper_descriptor: __iadd__(...) x.__iadd__(y) <==> x+=y For mutable (built-in) objects such as lists, __iadd__ modifies the list and then returns the list object; for immutable objects, __iadd__ is equivalent to __add__ and just returns the new value. However, in both cases, the result is then rebound to x. This can lead to some behaviors you might not normally expect: >>> t = ([],) >>> t[0] += [1] Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment >>> t ([1],) -- David From zxo102 at gmail.com Thu Aug 2 23:46:44 2007 From: zxo102 at gmail.com (zxo102) Date: Thu, 02 Aug 2007 20:46:44 -0700 Subject: Help: GIS Message-ID: <1186112804.718290.207580@z24g2000prh.googlegroups.com> Hi, I am new in GIS area and need your suggestions for where I can start from. I have a python based web application with a database. Now I would like to add a GIS map into my application. When a user clicks a certain area in the GIS map, it can grab the data from the database via my python based application. Do I have to use MapServer or Grass or some other backends for this purpose? Thanks a lot. Ouyang From jjl at pobox.com Sun Aug 5 16:46:14 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 05 Aug 2007 20:46:14 GMT Subject: Misleading wikipedia article on Python 3? References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> Message-ID: <877io9soa1.fsf@pobox.com> "Martin v. L?wis" writes: >> I'm surprised to read this: >> >> http://en.wikipedia.org/wiki/Python_3 >> >> """Note that while there is no explicit requirement that code be able >> to run unmodified in both versions, in practice it is quite likely for >> most code. As of January 2007, it looks like most reasonable code >> should run quite well under either branch.""" > > It's difficult to predict the future, but I think this statement is > a fair description. > >> >> I haven't been following Python 3 development recently. Have things >> really changed that much? Last time I looked, e.g. dict.items() no >> longer returned a list. > > Correct. > >> Seems unlikely that most code will run on 2 >> and 3, in that case, > > Why that? Most reasonable code doesn't care what dict.items returns, > as it reads like > > for k,v in dict.items(): > do_something_with(k,v) We could discuss that. However, my example wasn't really intended to relate strictly to that technical feature. Rather, to the intent of the Python 3 developers, as suggested by things like that change, and by what they've said over the last year or so (I think I've seen that specific change used several times by people explaining that 2.6 / 3.0 compatibility will be impractical, which is why I chose it). >> and IIUC Guido has said all along that not much >> code will run on both. > > I think you misunderstood. It's not a design goal that code works > without modifications, yet most reasonable code will even without > that being an explicit goal. I think the design goals have been fairly clear. What hasn't been clear (to me, at least) is the practical question of the feasibility of code working unchanged on both 2.6 and 3.0. http://www.python.org/dev/peps/pep-3000/ """There is no requirement that Python 2.6 code will run unmodified on Python 3.0. Not even a subset. (Of course there will be a tiny subset, but it will be missing major functionality.)""" Though certainly neither quote is precise enough to pin it down formally, certainly the tone of the first quote (from the Wikipedia article) to my ear makes it sound like (at minimum!) it will be practical for most projects, if they do the work to support both 3.0 and 2.6, to run simultaneously on 2.6 and 3.0 without use of a translation tool. The second quote makes it sound like that will be highly impractical. That picture is reinforced by what follows (in PEP 3000): """ The recommended development model for a project that needs to support Python 2.6 and 3.0 simultaneously is as follows: 0. You should have excellent unit tests with close to full coverage. 1. Port your project to Python 2.6. 2. Turn on the Py3k warnings mode. 3. Test and edit until no warnings remain. 4. Use the 2to3 tool to convert this source code to 3.0 syntax. Do not manually edit the output! 5. Test the converted source code under 3.0. 6. If problems are found, make corrections to the 2.6 version of the source code and go back to step 3. 7. When it's time to release, release separate 2.6 and 3.0 tarballs (or whatever archive form you use for releases). It is recommended not to edit the 3.0 source code until you are ready to reduce 2.6 support to pure maintenance (i.e. the moment when you would normally move the 2.6 code to a maintenance branch anyway). """ So which is it? That is, will it be practical for most projects to support 2.6 and 3.0 simultaneously, from the same codebase, without relying on translation tools? I'm assuming the practicalities of this *are* clear by now to the Python 3 developers -- is that right? It seems to me that if I don't understand what the Python 3 developers expect the practicalities to be, most other interested people won't either ("interested" in the opposite sense to "disinterested" rather than to "uninterested"). John From ah at neznamkojamijeemailadre.sa Mon Aug 20 13:48:44 2007 From: ah at neznamkojamijeemailadre.sa (=?iso-8859-2?B?qXXmTXXmUGFQcm9saWo=?=) Date: Mon, 20 Aug 2007 19:48:44 +0200 Subject: I Need help from all the group participants References: <1187629313.357121.196370@q4g2000prc.googlegroups.com> Message-ID: "Shawn Milochik" wrote in message news:mailman.0.1187630213.32294.python-list at python.org... > On 8/20/07, Boris Ozegovic wrote: >> mensanator at aol.com wrote: >> >> > The only sentence that comes to mind is: >> > >> > "I hope I never find myself in a hospital that uses your system." >> >> You are not funny. The system isn't for hospitals, it is for university >> purposes. >> >> -- >> Ne dajte da nas la?ljivac Bandi? truje: >> http://cnn.blog.hr/arhiva-2007-06.html#1622776372 >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > I disagree. He is funny. Sorry you can't appreciate the humor -- it > must be the language barrier. > hahahahahahahahahahahahaha From antroy at gmail.com Sat Aug 11 18:25:28 2007 From: antroy at gmail.com (Ant) Date: Sat, 11 Aug 2007 15:25:28 -0700 Subject: The Future of Python Threading In-Reply-To: <1186807396.988368.201400@b79g2000hse.googlegroups.com> References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <1i2njyp.1o6yslqe7ff47N%luc@honk-honk.com> <1186782710.600889.245930@j4g2000prf.googlegroups.com> <1186802188.653072.236260@x40g2000prg.googlegroups.com> <1186807396.988368.201400@b79g2000hse.googlegroups.com> Message-ID: <1186871128.210582.27300@k79g2000hse.googlegroups.com> On Aug 11, 5:43 am, Seun Osewa wrote: > > I think I've heard Guido say the last attempt at removing the Global > > Interpreter Lock (GIL) resulted in a Python that was much slower... > > What is it about Python that makes a thread-safe CPython version much > slower? Why doesn'ttrue threading slow down other languages like Perl > and Java? I have no idea about Perl - but there's probably some hideous black magic going on ;-) As for Java, making code thread safe *does* slow down the code. It is the very reason that the language designers made the collections API non-thread safe by default (you have to wrap the standard collections in a synchronised wrapper to make them thread safe). -- Ant... From bjourne at gmail.com Thu Aug 23 08:20:21 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Thu, 23 Aug 2007 14:20:21 +0200 Subject: advice about `correct' use of decorator In-Reply-To: <1187792001.935204.42330@e9g2000prf.googlegroups.com> References: <46C4B097.4080309@fmed.uba.ar> <740c3aec0708170529s6f7e7fe2l8c92771c2d0a51d4@mail.gmail.com> <46C5C9AE.5020508@fmed.uba.ar> <1187792001.935204.42330@e9g2000prf.googlegroups.com> Message-ID: <740c3aec0708230520h6a92a29ar180efed41730f563@mail.gmail.com> On 8/22/07, Gabriel Genellina wrote: > On 22 ago, 10:00, "BJ?rn Lindqvist" wrote: > > As I said, you can accomplish the exact same thing by calling a > > function from within the function that requires the user to be logged > > in. > > > > def change_pass(): > > check_user_logged_in() > > ... more stuff here... > > > > is less complex (and therefore preferable) than: > > > > @check_user_logged_in > > def change_pass(): > > ... more stuff here... > > > > An important principle in engineering is that you should always strive > > to make your design as simple as possible. If you have two equal > > designs, you should always choose the one that is simpler because > > simple things are easier to understand than complex things. > > I don't see the complexity in this case - both are a single line of > code. Any internal complexity is hidden by the language. In fact, I "Hiding" doesn't reduce complexity, quite the opposite. > consider the decorated function simpler than the other: its body > represents exactly what the function does, without any distracting > precondition calls. Think about how the decorator is implemented. It is a high order function, taking a function and returning a new function. Something like this: def check_user_logged_in(func): def f(*args, **kwargs): if global_state.the_user.is_logged_in: return func(*args, **kwargs) return show_login_page() return f @check_user_logged_in def change_pass(): ... more stuff here... or: def check_user_logged_in(): return global_state.the_user.is_logged_in def change_pass(): if not check_user_logged_in(): return show_login_page() ... more stuff here ... or even: def change_pass(): if not global_state.the_user.is_logged_in: return show_login_page() ... more stuff here ... > The decorator has some advantages: can have syntax support on your > editor, can perform some registering/logging, it's even easier to > quickly check visually if it's here. The decorator has just as many disadvantages. For example, what if you want to redirect back to the change_pass page once the user has pressed the Login button on the login_page? Or if you want to show different login pages depending on user properties? How much control flow do you really want to "hide" in your decorator? -- mvh Bj?rn From nick at craig-wood.com Sat Aug 18 07:30:05 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 18 Aug 2007 06:30:05 -0500 Subject: Python and Tkinter Programming--Expensive! References: Message-ID: W. Watson wrote: > Why is the book in Subject (author is Grayson) so expensive? $100 on Amazon > and $195 on ABE. Aren't there alternatives? There is an excellent section (266 pages) on TKinter in "Programming Python" by Mark Lutz. I've got the 2nd edition. Lutz concentrates on TK programming using classes, making re-usable components which I found really helpful compared to the ad-hoc way I'd seen TK presented previously. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From edgrsprj at ix.netcom.com Thu Aug 30 22:04:31 2007 From: edgrsprj at ix.netcom.com (E.D.G.) Date: Thu, 30 Aug 2007 20:04:31 -0600 Subject: Important Research Project References: <13ddcvm1bsu3s94@corp.supernews.com> <46D6CA0E.E66ED5C8@yahoo.com> Message-ID: <13deq9nj9atft62@corp.supernews.com> "CBFalconer" wrote in message news:46D6CA0E.E66ED5C8 at yahoo.com... > "E.D.G." wrote: > Where is Perl described in the C standard? This seems rather OT. It has been my experience that a person who is an expert with one computer language can usually do reasonably well when working with other languages. I am trying to find some people who can assist with getting a Perl program running. It would probably be easier for expert programmers in any language to help with this type of work compared with people such as myself who are not experts in any programming language. From ldo at geek-central.gen.new_zealand Mon Aug 27 04:35:51 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 27 Aug 2007 20:35:51 +1200 Subject: Chaining programs with pipe References: <1187734166.384152.178040@o80g2000hse.googlegroups.com> <13cnbi87neru8c3@corp.supernews.com> <13cogr3n6no937b@corp.supernews.com> <1187795716.083417.299540@q4g2000prc.googlegroups.com> Message-ID: In message <1187795716.083417.299540 at q4g2000prc.googlegroups.com>, Gabriel Genellina wrote: > On 22 ago, 11:08, Grant Edwards wrote: > >> but I'm a Unix guy who occasionally tries >> to ship a Windows version of a Python app: the concept of a >> process defaulting to having a stderr or stdout that wasn't >> writable was utterly foreign to me. > > Ah, that explains your previous post telling that things on Windows > don't work as they "should". They work, but not necesarily as a > "foreigner" would expect. So what's the good reason for Windows having unusable defaults for stderr and stdout, then? From nick at craig-wood.com Tue Aug 28 07:30:07 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 28 Aug 2007 06:30:07 -0500 Subject: Python's Suitability? References: Message-ID: Michael R. Copeland wrote: > I have some questions about the suitability of Python for some > applications I've developed in C/C++. These are 32 bit Console > applications, but they make extensive use of STL structures and > functions (Lists, Maps, Vectors, arrays) - primarily because the data > volume is high (2,500,000+ records). This is all bread and butter stuff to python and 10 times easier to do in python than C++! > The main thing I'd like to do is port one part of the system that has > a series of user menus and works with several text data files (one > _very_ large). I'm not using any database system, just my home-grown > indexed sequential file database. There's nothing but volume that > precludes this application from running from almost any text file- > processing language system (e.g. Perl, BASIC, etc.). > From what little I've seen of Python, it appears I could port this > application to Python code, but I'd do so only if I could: > 1. Integrate it into a Web application in such a way that the user > could select it as an option from a main page and have it execute as a > WEB GUI application. Currently, the application's interface is only a > crude DOS window. A web application is possible. You can start your application which would run its own embedded web server which the user could then control. Python has a web server in the standard library. I've done exactly this using cherrypy as a simple web application framework. The asynchronous nature of web applications are often a pain. You could write a windows GUI using TKinter (which comes with python) or WxPython (which doesn't). Those toolkits make it very easy to make GUI applications. > 2. Assure that the performance isn't totally crippled by using Python, > an interpretted language. While I don't expect native C/C++ > performance, I don't want to be embarrassed... Depends exactly what you are doing. If you are IO limited then Python is just as fast as C++. If you are doing lots of calculation on the data then python can be slow. You can use the numpy library which is a library of scientific maths routines all coded in C for speed which is very quick. http://numpy.scipy.org http://sourceforge.net/projects/numpy > 3. Make sure that the volume of stored data (2.5+ million records) can > be accommodated in Python structures (I don't know enough about Python > to answer this question...). I wouldn't have thought that would be a problem. > Note that I'm not considering using the existing C/C++ code in my Web > application, because I don't know how to write a C/C++ Windows > application - and I'm sure the learning curve here is greater than > Python's. You could always use ctypes from python to interface with your C code. If you can export your code in a DLL then ctypes can use it. (Not sure about C++ though) > I'm a very old procedural-based application developer (47+ > years of programming experience), and developing Windows applications is > beyond me. > So, I only (?) want to take an existing application that uses a large > text file (and several smaller text indexing files) and put it into a > Web system I already have. I feel Python (or Perl) is(are) my best > option(s), and here I'm only looking for some initial guidance from the > Python users. TIA Go for it! Python is such an easy language to write stuff in (escpecially compared to C++) that you'll have the prototype done very quickly and you can evaluate the rest of your concerns with working code! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From hniksic at xemacs.org Thu Aug 9 17:55:27 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 09 Aug 2007 23:55:27 +0200 Subject: Puzzled by "is" References: <20070809194105.39BD11E400A@bag.python.org> Message-ID: <87ejicl6eo.fsf@mulj.homelinux.net> Grzegorz S?odkowicz writes: >> Seriously, it's just an optimization by the implementers. There is >> no need for more than one empty tuple, since tuples can never be >> modified once created. >> >> But they decided not to create (1, ) in advance. They probably knew >> that hardly anybody would want to create that tuple ;-) [Seriously: >> if you started trying to predict which tuples would be used you >> would go insane, but the empty tuple is the most likely candidate]. >> > That's just theorisation but I'd rather expect the interpreter simply > not to create a second tuple while there already is an identical > one. But then tuple creation would be slowed down by searching for whether an "identical one" already exists. In the general case, that is quite unlikely, so it's not done. (I suspect that only the requirement to store the list of all tuples somewhere would outweigh any potential gains of this strategy; and if the search were implemented as a hash table lookup, even more space would be wasted.) It's done for the empty tuple because no search is necessary, only a size test. > Admittedly the empty tuple is a special case but then 'Special cases > aren't special enough to break the rules'. Except no rule is being broken. As others have pointed out, since tuples are immutable, caching them is quite safe. From bdesth.quelquechose at free.quelquepart.fr Thu Aug 30 08:59:19 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 30 Aug 2007 14:59:19 +0200 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188517050.174081.265900@x40g2000prg.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> <1188430887.481586.106760@l22g2000prc.googlegroups.com> <1188504811.019632.186580@x35g2000prf.googlegroups.com> <46d75116$0$401$426a74cc@news.free.fr> <1188517050.174081.265900@x40g2000prg.googlegroups.com> Message-ID: <46d75d33$0$6231$426a34cc@news.free.fr> Russ a ?crit : > Bruno Desthuilliers wrote: > >>Russ a ?crit : >>(snip) >> >> >>>I don't see how you can avoid adding some new syntax, given that >>>Python does not >>>currently have syntax for specifying invariants and pre- and post- >>>conditions. >> >>class Parrot(object): >> @pre(lambda x : x != 42) >> @post(lambda result: result != 42) >> @invariant(lambda self: self.x == 42) >> def reliable_method(self, x): >> # your code here >> return something > > > That looks like new syntax to me. It's the syntax for decorator functions, and it's not that new - it cames with Python 2.4, released November 30, 2004. > Did I miss your point? Yes. From aisaac at american.edu Fri Aug 31 00:55:00 2007 From: aisaac at american.edu (Alan Isaac) Date: Fri, 31 Aug 2007 04:55:00 GMT Subject: create Powerpoint via com In-Reply-To: <1188500822.869925.194430@e9g2000prf.googlegroups.com> References: <1188500822.869925.194430@e9g2000prf.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > OK, creating bulleted lists, or tables, or adding pictures is all straightforward. How about chart creation (in Ppt 2003)? I do not see how to do this with Python. Thanks, Alan From linnewbie at gmail.com Sun Aug 12 13:21:02 2007 From: linnewbie at gmail.com (linnewbie at gmail.com) Date: Sun, 12 Aug 2007 17:21:02 -0000 Subject: Regular Expression Grouping Message-ID: <1186939262.144073.182450@z24g2000prh.googlegroups.com> Fairly new to this regex thing, so this might be very juvenile but important. I cannot understand and why 'c' constitutes a group here without being surrounded by "(" ,")" ? >>>import re >>> m = re.match("([abc])+", "abc") >>> m.groups() ('c',) Grateful for any clarity. From Jameson.Quinn at gmail.com Mon Aug 27 17:35:35 2007 From: Jameson.Quinn at gmail.com (Jameson.Quinn at gmail.com) Date: Mon, 27 Aug 2007 14:35:35 -0700 Subject: "Try:" which only encompasses head of compound statement Message-ID: <1188250535.607963.42540@22g2000hsm.googlegroups.com> I have: try: for line in open(myFileName): count += 1 except IOError: print "Can't open myfile" (I know, this is bad, I never close the file, but its just for illustration). But then I change it to: try: for line in open(myFileName): count += openAndProcessSubfile(line) except IOError: print "Can't open myfile" ... now the 'except' incorrectly catches errors from openAndProcessSubfile. Of course, I can always do: try: myFile = open(myFileName) except IOError: print "Can't open myfile" for line in myFile: count += openAndProcessSubfile(line) ...But if my compound statement is "with" instead of "for" that seems to defeat the purpose: try: myFile = open(myFileName) except IOError: print "Can't open myfile" with myFile as anotherNameForMyFile: .... This is not a very readable "with" statement, I end up giving the same thing two names, and there's a moment when the above code doesn't know to close myFile. It's hard to imagine a good idiom to fix this. The best I can do is: for line in open(myFileName) exceptHead IOError: print "Can't open myfile" count += openAndProcessSubfile(line) exceptHead would be usable as the first indented line in any compound statement, and would catch any errors raised by the preceding line only. The bad thing about this (besides the silly name exceptHead) is that after the except block, control flow would skip the entire compound statement including else blocks. From max at alcyone.com Fri Aug 31 05:37:15 2007 From: max at alcyone.com (Erik Max Francis) Date: Fri, 31 Aug 2007 02:37:15 -0700 Subject: list index() In-Reply-To: <1188551958.728836.137370@x35g2000prf.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188497498.3468.60.camel@dot.uniqsys.com> <0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net> <1188551958.728836.137370@x35g2000prf.googlegroups.com> Message-ID: Paddy wrote: > I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll > and role similarly. > > My accent is probably from the East Midlands of the UK, but is not > pronounced. _Troll_ and _frolic_ aren't pronounced with the same "o" sound in any accent I've ever heard of. Which you pronounce _boat_ and _bot_ the same way, too? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis There are no dull subjects. There are only dull writers. -- H.L. Mencken From mcl.office at googlemail.com Sun Aug 26 15:43:13 2007 From: mcl.office at googlemail.com (mcl) Date: Sun, 26 Aug 2007 12:43:13 -0700 Subject: Joining Big Files In-Reply-To: <1188139515.349468.315290@q5g2000prf.googlegroups.com> References: <1188035844.616831.205350@i38g2000prf.googlegroups.com> <1188090939.364787.296630@r34g2000hsd.googlegroups.com> <1188092913.645157.15370@o80g2000hse.googlegroups.com> <1188139515.349468.315290@q5g2000prf.googlegroups.com> Message-ID: <1188157393.234494.62500@w3g2000hsg.googlegroups.com> On 26 Aug, 15:45, vasudevram wrote: > On Aug 26, 6:48 am, Paul McGuire wrote: > > > > > On Aug 25, 8:15 pm, Paul McGuire wrote: > > > > On Aug 25, 4:57 am,mosscliffe wrote: > > > > > I have 4 text files each approx 50mb. > > > > 50mb? Really? Did you actually try this and find out it was a > > > problem? > > > > Try this: > > > import time > > > > start = time.clock() > > > outname = "temp.dat" > > > outfile = file(outname,"w") > > > for inname in ['file1.dat', 'file2.dat', 'file3.dat', 'file4.dat']: > > > infile = file(inname) > > > outfile.write( infile.read() ) > > > infile.close() > > > outfile.close() > > > end = time.clock() > > > > print end-start,"seconds" > > > > For 4 30Mb files, this takes just over 1.3 seconds on my system. (You > > > may need to open files in binary mode, depending on the contents, but > > > I was in a hurry.) > > > > -- Paul > > > My bad, my test file was not a text file, but a binary file. > > Retesting with a 50Mb text file took 24.6 seconds on my machine. > > > Still in your working range? If not, then you will need to pursue > > more exotic approaches. But 25 seconds on an infrequent basis does > > not sound too bad, especially since I don't think you will really get > > any substantial boost from them (to benchmark this, I timed a raw > > "copy" command at the OS level of the resulting 200Mb file, and this > > took about 20 seconds). > > > Keep it simple. > > > -- Paul > > There are (at least) another couple of approaches possible, each with > some possible tradeoffs or requirements: > > Approach 1. (Least amount of code to write - not that the others are > large :) > > Just use os.system() and the UNIX cat command - the requirement here > is that: > a) your web site is hosted on *nix (ok, you can do it if on Windows > too - use copy instead of cat, you might have to add a "cmd /c " > prefix in front of the copy command, and you have to use the right > copy command syntax for concatenating multiple input files into one > output file). > > b) your hosting plan allows you to execute OS level commands like cat, > and cat is in your OS PATH (not PYTHONPATH). (Similar comments apply > for Windows hosts). > > import os > os.system("cat file1.txt file2.txt file3.txt file4.txt > > file_out.txt") > > cat will take care of buffering, etc. transparently to you. > > Approach 2: Read (in a loop, as you originally thought of doing) each > line of each of the 4 input files and write it to the output file: > > ("Reusing" Paul McGuire's code above:) > > outname = "temp.dat" > outfile = file(outname,"w") > for inname in ['file1.dat', 'file2.dat', 'file3.dat', 'file4.dat']: > infile = file(inname) > for lin in infile: > outfile.write(lin) > infile.close() > outfile.close() > end = time.clock() > > print end-start,"seconds" > > # You may need to check that newlines are not removed in the above > code, in the output file. Can't remember right now. If they are, just > add one back with: > > outfile.write(lin + "\n") instead of outfile.write(lin) . > > ( Code not tested, test it locally first, though looks ok to me. ) > > The reason why this _may_ not be much slower than manually coded > buffering approaches, is that: > > a) Python's standard library is written in C (which is fast), > including use of stdio (the C Standard IO library, which already does > intelligent buffering) > b) OS's do I/O buffering anyway, so do hard disk controllers > c) from some recent Python version, I think it was 2.2, that idiom > "for lin in infile" has been (based on somethng I read in the Python > Cookbook) stated to be pretty efficient anyway (and yet (slightly) > more readable that earlier followed approaches of reading a text > file). > > Given all the above facts, it probably isn't worth your while to try > and optimize the code unless and until you find (by measurements) that > it's too slow - which is a good practice anyway: > > http://en.wikipedia.org/wiki/Optimization_(computer_science) > > Excerpt from the above page (its long but worth reading, IMO): > > "Donald Knuth said, paraphrasing Hoare[1], > > "We should forget about small efficiencies, say about 97% of the time: > premature optimization is the root of all evil." (Knuth, Donald. > Structured Programming with go to Statements, ACM Journal Computing > Surveys, Vol 6, No. 4, Dec. 1974. p.268.) > > Charles Cook commented, > > "I agree with this. It's usually not worth spending a lot of time > micro-optimizing code before it's obvious where the performance > bottlenecks are. But, conversely, when designing software at a system > level, performance issues should always be considered from the > beginning. A good software developer will do this automatically, > having developed a feel for where performance issues will cause > problems. An inexperienced developer will not bother, misguidedly > believing that a bit of fine tuning at a later stage will fix any > problems." [2] > " > > HTH > Vasudev > ----------------------------------------- > Vasudev Ramhttp://www.dancingbison.comhttp://jugad.livejournal.comhttp://sourceforge.net/projects/xtopdf > ----------------------------------------- All, Thank you very much. As my background is much smaller memory machines than today's giants - 64k being a big machine and 640k being gigantic. I get very worried about crashing machines when copying or editing big files, especially in a multi-user environment. Mr Knuth - that brings back memories. I rememeber implementing some of his sort routines on a mainframe with 24 tape units and an 8k drum and almost eliminating one shift per day of computer operator time. Thanks again Richard From ptmcg at austin.rr.com Wed Aug 1 09:18:53 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 01 Aug 2007 06:18:53 -0700 Subject: access the name of my method inside it In-Reply-To: <1185973639.234450.305690@g12g2000prg.googlegroups.com> References: <1185959202.302467.276080@x35g2000prf.googlegroups.com> <5hb1ebF3inuf2U6@mid.uni-berlin.de> <1185973639.234450.305690@g12g2000prg.googlegroups.com> Message-ID: <1185974333.891840.279460@l70g2000hse.googlegroups.com> On Aug 1, 8:07 am, james_027 wrote: > Hi, > > On Aug 1, 5:18 pm, Marc 'BlackJack' Rintsch wrote: > > > On Wed, 01 Aug 2007 09:06:42 +0000, james_027 wrote: > > > for example I have this method > > > > def my_method(): > > > # do something > > > > # how do I get the name of this method which is my_method here? > > > Why do you need this? There are ways but those are not really good for > > production code. > > I am going to use this in Django. I am trying to implement a > permission here, where in the database store the methods that the user > are allowed to execute. for example if the method is def > create_event(): the method will look for create_event in the database > to see if it allow to be execute. > > Thanks. > james How about using a decorator? Here is a rough version: def checkPrivs(fn): fnName = fn.func_name def restricted(*args): print "about to call function", fnName if fnName in listOfAllowedFunctions: return fn(*args) else: raise KeyError("you don't have sufficient privileges to do THAT") return restricted listOfAllowedFunctions = ['add','subtract'] @checkPrivs def add(a,b): return a+b @checkPrivs def subtract(a,b): return a-b @checkPrivs def multiply(a,b): return a*b add(1,2) subtract(4,1) multiply(3,2) -- Paul From greg at cosc.canterbury.ac.nz Wed Aug 8 21:02:00 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 09 Aug 2007 13:02:00 +1200 Subject: Misleading wikipedia article on Python 3? In-Reply-To: <1186583168.447608.114040@d55g2000hsg.googlegroups.com> References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <7xzm15q8fy.fsf@ruckus.brouhaha.com> <1186583168.447608.114040@d55g2000hsg.googlegroups.com> Message-ID: <5hv7jeF3m75aqU1@mid.individual.net> Istvan Albert wrote: > A solution would be writing the code with a logging function to begin > with, alas many times that is out of one's hand. If the code has been written with calls to a builtin print function, the situation isn't much better. You could monkeypatch the print function, but that's probably worse than swapping sys.stdout. (I agree that print should be a function, simply because there's no strong reason for it *not* to be. But I don't think it makes a difference to this particular problem.) -- Greg From martin at v.loewis.de Wed Aug 22 15:30:57 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 22 Aug 2007 21:30:57 +0200 Subject: MsiLib In-Reply-To: References: Message-ID: <46cc8ef1$0$5970$9b622d9e@news.freenet.de> > I am trying to figure out how to use msilib to extract the registry > information from an MSI file and I really could use a good example of > how that is accomplished or even just an example using msilib in > general. Does anybody happen to know of an example for this as I wasn't > able to find one? If there isn't one, would anybody be willing to throw > one together? You need to look at the Registry table, whose structure is described here: http://msdn2.microsoft.com/en-us/library/Aa371168.aspx In particular, the fields you need to look at are Key, Name, and Value. Notice that Value is Formatted, so you may have to expand the formatting first (looking at further tables possibly). The rough sequence of actions would be db = msilib.OpenDatabase(path, MSIDBOPEN_READONLY) view = db.OpenView("SELECT Key, Name, Value FROM Registry") while True: record = view.Fetch() if not record: break print record.GetString(1), record.GetString(2), record.GetString(3) Unfortunately, GetString is not implemented yet, so it might be that what you want to do is not possible yet. HTH, Martin From deets at nospam.web.de Wed Aug 1 11:16:16 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 01 Aug 2007 17:16:16 +0200 Subject: Python end of file marker similar to perl's __END__ References: <1185940391.135261.130950@i38g2000prf.googlegroups.com> <1185976656.753817.27980@x40g2000prg.googlegroups.com> Message-ID: <5hbme0F3jck3bU1@mid.uni-berlin.de> beginner wrote: > On Jul 31, 10:53 pm, beginner wrote: >> Hi All, >> >> This is just a very simple question about a python trick. >> >> In perl, I can write __END__ in a file and the perl interpreter will >> ignore everything below that line. This is very handy when testing my >> program. Does python have something similar? >> >> Thanks, >> Geoffrey > > Thanks everyone for responding. It doesn't look like python has it. I > would definitely miss it. As Steve said, the nice thing about __END__ > is that things below __END__ do not have to have legit syntax. That > let me focus on the lines of code I am debugging and do not have to > worry about some bad syntax down the line. This feature is especially > handy if I am, saying, replacing modoules or changing data structures. In emacs, I simply mark that portion of code and do M-x comment-region That's it. And I don't think a language should support things __END__ - commenting is enough. It's unfortunate that Python doesn't support multi-line-comments though. But as I said, that my Editor can handle for me. Diez From coyote_x at artcom.pl Thu Aug 2 02:17:13 2007 From: coyote_x at artcom.pl (Adam Kubica) Date: Thu, 02 Aug 2007 08:17:13 +0200 Subject: Equivalent to gzinflate() function in PHP. References: <1185976461.491418.20230@i38g2000prf.googlegroups.com> Message-ID: On Wed, 01 Aug 2007 13:54:21 +0000, kyosohma wrote: > On Aug 1, 8:44 am, Adam Kubica wrote: >> Hellou. >> >> Anybody know about code that work equivalent to gzinflate() >> function used in PHP? >> >> I search via google but I don't found anything sensible :-( > > I'm not sure what gzinflate does, but it looks like it's some kind of > compression/decompression method. Python can do that. Check out the > following links: > > http://www.python.org/doc/lib/module-gzip.html > http://www.python.org/doc/lib/module-zlib.html > http://python.active-venture.com/lib/module-bz2.html > > Hopefully this is the type of thing you were looking for. > OK, but it isn't that I looking for :-( gzinflate() is reversed function of gzdeflate(), zlib module allows to use compress methon only, it's equivalent to gzcompress() in PHP. From nospam.themindstorm at gmail.com Thu Aug 2 04:18:30 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Thu, 2 Aug 2007 08:18:30 +0000 (UTC) Subject: Pythonic way for missing dict keys References: <1185041243.323915.161230@x40g2000prg.googlegroups.com> <87lkd0eprj.fsf@pobox.com> <46b0ed0b$0$2257$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote in news:46b0ed0b$0$2257$426a74cc at news.free.fr: > Steven D'Aprano a ?crit : > (snip) > >> Instead of doing: > >> if callable(function): function() >> >> you should do: >> >> try: >> function() >> except TypeError: >> pass > > There are time where you may want to know if you have a callable > without calling it... > >> That should work for most uses of callable(), but isn't quite the >> same. (What if function() has side-effects, or is expensive, and you >> want to determine if it is callable, but not actually call it _now_?) > > Indeed. > > The 'correct' replacement would be: > > if hasattr(obj, '__call__'): > # it's a callable > > but I don't find it so Pythonic to have to check for a __magic__ > method. > > It looks like Python devs have decided it is Pythonic, because it is already in the PEP. Same for execfile and the others. And I am not arguing pro or con. I was just wondering about the reasons, as I haven't been able to find anything (neither here nor on the dev group). bests, ./alex -- .w( the_mindstorm )p. From fernandofariajunior at gmail.com Fri Aug 31 15:33:04 2007 From: fernandofariajunior at gmail.com (fernando) Date: Fri, 31 Aug 2007 19:33:04 -0000 Subject: Registering a python function in C In-Reply-To: <1188516423.744038.309700@z24g2000prh.googlegroups.com> References: <1188508874.879215.319400@i13g2000prf.googlegroups.com> <1188516423.744038.309700@z24g2000prh.googlegroups.com> Message-ID: <1188588784.764658.317570@r34g2000hsd.googlegroups.com> Thanks for the responses. To be more specific, this code is part of a Maya plugin. The funcion MFnPlugin::registerUI takes a pointer to a PyObject which is the function that will set up the UI for that plugin. The code Matimus posted seems to me exactly like what I need to do, except that maya gives me an error when I call PyImport_ImportModule... I don't even have a chance to check the return value, Maya simply gives up. I have checked that python is initialized by the time I call this function, and the python path is correct, I can load the module from the maya python interpreter. What bugs me is that PyImport_ImportModule doesn't even return, it should return 0 if something bad happened, right? Here's my code: if(Py_IsInitialized()) cout << "python is already initialized" << endl; if(!Py_IsInitialized()){ cout << "had do initialize python" << endl; Py_Initialize(); } PyObject* mod= PyImport_ImportModule("vzPyTest"); if(mod == 0){ cout << "didn't load" << endl; } PyObject* func1 = PyObject_GetAttrString(mod, "vzPyTest.test1"); PyObject* func2 = PyObject_GetAttrString(mod, "vzPyTest.test2"); plugin.registerUI(func1, func2); Thanks for the help!!! From unlikeablePorpoise at gmail.com Tue Aug 14 08:52:49 2007 From: unlikeablePorpoise at gmail.com (unlikeablePorpoise at gmail.com) Date: Tue, 14 Aug 2007 12:52:49 -0000 Subject: JPype - passing to Java main In-Reply-To: References: <1187040070.806416.75090@r34g2000hsd.googlegroups.com> Message-ID: <1187095969.789811.63960@j4g2000prf.googlegroups.com> > > Try this: > com.JPypeTest.main("arg") > > Ian Thanks for your suggestion, but it doesn't work (produces an error). Does anybody else have any ideas? Thanks, Sarah From wildemar at freakmail.de Wed Aug 22 18:11:24 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Thu, 23 Aug 2007 00:11:24 +0200 Subject: Import question In-Reply-To: <46CCAE52.3000800@freakmail.de> References: <46CCAE52.3000800@freakmail.de> Message-ID: <46CCB48C.2000707@freakmail.de> Lamonte Harris wrote: > On 8/22/07, *Wildemar Wildenburger* > wrote: > > So your'e basically saying that you haven't tried it? > > No I haven't. Thats why I asked? Common sense? Sorry. Excuse my sarcasm. The common way for answering easy questions like this one is firing up the interpreter and trying it for yourself. You don't go up to a shoestore clerk to ask whether your shoes might fall off if you tie them sloppily, do you? Thats just wasting everyones time. And regarding your question: Python 2.5 (r25:51908, Apr 10 2007, 10:29:13) [GCC 4.1.2 20070403 (Red Hat 4.1.2-8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys, datetime >>> sys.platform, datetime.datetime.now() ('linux2', datetime.datetime(2007, 8, 23, 0, 1, 41, 727155)) Hint for the future: Please try these things before asking. If *then* you have a problem, ask. /W From kyosohma at gmail.com Mon Aug 27 09:14:02 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 27 Aug 2007 06:14:02 -0700 Subject: wx.grid and different Value Choice each line ? In-Reply-To: <46d2a1f9$0$27412$ba4acef3@news.orange.fr> References: <46d2a1f9$0$27412$ba4acef3@news.orange.fr> Message-ID: <1188220442.944332.102910@57g2000hsv.googlegroups.com> On Aug 27, 5:08 am, BH wrote: > Hi, > > Hox can I have different value choice for each line in a grid with > wxPython ? > I want to develop a small software for satisfaction surveys. Each line > of the grid is a different question. Sometimes answers are the sames > between two lines, but sometimes not. > > Thx, > > Bertrand I don't know if you can insert a combobox into a grid object or not. It's probably possible. You should post your question to the wxPython group though since this is a very specific issue. See here: http://www.wxpython.org/maillist.php If it was me though, I would probably use a wizard and put my questions and choices on it. Or maybe use a notebook control. Mike From chris.hamons at gmail.com Sat Aug 25 13:04:44 2007 From: chris.hamons at gmail.com (chris.hamons at gmail.com) Date: Sat, 25 Aug 2007 17:04:44 -0000 Subject: Debugging a curses application in python Message-ID: <1188061484.516090.231200@q5g2000prf.googlegroups.com> Hello all, I'm trying to debug a python application which uses the curses module under Linux. I'm having trouble, since I can't get any debugger to work. Is there a way to separate the output of an application from the debugger. In gdb, the tty command would allow me to specify a separate tty to write the curses output to. Any suggestions? Thanks, --Chris Hamons From steve at holdenweb.com Thu Aug 23 23:12:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 23 Aug 2007 23:12:30 -0400 Subject: creating a tar file with python In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE2EC@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> <93066C069973ED448DC2BCEA9C44A7383BE2EC@efmailx> Message-ID: <46CE4C9E.2020301@holdenweb.com> Brian McCann wrote: > > Hi, > > I tried Steve's solution but get this error > using the tar script below > --Brian > > tar = tarfile.open(".","test.tar.gz",w:gz) > [viz at vizbld02 tmp]$ ./tarup.py > File "./tarup.py", line 24 > tar = tarfile.open(".","test.tar.gz",w:gz) > ^ > SyntaxError: invalid syntax > ###################################################### > > #!/usr/bin/python > import string > import os > import sys > import time > import errno > import shutil > import tarfile > > tar = tarfile.open(".","test.tar.gz",w:gz) > > > > > *From:* python-list-bounces+brian.mccann=viziant.net at python.org on > behalf of Steve Holden > *Sent:* Thu 8/23/2007 5:24 PM > *To:* python-list at python.org > *Subject:* Re: creating a tar file with python > > Brian McCann wrote: > > Hi, > > > > I'm trying to create a tar file of the contents of the current directory > > > > right now there is only one file "text.xml" in the current dir, I'm > > using"." current dir as source > > but that gives syntax error > > > > any help would be greatly appreciated > > --Brian > > > > > > #!/usr/bin/python > > import string > > import os > > import sys > > import time > > import errno > > import shutil > > import tarfile > > > > > > tar = tarfile.open(.,"test.tar.gz", "w:gz) > > > > > > > well, /probably/ (meaning I haven't done any testing) you need quotes > around the name of the current directory just like you do around the > name of the file. Try > > tar = tarfile(".", "test.tar.gz", "w:gz") > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- > > -- > http://mail.python.org/mailman/listinfo/python-list > [Jeez, doesn't anybody use standard-conformant mailers any more: why is my signature quoted above, and what it it supposed to add? Couldn't you have taken a second to delete it: that would probably have taken about 35 MB off the Internet backbone. Or perhaps you think that all resources are unlimited? Sorry, I'm a bit cranky this week, being short of sleep.] I admitted my code was untested, but I believe if you had copied-and-pasted you would not have received the error you did (which is not to say you wouldn't have received some other error). Don't run what you /think/ I wrote, run /what I wrote/, as pasted by your operating system, dammit. Or are you running on some platform that doesn't allow you to select what I wrote and paste it into an editor window? sholden at bigboy /tmp $ cat > Brian\'s\ Original tar = tarfile.open(.,"test.tar.gz", w:gz) sholden at bigboy /tmp $ cat > what\ I\ wrote tar = tarfile(".", "test.tar.gz", w:gz") sholden at bigboy /tmp $ diff Brian\'s\ Original what\ I\ wrote 1c1 < tar = tarfile.open(.,"test.tar.gz", w:gz) --- > tar = tarfile(".", "test.tar.gz", "w:gz") sholden at bigboy /tmp Hmm, you probably don't understand the gobbledygook above, but what it means is that you didn't pay sufficient attention to detail. This isn't a serious problem: Google will probably show you several thousand occurrences of me exhibiting similar symptoms. But remember, computers are TOMCATs: Thoroughly Obedient Moron, Cannot Actually Think. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From vasudevram at gmail.com Wed Aug 15 12:37:06 2007 From: vasudevram at gmail.com (vasudevram) Date: Wed, 15 Aug 2007 16:37:06 -0000 Subject: Python Book Recommendations In-Reply-To: <1187192077.005818.174440@i13g2000prf.googlegroups.com> References: <1b31ae500708141638w77614014o6f382d0389bc69df@mail.gmail.com> <1187191803.845011.30400@x35g2000prf.googlegroups.com> <1187192077.005818.174440@i13g2000prf.googlegroups.com> Message-ID: <1187195826.232055.217260@x40g2000prg.googlegroups.com> On Aug 15, 8:34 pm, kyoso... at gmail.com wrote: > On Aug 15, 10:30 am, Azazello wrote: > > > > > On Aug 15, 7:47 am, "Shawn Milochik" wrote: > > > > If I could have only one book, I would buy "Core Python, Second > > > Edition," by Wesley Chun. > > > > For the record, I own: > > > Core Python, Second Edition (great) > > > wxPython in Action (haven't used yet) > > > Beginning Python (barely used) > > > Python in a Nutshell (use as a reference, although interactive python > > > dir() is more useful) > > > Dive into Python (great book) > > > Python Cookbook (great book) > > > Python Pocket Reference (not very useful) > > > Python Phrasebook (I love the Phrasebook series, but this isn't a > > > necessary book) > > > I would like to add: > > > Foundations of Python Network Programming > > > I also use the Python Essential Reference. (although all of the > > information is probably online it's nice to have a solid paper > > reference) > > Depending on what you're doing, a book can actually be faster than > Google! Of course, a lot of these books don't cover any 3rd party > modules, so Google is still very handy. > > Mike I second some of those recommendations - for the books I own / have read: Python Cookbook - excellent Python in a Nutshell - excellent Though interactive dir() is good, it doesn't give you a lot of things that Python in a Nutshell and the official Python docs do - rules of the language, info on new-style classes, etc. Also, Google for "Guide to Python Introspection" - a good online article that shows a lot more about that topic, over and above use of dir(). Also: Programming Python - excellent. Didn't know about the Python Network programming book - thanks, will check it out. Vasudev Ram http://www.dancingbison.com http://jugad.livejournal.com http://sourceforge.net/projects/xtopdf From jjl at pobox.com Mon Aug 20 15:53:54 2007 From: jjl at pobox.com (John J. Lee) Date: Mon, 20 Aug 2007 19:53:54 GMT Subject: desperately in need of a tool References: <1187560418.339131.283470@i38g2000prf.googlegroups.com> Message-ID: <87d4xix9rh.fsf@pobox.com> yagyala writes: > I recently started working for a company that has just implemented its > first set of software standards. So far, so good. Here's the problem: > one of those standards is that the comments for each routine must > indicate every other routine that it calls. As I try to keep my > routines small, and factor out methods alot, this can lead to an > enormous ammount of extra typing. I really, really, really don't want > to do this by hand. Does anyone know of a tool that could do this for > me, or at least a tool that can tell what other routines a given > routine calls that I could program against? (Preferably something that > works under pydev, but I'm not going to be choosy.) import tokenize for token in tokenize.generate_tokens(open("foo.py")): print token Note module token, also. Module inspect may also be of use: http://docs.python.org/lib/inspect-source.html Also, Python 2.5 introduced a new AST, which I haven't had occasion to use yet (not even certain whether it ended up getting exposed it to Python, or just staying on the C level...) Possibly you could even persuade some existing source code analysis tool to do exactly the job you want for you -- but it's probably much easier just to write what you need yourself. John From byte8bits at gmail.com Thu Aug 9 10:04:50 2007 From: byte8bits at gmail.com (brad) Date: Thu, 09 Aug 2007 10:04:50 -0400 Subject: tests In-Reply-To: <1186666919.456036.120270@d30g2000prg.googlegroups.com> References: <1186666919.456036.120270@d30g2000prg.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > You should be able to read chunks of each file in binary mode and do a > compare to check for equality. Some kind of loop should do the trick. Why not a simple md5 or sha with the hash library? From steve at holdenweb.com Thu Aug 16 20:34:42 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 16 Aug 2007 20:34:42 -0400 Subject: Pass by reference or by value? In-Reply-To: <496954360708161526o5b6a0fffof2fbd5227244e709@mail.gmail.com> References: <496954360708161402x58faba47x7a6eae6e68f81d4@mail.gmail.com> <496954360708161501s541bddb7vfe168e4863f7f1e@mail.gmail.com> <46C4CCAD.3080104@holdenweb.com> <496954360708161526o5b6a0fffof2fbd5227244e709@mail.gmail.com> Message-ID: Robert Dailey wrote: [but he top-posted, so he should consider himself smacked on the wrist] > On 8/16/07, *Steve Holden* > wrote: > > Robert Dailey wrote: > > So immutable objects cannot be modified directly? I guess this means > > integers are immutable and the act of assigning to one is a > completely > > new definition? > > Correct. A new value is bound to the name or item on the left-hand side > - remember, all variables are pointers to values, there's no way to > replace the value of a variable because of the automatic dereferencing. > And yes, immutable objects can't be modified. At all, period. Hence the > name. > > > So if I were to create a class called Integer and > give > > it a .set() method, this would allow me to create mutable > integers, and > > thus passing in an object of type class Integer would allow me to > modify > > the value from inside the function? > > > Well, the .set() method wouldn't be called automatically on an > assignment statement but yes, if you passed an Integer object into your > function and called its .set() method from inside then it should work. > > As long as you get your mutable integer implementation correct, of > course ;-). I'd suggest delegating everything except the .set() method > to the underlying integer value. > Thanks Steve for your explanation. It was very helpful. I think I > understand it now. By the way, by the .set method I meant: > > class Integer: > def __init__( self, number=0 ): > self._int = number > > def set( self, number ): > self._int = number > > > # later on.... > > mutableInt = Integer( 5 ) > def change_me( var ): > var.set( 6 ) > > > Of course, I'd probably use overloaded operators in a more realized > example. > > Fair enough, but I was trying to point out that assignment isn't an operator so you won't be able to achieve what you want by assignment to a name local to the function. You could, of course, assign to a name local to the instance you passed in, but then there wouldn't be much point in using anything but a simple subclass of object (normally referred to as Bunch). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From as at hut.at Wed Aug 29 10:55:49 2007 From: as at hut.at (hyena) Date: Wed, 29 Aug 2007 16:55:49 +0200 Subject: handling tabular data in python--newbie question References: <6cf42$46d56771$839b8704$5034@news1.tudelft.nl> Message-ID: Thanks Bruno and Steve for the quick answer! >What make you think such a thing ? I am also using R and java from time to time, and think it is very covinient that in R tables are handled as matrixs or data frames. Thus I expect python has something similiar. :) And I went for Steve's first suggestion, which is just what I want at this moment. Thanks again. From wolf_tracks at invalid.com Sun Aug 19 18:47:38 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sun, 19 Aug 2007 22:47:38 GMT Subject: Python on Computation, Math and Statistics In-Reply-To: <5irldoF3qonnbU1@mid.uni-berlin.de> References: <5irgvaF3oi5dpU2@mid.uni-berlin.de> <5irldoF3qonnbU1@mid.uni-berlin.de> Message-ID: Thanks. I appreciate the info. Diez B. Roggisch wrote: > W. Watson schrieb: >> Google? What's that? Thanks. I like to get a insider's view when I >> know experts are out there. So now I ask a deeper question. Are there >> matrix computation libraries or even statistical (regression, factor >> analysis) libraries? > > That's your idea of an "in depth question"? > > Did you even consider googling the projects I told you about? Reading up > on them just the tiniest? > > http://www.scipy.org/ > > """ > SciPy (pronounced "Sigh Pie") is open-source software for mathematics, > science, and engineering. It is also the name of a very popular > conference on scientific programming with Python. The SciPy library > depends on NumPy, which provides convenient and fast N-dimensional array > manipulation. The SciPy library is built to work with NumPy arrays, and > provides many user-friendly and efficient numerical routines such as > routines for numerical integration and optimization. Together, they run > on all popular operating systems, are quick to install, and are free of > charge. NumPy and SciPy are easy to use, but powerful enough to be > depended upon by some of the world's leading scientists and engineers. > If you need to manipulate numbers on a computer and display or publish > the results, give SciPy a try! > """ > > Or do you wish a comprehensive overview as Powerpoint presentation in > your favorite colors? > > > > Diez -- Wayne Watson (Nevada City, CA) Web Page: From tundra at tundraware.com Fri Aug 31 22:13:53 2007 From: tundra at tundraware.com (Tim Daneliuk) Date: Fri, 31 Aug 2007 21:13:53 -0500 Subject: So what exactly is a complex number? In-Reply-To: <46d89ba9$0$30380$9b4e6d93@newsspool4.arcor-online.net> References: <451mq4-les.ln1@ozzie.tundraware.com> <46d89ba9$0$30380$9b4e6d93@newsspool4.arcor-online.net> Message-ID: Wildemar Wildenburger wrote: > Tim Daneliuk wrote: >> A number by itself is called a "scalar". For example, when I say, >> "I have 23 apples", the "23" is a scalar that just represents an >> amount in this case. >> >> One of the most common uses for Complex Numbers is in what are >> called "vectors". In a vector, you have both an amount and >> a *direction*. For example, I can say, "I threw 23 apples in the air >> at a 45 degree angle". Complex Numbers let us encode both >> the magnitude (23) and the direction (45 degrees) as a "number". >> > 1. Thats the most creative use for complex numbers I've ever seen. Or > put differently: That's not what you would normally use complex numbers > for. > 2. Just to confuse the issue: While complex numbers can be represented > as 2-dimensional vectors, they are usually considered scalars as well > (since they form a field just as real numbers do). > > >> There are actually two ways to represent Complex Numbers. >> One is called the "rectangular" form, the other the "polar" >> form, but both do the same thing - they encode a vector. >> > Again, that is just one way to interpret them. Complex numbers are not > vectors (at least no moe than real numbers are). > > > /W Yeah, I know it's a simplification - perhaps even a vast simplification - but one eats the elephant a bite at a time. FWIW, the aforementioned was my first entre' into complex arithmetic, long before I waded through complex analysis and all the more esoteric stuff later in school. I wonder why you think it is "creative", though. Most every engineer I've ever know (myself included) was first exposed to complex numbers in much this way. Then again, I was never smart enough to be a pure mathematician ;) -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From steveo at syslang.net Fri Aug 24 12:26:13 2007 From: steveo at syslang.net (Steven W. Orr) Date: Fri, 24 Aug 2007 12:26:13 -0400 (EDT) Subject: How to replace a method in an instance. In-Reply-To: <1187971953.261328.219000@q3g2000prf.googlegroups.com> References: <1187971953.261328.219000@q3g2000prf.googlegroups.com> Message-ID: On Friday, Aug 24th 2007 at 09:12 -0700, quoth kyosohma at gmail.com: =>On Aug 24, 11:02 am, "Steven W. Orr" wrote: =>> In the program below, I want this instance to end up calling repmeth =>> whenever inst.m1 is called. As it is now, I get this error: =>> =>> Hello from init =>> inst = <__main__.CC instance at 0x402105ec> =>> Traceback (most recent call last): =>> File "./foo9.py", line 17, in ? =>> inst.m1() =>> TypeError: repmeth() takes exactly 1 argument (0 given) =>> =>> #! /usr/bin/python =>> def repmeth( self ): =>> print "repmeth" =>> =>> class CC: =>> def __init__( self ): =>> self.m1 = repmeth =>> print 'Hello from init' =>> =>> def m1 ( self ): =>> print "m1" =>> =>> inst = CC() =>> inst.m1() =>Remove "self" from repmeth as it's not required in a function, only in =>functions that are defined within a class. Of course, a function in a =>class is also know as a method. Sorry. I need repmeth to have self passed to it automatically if it's called. I didn't mean to obfuscate the problem by not making a reference to self in repmeth. Am I being clear? -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From pavlovevidence at gmail.com Thu Aug 2 21:54:13 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 03 Aug 2007 01:54:13 -0000 Subject: __call__ considered harmful or indispensable? In-Reply-To: <7xfy31smuq.fsf@ruckus.brouhaha.com> References: <7xfy31smuq.fsf@ruckus.brouhaha.com> Message-ID: <1186106053.823905.285880@j4g2000prf.googlegroups.com> On Aug 2, 4:27 pm, Paul Rubin wrote: > s... at pobox.com writes: > > In this particular case it was clearly unnecessary and just obfuscated the > > code. I'm wondering, are there some general cases where __call__ methods of > > a user-defined class are simply indispensable? > > I don't know about "indispensable" but __call__ is convenient sometimes > and I do use it. I've wished that modules supported call, so I could > say > > import foo > x = foo(3) > > instead of having to say x=foo.foo(3) or something like that. I used to think that. Or, rather, I often thought that it'd be nice if a function or class could be imported like a module. These days I think it'd be enough if modules don't have the same name as any (public) objects they define. No more glob.glob, select.select, or time.time. It's ugly and potentially confusing. And if I were Polynesian I would keep thinking I was seeing plurals. Carl Banks From mensanator at aol.com Mon Aug 13 19:38:55 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 13 Aug 2007 16:38:55 -0700 Subject: (sort of) deterministic timing in Python In-Reply-To: <1i2si8h.1qc8f77i68gyeN%johnmfisher@comcast.net> References: <1i2si8h.1qc8f77i68gyeN%johnmfisher@comcast.net> Message-ID: <1187048335.358956.111340@z24g2000prh.googlegroups.com> On Aug 13, 5:16 pm, johnmfis... at comcast.net (John Fisher) wrote: > I am working on a framework for data acquisition in Python 2.5, am > trying to get a structure going more like this: > > mark start time > start event > event finishes > count time until next interval > start second event... > > rather than this: > > start event > event finishes > sleep for interval > start second event > > Do you see the difference? I get a true fixed interval from the first, > including the time to accomplish the event task(s). In the second case, > the sleep just gets tacked on at the end of the events, not very > deterministic (timing-wise). > > So how do I accomplish this in Python with a minimum of labour? > > Thanks for any light you can shed on my darkness... > > wave_man In the first example, you know when to start the second interval, right? In the second case, you are assuming the second task is ready to run after the sleep interval. Here's an example that times how long an external program takes, the os.popen() returns to the Python script when the external C program completes, so no need for any sleep interval. Because of the poorly written factor program, some composites are falsely reported as unfactorable. This example keeps re-calling the factor!.exe program until all composites are factored or marked intractable, and the time to execute each iteration of factor!.exe is printed after each call. import os import time factor_program = 'factor! -d200 ' the_composites = [['COMPOSITE_FACTOR','50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749']] the_primes = [] the_intractables = [] phase = 1 the_times = [] while the_composites: print "="*40 print 'Phase',phase the_comp = the_composites.pop(0) print the_comp print the_times.append(time.time()) # time how long it takes to run factor!.exe the_output = os.popen(factor_program+the_comp[1]).readlines() the_times.append(time.time()) new_factors = [i.split() for i in the_output] for i in new_factors: print i print if len(new_factors) == 1: # it's prime or intractable if new_factors[0][0] == 'PRIME_FACTOR': the_primes.append([new_factors[0][0],long(new_factors[0][1])]) else: the_intractables.append([new_factors[0][0],long(new_factors[0] [1])]) new_factors.pop() while new_factors: j = new_factors.pop(0) if j[0] == 'PRIME_FACTOR': the_primes.append([j[0],long(j[1])]) else: the_composites.append(j) print the_times[phase] - the_times[phase-1],'seconds' phase += 1 print "="*40 print print 'Factoring complete' print the_primes.sort() the_intractables.sort() the_primes.extend(the_intractables) for i in the_primes: print i[0],i[1] print print "="*40 ## ======================================== ## Phase 1 ## ['COMPOSITE_FACTOR', '50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749'] ## ## ['PRIME_FACTOR', '37'] ## ['PRIME_FACTOR', '43'] ## ['PRIME_FACTOR', '167'] ## ['COMPOSITE_FACTOR', '507787751'] ## ['PRIME_FACTOR', '69847'] ## ['PRIME_FACTOR', '30697'] ## ['PRIME_FACTOR', '89017'] ## ['PRIME_FACTOR', '3478697'] ## ['PRIME_FACTOR', '434593'] ## ['PRIME_FACTOR', '49998841'] ## ['PRIME_FACTOR', '161610704597143'] ## ['PRIME_FACTOR', '14064370273'] ## ['COMPOSITE_FACTOR', '963039394703598565337297'] ## ['PRIME_FACTOR', '11927295803'] ## ## 0.860000133514 seconds ## ======================================== ## Phase 2 ## ['COMPOSITE_FACTOR', '507787751'] ## ## ['PRIME_FACTOR', '29819'] ## ['PRIME_FACTOR', '17029'] ## ## 0.0780000686646 seconds ## ======================================== ## Phase 3 ## ['COMPOSITE_FACTOR', '963039394703598565337297'] ## ## ['PRIME_FACTOR', '518069464441'] ## ['PRIME_FACTOR', '1858900129817'] ## ## 0.0469999313354 seconds ## ======================================== ## ## Factoring complete ## ## PRIME_FACTOR 37 ## PRIME_FACTOR 43 ## PRIME_FACTOR 167 ## PRIME_FACTOR 17029 ## PRIME_FACTOR 29819 ## PRIME_FACTOR 30697 ## PRIME_FACTOR 69847 ## PRIME_FACTOR 89017 ## PRIME_FACTOR 434593 ## PRIME_FACTOR 3478697 ## PRIME_FACTOR 49998841 ## PRIME_FACTOR 11927295803 ## PRIME_FACTOR 14064370273 ## PRIME_FACTOR 518069464441 ## PRIME_FACTOR 1858900129817 ## PRIME_FACTOR 161610704597143 ## ## ======================================== From aleax at mac.com Thu Aug 2 01:29:30 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 1 Aug 2007 22:29:30 -0700 Subject: Where do they tech Python officialy ? References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> <1185265091.276958.239910@r34g2000hsd.googlegroups.com> <1i23wyk.avc945i4dwsiN%aleax@mac.com> <1i25pjo.1mo5uqc1yxqsjkN%aleax@mac.com> Message-ID: <1i26u6o.pthuan2j7nufN%aleax@mac.com> Alex Popescu wrote: ... > Have you seen/heard of Jim lately? Cause I haven't. By the time he was > the lead of the AspectJ team his charismatic presence was everywhere (at > least around that project). He wasn't at OSCON this year, but I hope to see him at Pycon next year. I don't see this as a deep dark M$ plot to kidnap and hide the best and brightest Open Sourcers, because I know what it means to get a wonderful challenging new job and pour all you have into it (I've had to skip a couple Pycons, myself, though I hope to be back next year). > However I do agree with you. The only remark is that US trends are not > hitting my part of Eu so quickly ;-) (things are indeed changing). About 3 years ago I was also getting sick and tired about my own part of the EU, which is part of why I emigrated:-). I do see things getting better in Southern Europe, albeit from a distance. > > These are the ones you don't wan't to work for anyway !-) > > Well... this is sometimes debatable :-). A totally clueless employer may still be a way to make some quick and dirty money right now, but it will barely be enough to pay for the extra Maalox and Zantac you'll need. Looking back on your life when you're closer to retirement than to when you started working, you'll see what a mistake it was to accept clueless-employers' offers, and how much happier your life would have been if you'd known that up front:-). Alex From python-url at phaseit.net Mon Aug 13 07:19:11 2007 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 13 Aug 2007 11:19:11 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Aug 13) Message-ID: QOTW: "The first time you see twenty tons of machinery move unexpectedly because you inadvertently changed one bit in memory, you become very conservative about your software platform." - Walt Leipold "Making use of the available wrappers for current Tk libraries such as BWidgets, Tile, Tablelist, TkTreeCtrl, and so on allows you to make UI's every bit as polished as what comes with wxPython ..." - Kevin Walzer Looking for the best programs written entirely in Python: http://groups.google.com/group/comp.lang.python/browse_thread/thread/9fea4deb4c70fef1/ `a==b` vs. `a is b` revisited, with some advice on when to use one test or another: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4a087153826f1f2b/ Pros and cons of "desktop web" applications vs. native GUIs: http://groups.google.com/group/comp.lang.python/browse_thread/thread/1f823a9c8a41c8bb/50c2f4bc10621f9a?rnum=1#50c2f4bc10621f9a started as http://groups.google.com/group/comp.lang.python/browse_thread/thread/1f823a9c8a41c8bb When is OK to use __del__? http://groups.google.com/group/comp.lang.python/browse_thread/thread/b09e02b7c67c8a3b/ Leipzig is the site of the second "Python im deutschsprachigen Raum 2007". Among the presentations likely to reward both novices and experienced Pythoneers are ones on Web applications, use of Python in science, developer tools in Python, and Python for simulations in aerospace. http://www.python-academy.de/workshop/index.html Somewhat related to previous topic: how to ensure a generator object is closed in Python 2.4? http://groups.google.com/group/comp.lang.python/browse_thread/thread/3f789096bded17e7/ Discussing Python threading model, the GIL, Stackless, and possible future alternatives: http://groups.google.com/group/comp.lang.python/browse_thread/thread/bbeb8b826af93ae/ "Use spaces for space and use tabs for tables": A Python song, by James Stroud http://groups.google.com/group/comp.lang.python/msg/9743131cf0c426eb ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From wolf_tracks at invalid.com Sun Aug 19 14:29:38 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sun, 19 Aug 2007 18:29:38 GMT Subject: Python on Computation, Math and Statistics Message-ID: I would hope Python is doing a lot of standard computations beyond arithmetic. Trig functions and more. Comments? -- Wayne Watson (Nevada City, CA) Web Page: From ramashish.lists at gmail.com Sun Aug 19 01:03:38 2007 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: Sun, 19 Aug 2007 05:03:38 -0000 Subject: Understanding closures Message-ID: <1187499818.125192.12930@m37g2000prh.googlegroups.com> Hi, I want to use variables passed to a function in an inner defined function. Something like- def fun1(method=None): def fun2(): if not method: method = 'GET' print '%s: this is fun2' % method return fun2() fun1() However I get this error- UnboundLocalError: local variable 'method' referenced before assignment This however works fine. def fun1(method=None): if not method: method = 'GET' def fun2(): print '%s: this is fun2' % method return fun2() fun1() Is there a simple way I can pass on the variables passed to the outer function to the inner one without having to use or refer them in the outer function? Thanks, Ramashish From rcdailey at gmail.com Mon Aug 13 10:35:28 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 13 Aug 2007 09:35:28 -0500 Subject: Binary, Hex, and Decimal string conversions In-Reply-To: <20070813034138.CA4C81E4012@bag.python.org> References: <496954360708111559s1cef4212pabd14e95b27435ea@mail.gmail.com> <496954360708121620r4dd68ac9o430326ae8c8ae04d@mail.gmail.com> <649D1D6C-A44C-4D03-920D-489BBD108789@jedimindworks.com> <20070813034138.CA4C81E4012@bag.python.org> Message-ID: <496954360708130735s73a0fb02mbba68dad14f59193@mail.gmail.com> Just curious Dick, why are you making your own to_base method? Doesn't the source I provided in my earlier email give you all that you need? I was hoping my source might be useful to a few people, even though it's pretty trivial code. On 8/12/07, Dick Moores wrote: > > At 07:04 PM 8/12/2007, Michael Bentley wrote: > > >On Aug 12, 2007, at 6:28 PM, Dick Moores wrote: > > > >>n = 12 > >>base = 36 > >>print to_base(n, base) > >>========================================== > >>This seems to work fine for n >= base, but not for n < base. For > >>example, the code shown returns "c". Is my indentation wrong, or > >>the code? It seems to me that the code should work for the general > >>case, not just for n >= base. > > > >Isn't 'c' the correct answer? > > Yes, of course. Stupid of me. > > Dick > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From aboudouvas at panafonet.gr Fri Aug 3 18:03:49 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Fri, 03 Aug 2007 15:03:49 -0700 Subject: Eclipse/PyDev question. In-Reply-To: References: <1186153119.391091.275860@r34g2000hsd.googlegroups.com> <1186153259.372809.230110@d30g2000prg.googlegroups.com> <1186153503.806195.225560@g4g2000hsf.googlegroups.com> Message-ID: <1186178629.918590.117540@19g2000hsx.googlegroups.com> On Aug 3, 5:46 pm, "Danyelle Gragsone" wrote: > I wonder how long before they come out with a python version of > eclipse. I know there is a C/C++ now. > > Danyelle The only problem i see in Eclipse/Pydev solution is that Eclipse is bulky...I was not designed for specific Python usage and because of that we have a lot of stuff that does not concern us. I started to look at Eric4 and i must way i like it a lot. I am not sure if i switch yet but it seems very nice. From pyth0nc0d3r at gmail.com Thu Aug 30 21:11:14 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Thu, 30 Aug 2007 20:11:14 -0500 Subject: So what exactly is a complex number? Message-ID: Like in math where you put letters that represent numbers for place holders to try to find the answer type complex numbers? -------------- next part -------------- An HTML attachment was scrubbed... URL: From gh at ghaering.de Thu Aug 30 18:29:21 2007 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 31 Aug 2007 00:29:21 +0200 Subject: python + gcov In-Reply-To: <1188472743.570376.120390@o80g2000hse.googlegroups.com> References: <1188404571.590476.265840@r34g2000hsd.googlegroups.com> <1188472743.570376.120390@o80g2000hse.googlegroups.com> Message-ID: labrach at gmail.com wrote: > [...] Do I need to make a static extension of my imported module to profile > it ? I always bit the bullet and finally just did that. -- Gerhard From tjreedy at udel.edu Thu Aug 9 11:57:57 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 9 Aug 2007 11:57:57 -0400 Subject: Stackless Integration References: <1186650027.043779.276520@i38g2000prf.googlegroups.com> Message-ID: "Justin T." wrote in message news:1186650027.043779.276520 at i38g2000prf.googlegroups.com... | I've been looking at stackless python a little bit, and it's awesome. | My question is, why hasn't it been integrated into the upstream python | tree? Does it cause problems with the current C-extensions? It seems | like if something is fully compatible and better, then it would be | adopted. However, it hasn't been in what appears to be 7 years of | existence, so I assume there's a reason. First, which 'stackless'? The original continuation-stackless (of about 7 years ago)? Or the more current tasklet-stackless (which I think is much younger than that)? The original added a feature Guido did not want (continuations) and required major changes to the core that would have make maintainance probably more difficult for most of the developers, including GvR. For more, see http://www.python.org/dev/peps/pep-0219/ Second, what do you mean by integration? The current tasklet version is, I am sure, as well integrated as Tismer can make it. Last I looked, there were warnings about possible incompatibilities, but perhaps these have been overcome. It is just not part of the stdlib. And as far as I know or could find in the PEP index, C. Tismer has never submitted a PEP asking that it be made so. Doing so would mean a loss of control, so there is a downside as well as the obvious upside of distribution. tjr From fartknuckle at fartknuckle.com Fri Aug 10 19:23:11 2007 From: fartknuckle at fartknuckle.com (fartknuckle) Date: Fri, 10 Aug 2007 18:23:11 -0500 Subject: Error calling module Message-ID: When I try to call gtk like so: import gtk I get the error: ImportError: No module named gtk I installed a new Python and a new pygtk. Is the gtk module not a part of pygtk??? I have PYTHONPATH=/usr/local/lib/python2.5/site-packages set. So what am I doing wrong? Thanks -- Take summa dis punk! From lesande at gmail.com Thu Aug 9 18:11:40 2007 From: lesande at gmail.com (Lee Sander) Date: Thu, 09 Aug 2007 15:11:40 -0700 Subject: programmatically define a new variable on the fly Message-ID: <1186697500.024593.303820@x35g2000prf.googlegroups.com> Hi, I would like to define a new variable which is not predefined by me. For example, I want to create an array called "X%s" where "%s" is to be determined based on the data I am processing. So, for example, if I the file I'm reading has g 99 on the first line, I want to create a new variable called "Xg" whose length is 99. I tried eval("Xg=[0]*99") but that did not work. any help would be greatly appreciated Lee From iansan at gmail.com Thu Aug 30 13:32:58 2007 From: iansan at gmail.com (IamIan) Date: Thu, 30 Aug 2007 17:32:58 -0000 Subject: Simple elementtree question Message-ID: <1188495178.701968.246690@50g2000hsm.googlegroups.com> This is in Python 2.3.5. I've had success with elementtree and other RSS feeds, but I can't get it to work with this format: Example feed http://www.sample.com Sample News Agency - News Feed Our News Feed http://www.sample.com/img/title.gif http://www.sample.com First story 30 August, 2007 : - - First description including unicode characters http://www.sample.com/news/20000/news.htm Second story 30 August, 2007 : - - Second description including unicode characters http://www.sample.com/news/20001/news.htm What I want to extract is the text in the title and link tags for each item (eg. First story and http://www.sample.com/ news/20000/news.htm). Starting with the title, my test script is: import sys from urllib import urlopen sys.path.append("/home/me/lib/python") import elementtree.ElementTree as ET news = urlopen("http://www.sample.com/rss/rss.xml") nTree = ET.parse(news) for item in nTree.getiterator("title"): print item.text Whether I try this for title or link, nothing is printed. There are also unicode characters in the tags, I'm not sure if that could affect the output like this. In case it did I passed an encoding argument to ET.parse (which I'd seen in other posts) but it said encoding was an unexpected argument... Printing all subelements does work: print nTree.getiterator() [<Element {http://www.w3.org/1999/02/22-rdf-syntax-ns#}RDF at 40436d2c>, <Element {http://purl.org/rss/1.0/}channel at 40436b2c>, <Element {http://purl.org/rss/ 1.0/}title at 40436dcc>, <Element {http://purl.org/rss/1.0/}link at 40436d6c>, < Element {http://purl.org/rss/1.0/}description at 40436e0c>, <Element {http://pur l.org/rss/1.0/}image at 40436e6c>, <Element {http://purl.org/rss/1.0/}items at 4 0436f2c>, <Element {http://www.w3.org/1999/02/22-rdf-syntax-ns#}Seq at 40436f6c> , <Element {http://www.w3.org/1999/02/22-rdf-syntax-ns#}li at 40436f0c>, <Element {http://www.w3.org/1999/02/22-rdf-syntax-ns#}li at 40436fec>, <Element {http://purl.org/rss /1.0/}item at 4044624c>, <Element {http://purl.org/rss/1.0/}title at 4044626c>, <Element {http://purl.org/rss/1.0/}description at 4044614c>, <Element {http://purl.org/rss/1.0/}link at 4044630c>, <Element {http://purl.org/rss/1.0/}item at 40 4463ac>, <Element {http://purl.org/rss/1.0/}title at 404463cc>, <Element {http:/ /purl.org/rss/1.0/}description at 404462ac>, <Element {http://purl.org/rss/1.0/} link at 4044640c>] Any ideas are greatly appreciated. From gregpinero at gmail.com Sat Aug 4 17:52:16 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Sat, 04 Aug 2007 21:52:16 -0000 Subject: Best way to capture output from an exec'ed (or such) script? In-Reply-To: <1186154066.529360.90260@q75g2000hsh.googlegroups.com> References: <1186084086.212050.264270@q3g2000prf.googlegroups.com> <mailman.1547.1186097565.22759.python-list@python.org> <1186154066.529360.90260@q75g2000hsh.googlegroups.com> Message-ID: <1186264336.502429.232840@r34g2000hsd.googlegroups.com> On Aug 3, 11:14 am, "gregpin... at gmail.com" <gregpin... at gmail.com> wrote: > On Aug 2, 7:32 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote:> If your web server is multithreaded (or you use some other way to process > > many simultaneous requests) you have to be more careful - remember that > > sys.stdout is global, you must find a way to distinguish between output > > from different processes all going into the same collector. > > Any ideas on how to do this? Is it even possible? > > -Greg I'm actually worried about this now. Does anyone know of any potential solutions? Anything to at least get me started? -Greg From horpner at yahoo.com Wed Aug 8 16:22:04 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 08 Aug 2007 20:22:04 GMT Subject: Misleading wikipedia article on Python 3? References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <mailman.1660.1186380664.22759.python-list@python.org> <7xzm15q8fy.fsf@ruckus.brouhaha.com> <eICti.37400$G23.15165@newsreading01.news.tds.net> <41Dti.37401$G23.10727@newsreading01.news.tds.net> <1186582066.096793.14700@57g2000hsv.googlegroups.com> <slrnfbk05n.20o.horpner@FIAD06.norwich.edu> <1186600271.858692.182090@22g2000hsm.googlegroups.com> <7xmyx1bxkf.fsf@ruckus.brouhaha.com> Message-ID: <MBpui.37519$G23.36050@newsreading01.news.tds.net> On 2007-08-08, Paul Rubin <http> wrote: > Istvan Albert <istvan.albert at gmail.com> writes: >> apply(), callable(), coerce(), file(), reduce(), reload() > > reduce() is really gone????? Maybe itertools can get an > ireduce function or something like that? I don't see how file() can be "removed", actually, unless the file type itself is getting axed. -- Neil Cerutti From arkanes at gmail.com Thu Aug 30 13:17:17 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 30 Aug 2007 12:17:17 -0500 Subject: Python threading In-Reply-To: <1188492781.894079.153260@r23g2000prd.googlegroups.com> References: <1188492781.894079.153260@r23g2000prd.googlegroups.com> Message-ID: <4866bea60708301017s53bfb9a2g9652b8e7899363c4@mail.gmail.com> On 8/30/07, Robert.R.Emmel at gmail.com <Robert.R.Emmel at gmail.com> wrote: > Hello, > > I am using the threading module and the Queue module in python to to > send out shipment tracking URL requests. > > Is there a way to timeout a thread within a Queue? > > I think the way I have it now the thread will wait until something is > returned and will basically wait forever for that something. > > Between the waiting for something to be returned and the timeouts on > the database connections, the program appears to just hang like it has > stopped working. Any suggestions? > > Here is a sample of code I am using (left out some of the code for > brevity): > <code snipped> The two possible implementations: a) Use a timeout in your get() call to allow to check for thread termination b) push a sentinel object into the Queue that means "please exit now". From ed at leafe.com Fri Aug 24 11:08:45 2007 From: ed at leafe.com (Ed Leafe) Date: Fri, 24 Aug 2007 11:08:45 -0400 Subject: creating a tar file with python In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE2EE@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> <faktv8$8fs$1@sea.gmane.org> <93066C069973ED448DC2BCEA9C44A7383BE2ED@efmailx> <46CE4D3D.7020106@holdenweb.com> <93066C069973ED448DC2BCEA9C44A7383BE2EE@efmailx> Message-ID: <B925F95D-D8B0-4820-B4BB-0D189226684F@leafe.com> On Aug 23, 2007, at 11:27 PM, Brian McCann wrote: > I ran the code as you suggested, didn't work, tried variations of > it didn't work, > If you don't know the answer don't pretend you do! > > Apology not accepted, please don't wake up! > > Future correspondence on any python questions from you go to trash. > May your pillow not have pity on your head! What a tool. Add another to the twit filter... -- Ed Leafe -- http://leafe.com -- http://dabodev.com From arkanes at gmail.com Thu Aug 30 19:50:59 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 30 Aug 2007 18:50:59 -0500 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188517050.174081.265900@x40g2000prg.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> <mailman.120.1188423362.28954.python-list@python.org> <1188430887.481586.106760@l22g2000prc.googlegroups.com> <mailman.159.1188499976.28954.python-list@python.org> <1188504811.019632.186580@x35g2000prf.googlegroups.com> <46d75116$0$401$426a74cc@news.free.fr> <1188517050.174081.265900@x40g2000prg.googlegroups.com> Message-ID: <4866bea60708301650n639db1d3v3be9c31c0bbec3ab@mail.gmail.com> On 8/30/07, Russ <uymqlp502 at sneakemail.com> wrote: > > Bruno Desthuilliers wrote: > > Russ a ?crit : > > (snip) > > > > > I don't see how you can avoid adding some new syntax, given that > > > Python does not > > > currently have syntax for specifying invariants and pre- and post- > > > conditions. > > > > class Parrot(object): > > @pre(lambda x : x != 42) > > @post(lambda result: result != 42) > > @invariant(lambda self: self.x == 42) > > def reliable_method(self, x): > > # your code here > > return something > > That looks like new syntax to me. Did I miss your point? > > I have no strong leaning about what the exact syntax should be for > programming by contract. > The syntax you show above seems reasonable, except that I am not sure > about requiring > that everything be put inside parentheses. That seems a bit confining > for more complex > conditions. > This is existing, working python syntax (although the decorators would need to be defined). > -- > http://mail.python.org/mailman/listinfo/python-list > From bignose+hates-spam at benfinney.id.au Thu Aug 30 04:02:15 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 30 Aug 2007 18:02:15 +1000 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <46d674c2$0$417$426a34cc@news.free.fr> Message-ID: <878x7te9h4.fsf@benfinney.id.au> Bruno Desthuilliers <bruno.42.desthuilliers at wtf.websiteburo.oops.com> writes: > What's with using your brain instead of whining ? Now now, no need for snappiness. If you don't feel a constructive response is merited, please ignore. -- \ "A lot of people are afraid of heights. Not me, I'm afraid of | `\ widths." -- Steven Wright | _o__) | Ben Finney From kst-u at mib.org Thu Aug 30 21:57:13 2007 From: kst-u at mib.org (Keith Thompson) Date: Thu, 30 Aug 2007 18:57:13 -0700 Subject: Important Research Project References: <13ddcvm1bsu3s94@corp.supernews.com> <46D6CA0E.E66ED5C8@yahoo.com> <13deq9nj9atft62@corp.supernews.com> Message-ID: <lnsl60o492.fsf@nuthaus.mib.org> "E.D.G." <edgrsprj at ix.netcom.com> writes: > "CBFalconer" <cbfalconer at yahoo.com> wrote in message > news:46D6CA0E.E66ED5C8 at yahoo.com... >> "E.D.G." wrote: > >> Where is Perl described in the C standard? This seems rather OT. > > It has been my experience that a person who is an expert with one computer > language can usually do reasonably well when working with other languages. > I am trying to find some people who can assist with getting a Perl program > running. It would probably be easier for expert programmers in any language > to help with this type of work compared with people such as myself who are > not experts in any programming language. CBFalconer's point is that this newsgroup (comp.lang.c, where he and I are both reading this) is for discussion of the C programming language. If you want to discuss something other than C, please find another forum. Massive cross-posts like this are rarely appropriate. -- Keith Thompson (The_Other_Keith) kst-u at mib.org <http://www.ghoti.net/~kst> San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst> "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister" From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Aug 11 17:46:05 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 11 Aug 2007 23:46:05 +0200 Subject: The Future of Python Threading References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <5i329uF3muir4U1@mid.individual.net> <slrnfbou9k.vkb.nick@irishsea.home.craig-wood.com> <5i45luF3mvdesU1@mid.individual.net> <slrnfbrg68.dpo.nick@irishsea.home.craig-wood.com> Message-ID: <5i6p0tF3mr9f4U4@mid.individual.net> Nick Craig-Wood wrote: > Bjoern Schliessmann <usenet-mail-0306.20.chr0n0ss at spamgourmet.com> >> So, how much performance gain would you get? Again, managing >> fine-grained locking can be much more work than one simple lock. > > Assuming that you are not IO bound, but compute bound and that > compute is being done in python then you'll get a speed up > proportional to how many processors you have, minus a small amount > for locking overhead. Assuming this: Agreed. Regards, Bj?rn -- BOFH excuse #348: We're on Token Ring, and it looks like the token got loose. From bignose+hates-spam at benfinney.id.au Sat Aug 4 19:17:14 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 05 Aug 2007 09:17:14 +1000 Subject: sqlite3 create table col width? References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> <1186240708.874804.271030@b79g2000hse.googlegroups.com> <1186245190.970687.307920@k79g2000hse.googlegroups.com> <mailman.1620.1186249934.22759.python-list@python.org> Message-ID: <87r6miao05.fsf@benfinney.id.au> jim-on-linux <inq1ltd at inqvista.com> writes: > PY help, > > Using sqlite3 v3.1.3 You made this message a reply to an existing discussion, so your message is now part of that existing discussion. Please start a new discussion thread by composing a new message. -- \ "True greatness is measured by how much freedom you give to | `\ others, not by how much you can coerce others to do what you | _o__) want." --Larry Wall | Ben Finney From fabioztessitore at libero.it Thu Aug 2 05:12:04 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 02 Aug 2007 09:12:04 GMT Subject: Error with Tkinter and tkMessageBox References: <46af71b7$0$10619$4fafbaef@reader2.news.tin.it> <mailman.1481.1186027758.22759.python-list@python.org> <46b19caa$0$17951$4fafbaef@reader1.news.tin.it> Message-ID: <46b19fe4$0$17952$4fafbaef@reader1.news.tin.it> I've tried to use Twm and SURPRISE! it works!!! Can you say why? How can I fix the prob with Gnome? Thanks From draghuram at gmail.com Tue Aug 28 14:40:45 2007 From: draghuram at gmail.com (draghuram at gmail.com) Date: Tue, 28 Aug 2007 18:40:45 -0000 Subject: tempfile.mkstemp and os.fdopen In-Reply-To: <1188323759.955043.317630@19g2000hsx.googlegroups.com> References: <1188323759.955043.317630@19g2000hsx.googlegroups.com> Message-ID: <1188326445.329622.307880@q5g2000prf.googlegroups.com> On Aug 28, 1:55 pm, billiejoex <gne... at gmail.com> wrote: > In conjunction I used os.fdopen() to get a wrapper around file > properties (write & read methods, and so on...) but 'name' attribute > does not contain the correct file name. Why? > > >>> import os > >>> import tempfile > >>> fileno, name = tempfile.mkstemp(prefix='ftpd.', dir=os.getcwd()) > >>> fd = os.fdopen(fileno, 'wb') > >>> fd.name > > <fdopen> > > Moreover, I'd like to know if I'm doing fine. Does this approach avoid > race conditions or other types of security problems? > > Thanks in advance There seems to be a feature request for this: http://bugs.python.org/issue1625576 From pablo.mitchell at gmail.com Thu Aug 2 21:20:49 2007 From: pablo.mitchell at gmail.com (pablo.mitchell at gmail.com) Date: Thu, 02 Aug 2007 18:20:49 -0700 Subject: Efficient Rank Ordering of Nested Lists Message-ID: <1186104049.022836.253470@e9g2000prf.googlegroups.com> A naive approach to rank ordering (handling ties as well) of nested lists may be accomplished via: def rankLists(nestedList): def rankList(singleList): sortedList = list(singleList) sortedList.sort() return map(sortedList.index, singleList) return map(rankList, nestedList) >>> unranked = [ [ 1, 2, 3, 4, 5 ], [ 3, 1, 5, 2, 4 ], [ -1.1, 2.2, 0, -1.1, 13 ] ] >>> print rankLists(unranked) [[0, 1, 2, 3, 4], [2, 0, 4, 1, 3], [0, 3, 2, 0, 4]] This works nicely when the dimensions of the nested list are small. It is slow when they are big. Can someone suggest a clever way to speed it up? From ivlenin at gmail.com Wed Aug 22 01:31:57 2007 From: ivlenin at gmail.com (I V) Date: Wed, 22 Aug 2007 05:31:57 GMT Subject: IDE for Python References: <mailman.55.1187690455.32294.python-list@python.org> <1187698999.545439.322600@k79g2000hse.googlegroups.com> <mailman.91.1187742207.32294.python-list@python.org> Message-ID: <hTPyi.4052$Oo.2475@newssvr17.news.prodigy.net> On Tue, 21 Aug 2007 21:23:25 -0300, Ricardo Ar?oz wrote: > Do you know if for in-house development a GPL license applies? (Qt4 > and/or Eric4). (I'm not sure if I've understood your question right) If you distribute an app that _uses_ PyQT, you have to comply with the GPL (or buy a license from Trolltech), but note that this doesn't really have anything to do with Eric4. Running Eric4 doesn't require a license (either the GPL or Trolltech), and code you write using Eric4 doesn't have to be licensed according to the GPL either. From mail at microcorp.co.za Tue Aug 14 10:30:55 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 14 Aug 2007 16:30:55 +0200 Subject: (sort of) deterministic timing in Python References: <1i2si8h.1qc8f77i68gyeN%johnmfisher@comcast.net> Message-ID: <01f201c7de7f$d6e9ae00$03000080@hendrik> "John Fisher" <jo.....cast.net> wrote: import time period_time = TIME_CONSTANT # The time of a period in seconds - 0.001 is a millisec >mark start time start_time = time.time() >start event > event finishes event_time = time.time() - start_time wait_time = period_time-event_time >count time until next interval if wait_time > 0: time.sleep(wait_time) >start second event? that should (sort of) do it. HTH - Hendrik From steve at holdenweb.com Wed Aug 15 12:12:31 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 15 Aug 2007 12:12:31 -0400 Subject: Guitar Reviews In-Reply-To: <1187181739.853467.94630@r34g2000hsd.googlegroups.com> References: <1187181172.442413.193040@57g2000hsv.googlegroups.com> <1187181739.853467.94630@r34g2000hsd.googlegroups.com> Message-ID: <f9v8l8$rsr$1@sea.gmane.org> Dustan wrote: > On Aug 15, 7:32 am, cve... at gmail.com wrote: > <snip> > >>>> op.mother.speak() > Congratulations! You've just given your email address to millions of > people across Usenet! > What do you have to say for yourself? Probably something along the lines of "that's OK, it's disposable so I don't care who knows it". regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From sjmachin at lexicon.net Mon Aug 6 19:04:32 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 06 Aug 2007 16:04:32 -0700 Subject: xlrd question In-Reply-To: <mailman.1596.1186188547.22759.python-list@python.org> References: <mailman.1596.1186188547.22759.python-list@python.org> Message-ID: <1186441472.515556.27840@m37g2000prh.googlegroups.com> On Aug 4, 10:48 am, JYOUN... at kc.rr.com wrote: > I ran your code which gave me this: > > >>> import sys, xlrd; print sys.version; print xlrd.__file__ > > 2.3.5 (#1, Jan 30 2006, 13:30:29) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1819)] > /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/ > xlrd/__init__.pyc > > and as far as I can tell, the runxlrd.py file is located here (where I had drug this folder > originally): > > Macintosh HD/xlrd-0.6.1/scripts/runxlrd.py > > So if I'm understanding this correctly, xlrd only uses the folder you download (xlrd-0.6.1) > and then moves the > '__init__.pyc' file to the location mentioned above? Try actually *looking* in "the location mentioned above". Try actually *looking* in the download folder -- do you see a file called __init__.pyc? If you do, check the creation timestamp :-) > > There's definitely no problems or concerns. :-) I'm doing a bit of research to see if this > might be something I > use down the road at work. Our I/T department is extremely strict as to what we put on > employees machines > so I want to have a good understanding as to where files are installed so I can let i/T know all > the details. I would have thought that: (1) If your company already uses Python, the IT dept should have already come to grips with installing third- party packages, and shouldn't need your help to find out where a package's files are installed. (2) If they don't already use Python, where a packages's files are installed is a minor fraction of the concerns that would need to be overcome. (3) It might be a good idea to ask informally what would be required to get a particular package made available. From programmer.py at gmail.com Tue Aug 14 12:37:53 2007 From: programmer.py at gmail.com (programmer.py at gmail.com) Date: Tue, 14 Aug 2007 16:37:53 -0000 Subject: Simple python iteration question In-Reply-To: <1i2ulxb.179bf9ppsie5uN%raims@dot.com> References: <bFkwi.675$Oo.563@newssvr17.news.prodigy.net> <1i2ulxb.179bf9ppsie5uN%raims@dot.com> Message-ID: <1187109473.796762.159800@g4g2000hsf.googlegroups.com> On Aug 14, 11:27 am, ra... at dot.com (Lawrence Oluyede) wrote: > Bryan <b... at bcc.com> wrote: > > How do I do this? > > for i, item in enumerate(l): > print i, item > ^^ That is the `most-correct` answer. But because you're new, I'll take this time to introduce you to help(), just in case you're too lazy to RTFM (like me ;)). help works on objects, and things you may not expect - try help(2). Oh and welcome to `fun` programming! >>> help(enumerate) class enumerate(object) | enumerate(iterable) -> iterator for index, value of iterable | | Return an enumerate object. iterable must be an other object that supports | iteration. The enumerate object yields pairs containing a count (from | zero) and a value yielded by the iterable argument. enumerate is useful | for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ... .. and a bunch of stuff I clipped ... hth, jw From kw at codebykevin.com Wed Aug 8 14:22:32 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 08 Aug 2007 14:22:32 -0400 Subject: Tkinter or wxpython? In-Reply-To: <mailman.1757.1186592594.22759.python-list@python.org> References: <op.tv98rva4wepdt4@ericb.pragmadev> <mailman.1677.1186412323.22759.python-list@python.org> <7xlkcopu4r.fsf@ruckus.brouhaha.com> <7x7io8r6na.fsf@ruckus.brouhaha.com> <hgamo4-p2m.ln1@lairds.us> <46B9DE7B.3050909@codebykevin.com> <mailman.1750.1186587557.22759.python-list@python.org> <46B9F09B.2060903@codebykevin.com> <mailman.1757.1186592594.22759.python-list@python.org> Message-ID: <54bd9$46ba09ec$4275d90a$9068@FUSE.NET> Chris Mellon wrote: >> What do you mean here? Things like keyboard accelerators, menu >> placement, and so on? Those things are already natively implemented by >> Tk, and the developer just needs to invoke them. Sometimes some >> conditional code is required for stuff like keyboard accelerators (the >> "tk windowingsytem" command is useful for this), but again, it should >> Just Work. >> >> Or am I missing something? >> > > There's conventions for shortcuts and they vary by platform. For > example, home/end do different things on a mac vs on windows. > Scrollbars interact differently, and menu pulldowns operate > differently. To my knowledge, while Tile can replicate the *look* of > these things, it does not help with the interaction. On Windows and Mac, Tk gets the menus correct by default (menu is at the top of the screen on the Mac, attached to a window on Windows). The Tk scrollbar is native on the Mac; the Tile scrollbar has problems. On Windows, the Tile scrollbar maps to Vista or XP or Win32, depending on Windows version. You need to correctly specify the command-accelerator in your code (on Windows it's the Control key, on the Mac it's Command), but assuming you do this, it works fine. I don't use "home" and "end" keys myself (I think these are more common on Windows than Mac) so I can't speak to that. Under Tk, keyboard navigation with the tab key generally works as expected on the Mac, and I assume so for Windows as well. The biggest drawback with Tk/Tile on the Mac is that even with Tile theming, it's still a bit outdated--Tile hooks into some older API's on the Mac that are more compatible with Tk; for instance, the notebook tabs look like Jaguar-era tabs (c. 2002). The Tile scrollbar is broken, but the Tk one works natively. Tile on Windows looks pretty darn good--I've played with the Windows Inspection Tool Kit, a well-designed Tcl/Tk application on Windows XP that uses Tile, and it's indistinguishable from something developed in VB or Delphi. (See http://magicsplat.com/wits/screenshot.html). Tile on the Mac requires a bit more hackery, but it's quite possible to get something looking nearly native (see http://www.codebykevin.com/portauthority.html). As for X, Tk and Tile are more of a mixed bag, because there is simply no single standard to target. Standard Tk looks and feels like Motif, as you know. Some of the Tile themes under X don't look much better. The most popular Tile theme on X is probably Clam, which looks more like a modern Gtk Clearlooks-style theme (see http://tktable.sourceforge.net/tile/screenshots/demo-clam-unix.png or http://www.codebykevin.com/pylocate-tile-x11.png). As far as I know, Tk/Tile offers reasonable defaults for X, unless you are looking for specfic integration with a particular environment (i.e. Gnome or KDE); in that case it's not as acceptable. > > Don't think I'm singling out Tk, Gtk has exactly the same problem - > you can make the buttons look native, but it doesn't adjust the > behavior. Tk does a better job with platform-specific defaults and behaviors than Gtk. When I read complaints about Tk on Windows, it's more on how ugly Tk is, not that its menus/keyboard behaviors don't work correctly. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From wildemar at freakmail.de Mon Aug 13 07:41:54 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 13 Aug 2007 13:41:54 +0200 Subject: check if var is dict In-Reply-To: <46C02BFA.10703@al.com.au> References: <46C02BFA.10703@al.com.au> Message-ID: <46C04382.7050808@freakmail.de> Astan Chee wrote: > Hi, > I have a variable, I want to check if it is a dictionary or a string. > Is there any better way to do this than I've done. How I did it is by > doing a .items() and catching a AttributeError that it raises if its not > a dictionary. > How do i properly do it? > The way you did, actually :). Look for "It's better to ask for forgiveness than for permission" (or so) and the term "duck typing". That's the way to do it in python. And just for completeness' sake: You could have also checked for actual types via "isinstance(your_variable, dict) or "type(your_variable) is type(dict)" or ... But your approach is the recomended one. /W From fabioztessitore at libero.it Thu Aug 2 04:58:18 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 02 Aug 2007 08:58:18 GMT Subject: Error with Tkinter and tkMessageBox References: <46af71b7$0$10619$4fafbaef@reader2.news.tin.it> <mailman.1481.1186027758.22759.python-list@python.org> Message-ID: <46b19caa$0$17951$4fafbaef@reader1.news.tin.it> Il Thu, 02 Aug 2007 13:54:46 +1000, John McMonagle ha scritto: > What window manager are you using ? Hi John, I'm using gnome, with gdm. Do you think the problem is this? I'm going to try with another one ... bye From Dominic at PLEASEASK.co.uk Tue Aug 14 04:13:47 2007 From: Dominic at PLEASEASK.co.uk (special_dragonfly) Date: Tue, 14 Aug 2007 09:13:47 +0100 Subject: about negative polar plots References: <1187076466.955318.249250@57g2000hsv.googlegroups.com> <9radnTbkCoefwFzbnZ2dnUVZ_vPinZ2d@speakeasy.net> Message-ID: <46c16063$0$54289$7b0f0fd3@mistral.news.newnet.co.uk> "Erik Max Francis" <max at alcyone.com> wrote in message news:9radnTbkCoefwFzbnZ2dnUVZ_vPinZ2d at speakeasy.net... > yadin wrote: > >> hi am doing a polar plot of the radiation pattern of an antenna. >> the polar plots represents the value of the power in dB's and the dB >> go from -40dB to 0dB >> as the angle theta changes from 0 to 2*pi rads >> the polar plot in python goes with positive values >> how can i solve this problem >> rough example >> example: >> power = arange(-40,0,-10) >> theta = arange(0, 2pi,pi/12) >> polar(power,theta) >> title.....? >> how can i show the step on the polar plot plot(-40, -30,-20,-10,0) > > What is arange? What is polar? What is plot? You're going to have to > give more information about what you're doing, what you're using to do it, > and where it's giving you unexpected or undesired results if you want help > solving your problem. > > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis > So look into my eyes / I won't tell you lies > -- Neneh Cherry I can understand the problem, that when plotting in polar co-ordinates the center of the plot is a value of zero. You're wanting a value of -40 at the center? Is this a fixed quantity? The lines would then extend out to be zero at infinity, presumably by an inverse square law (as it's dB's - unless my physics is wrong). It sounds horrible, but if you know the angle and value, could you not convert to cartesian co-ordinates and plot them? Am I also right in thinking that the example you've given is MATLAB code where you have essentially 2 lists and a function? So power=arange(-40,0,-10) is a list looking like this: [-40,-30,-20,-10,0] theta is a list from 0 to 2pi increasing in increments of pi/12 and the function polar takes the power and theta value and returns... pass (would need to look up the function). http://www.k0gkd.com/fd02.jpg <-- something like this at the end of the day is what is wanted - correct? Now I'm not sure why you can't take your negative value and modulus it with 40 (or whatever value you want at the center). So -40 becomes 40 becomes 0 (the center), -30 becomes 30 becomes 10 (the next band out?) At the end of the day it'll be the labels on the graph you need to change. Tell me if this helps! Dominic From gagsl-py2 at yahoo.com.ar Mon Aug 20 04:26:57 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 20 Aug 2007 05:26:57 -0300 Subject: Retry: Question about FutureWarning References: <alpine.LFD.0.999.0708142137550.22214@saturn.syslang.net> Message-ID: <op.txcm27jdx6zn5v@a98gizw.cpe.telecentro.net.ar> En Tue, 14 Aug 2007 22:44:17 -0300, Steven W. Orr <steveo at syslang.net> escribi?: > The shell compile command I use to generate both the .pyc and the .pyo > files is: > > python=/usr/bin/python2.3 > i_python () > { > $python -c "import $1" > $python -O -c "import $1" > } This is irrelevant to your main question - but try the compileall module in the standard library. -- Gabriel Genellina From yattamax at gmail.com Wed Aug 1 08:15:26 2007 From: yattamax at gmail.com (The Max) Date: Wed, 01 Aug 2007 12:15:26 -0000 Subject: wxPython version question Message-ID: <1185970526.612299.277930@o61g2000hsh.googlegroups.com> Hi at all Hi have need of testing the version of wxPython in use .... at the moment I use wxversion, but I don't can find a method for testing version like this: if versionOfWX() <= 2.8: or if versionOfWX() >= 2.8: ( versioneOfWX is a pseudo-function create for this example ) Someone know a solution for this ? Thanks and sorry for my orrible english From Andy.cheesman at bristol.ac.uk Wed Aug 29 09:31:23 2007 From: Andy.cheesman at bristol.ac.uk (Andy Cheesman) Date: Wed, 29 Aug 2007 14:31:23 +0100 Subject: Python molecular viewer Message-ID: <46D5752B.4030108@bristol.ac.uk> Dear People, I was wondering if people could recommend a simple molecular viewing package written in python. I'm working in Theoretical chemistry and I'm not after an all-singing dancing molecular rendering package(pymol does that rather well) but a program which reads XYZ files and displays simple structures which can be rotated in 3D Thanks Andy From laurent.pointal at limsi.fr Tue Aug 14 09:10:51 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 14 Aug 2007 15:10:51 +0200 Subject: Script to copy database In-Reply-To: <GeOdnSj725utPFzbnZ2dnUVZ_vOlnZ2d@centurytel.net> References: <GeOdnSj725utPFzbnZ2dnUVZ_vOlnZ2d@centurytel.net> Message-ID: <f9s9ks$hns$1@news2.u-psud.fr> Tony a ?crit : > I'm new at this and would like to know how set up a script to copy a > database from a local computer to a network at a certain time everyday. > Should be simple enough, but, as of now I am unfamiliar with how to do this. > Would this be done by writing a script and setting up a scheduled task to > run the script? Can anyone help me with the script? Just need it to copy > an Access database from the local C: drive to a network F: drive. > > Thanks, > Tony > > As you wrote about c: and f:, I imagine you are working under Windows. IMHO you dont need Python for that. domybackup.bat copy c:\mypathtothefile\thefile.xxx F:\mypathdobackudir\ And use your "planificateur de taches" (its corresponding english control panel) to setup a periodic call to this batch file, eventually associate an ad-hoc account to the task, so that the batch can access the file to backup. If you need more (ie. network access to setup/clean), here is a copy of a script I use to export (using a Python script) an Access database. Just replace the call to the Python script by a simple call to copy xxx yyyy. @echo off REM LANCEMENT DE L'EXPORT DE LA BASE ADMINISTRATIVE EN MODE TACHE REM DE FOND (BATCH). SET EXPORTS_BATCH=1 REM Parametres pour se connecter a la machine de transfert. SET EXPORTS_HOST=thecomputer SET EXPORTS_SHARE=data SET EXPORTS_DRIVE=O: SET EXPORTS_USER=theremotuser SET EXPORTS_PASSWD=theremotepasswd REM Montage du volume. REM le start pour permettre d'attendre que le montage soit effectif. START /wait NET USE %EXPORTS_DRIVE% \\%EXPORTS_HOST%\%EXPORTS_SHARE% %EXPORTS_PASSWD% /USER:%EXPORTS_USER% /PERSISTENT:No IF ERRORLEVEL 1 GOTO erreur_montage REM Parametres pour le script Python. SET SCRIPT_EXPORT="C:\Documents and Settings\myaccount\My Documents\mybexport.py" SET DSN_BASE_ADMIN=mydbaccound SET LOGIN_BASE_ADMIN=mydbpasswd SET PATH_FICHIERS_EXPORTS=%EXPORTS_DRIVE%\ REM Variables d'environnement eventuellement utiles... SET TEMP=%PATH_FICHIERS_EXPORTS% SET TMP=%PATH_FICHIERS_EXPORTS% REM Lancement du script Python qui realise l'export. C:\Tools\Python24\python.exe %SCRIPT_EXPORT% REM Deconnexion du volume. NET USE %EXPORTS_DRIVE% /DELETE goto termine :erreur_montage ECHO "Erreur %ERROR_LEVEL% au montage de \\%EXPORTS_HOST%\%EXPORTS_SHARE% en lecteur %EXPORTS_DRIVE%." :termine From danb_83 at yahoo.com Thu Aug 23 23:49:48 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Thu, 23 Aug 2007 20:49:48 -0700 Subject: beginner, idomatic python 2 In-Reply-To: <13csjmeaoqh9le3@corp.supernews.com> References: <13csjmeaoqh9le3@corp.supernews.com> Message-ID: <1187927388.173203.298660@e9g2000prf.googlegroups.com> On Aug 23, 10:21 pm, "bambam" <da... at asdf.asdf> wrote: > Would someone like to suggest a replacement for this? This is a > function that returns different kinds of similar objects, depending > on what is asked for. PSP and PWR are classes. I don't really > want to re-write the calling code very much: I'm just wondering > if the function can be replaced with some kind of OOP pattern. > > def Device(DeviceType): > if DeviceType=='PSP': > return PSP() > elif DeviceType=="Power Supply" > return PWR() > etc... > > Thanks! Typically, you'd use a dictionary: DEVICE_DICT = { 'PSP': PSP. 'Power Supply': PWR, # etc. } and your function would simply return DEVICE_DICT[device_type]() From jrjt at 411.ca Wed Aug 1 20:18:16 2007 From: jrjt at 411.ca (Bell) Date: Wed, 1 Aug 2007 17:18:16 -0700 Subject: Doc Message-ID: <46B122C8.1060700@insuranceland.org> -------------- next part -------------- A non-text attachment was scrubbed... Name: Doc.pdf Type: application/pdf Size: 15232 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20070801/892422fd/attachment.pdf> From vito.detullio at gmail.com Fri Aug 24 11:24:32 2007 From: vito.detullio at gmail.com (ZeD) Date: Fri, 24 Aug 2007 15:24:32 GMT Subject: List Comprehension Question: One to Many Mapping? References: <1187929443.636690.287450@i13g2000prf.googlegroups.com> <7x8x81l9z3.fsf@ruckus.brouhaha.com> <mailman.241.1187951774.32294.python-list@python.org> Message-ID: <QKCzi.96010$U01.834323@twister1.libero.it> Boris Borcic wrote: >>> For example, if I have x=[ [1,2], [3,4] ] >>> What I want is a new list of list that has four sub-lists: >>> [[1,2], [f(1), f(2)], [3,4], [f(3), f(4)]] >> [[a, map(f,a)] for a in x] > [map(g,a) for a in x for g in [None,f]] > will do it. > > ...a bit too cleverly, but there's worse : > list((yield a) or map(f,a) for a in x) worse (in *many* ways) solutions: l = [[a, map(f,a)] for a in x] 1) s = sum(l, []) 2) from operator import add r = reduce(add, l, []) 3) a = [] for e in l: a.extend(e) -- Under construction From kyosohma at gmail.com Fri Aug 17 09:56:12 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 17 Aug 2007 06:56:12 -0700 Subject: Downloading multiple csv files from a website In-Reply-To: <1187356117.474747.189980@g4g2000hsf.googlegroups.com> References: <1187356117.474747.189980@g4g2000hsf.googlegroups.com> Message-ID: <1187358972.458872.241790@i13g2000prf.googlegroups.com> On Aug 17, 8:08 am, tkp... at hotmail.com wrote: > I'd like to download data from the websitehttp://www.russell.com/Indexes/performance/daily_values_US.asp. On > this web page, there are links to a number of .csv files, and I'd like > to download all of them automatically each day. The file names are not > visible on the page, but if I click on a link, a csv file opens in > Excel. I've searched this group and looked into urllib, but have not > found functions or code snippets that will allow me to download and > rename each file. Would someone kindly point me to appropriate > libraries/functions and/or code snippets that will get me started? > > Thanks in advance > > Thomas Philips This link shows how to extract a list of URLs: http://www.java2s.com/Code/Python/Network/ExtractlistofURLsinawebpage.htm and this one shows how to download: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/83208 Mike From paddy3118 at googlemail.com Sat Aug 4 11:18:28 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 04 Aug 2007 15:18:28 -0000 Subject: (no) fast boolean evaluation ? In-Reply-To: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> Message-ID: <1186240708.874804.271030@b79g2000hse.googlegroups.com> On Aug 2, 10:47 pm, Stef Mientki <S.Mientki-nos... at mailbox.kun.nl> wrote: > hello, > > I discovered that boolean evaluation in Python is done "fast" > (as soon as the condition is ok, the rest of the expression is ignored). > > Is this standard behavior or is there a compiler switch to turn it on/off ? > > thanks, > Stef Mientki The following program shows a(clumsy)? way to defeat the short- circuiting: def f(x): print "f(%s)=%s" % ('x',x), return x def g(x): print "g(%s)=%s" % ('x',x), return x print "\nShort circuit" for i in (True, False): for j in (True, False): print i,j,":", f(i) and g(j) print "\nShort circuit defeated" for i in (True, False): for j in (True, False): print i,j,":", g(j) if f(i) else (g(j) and False) The output is: Short circuit True True : f(x)=True g(x)=True True True False : f(x)=True g(x)=False False False True : f(x)=False False False False : f(x)=False False Short circuit defeated True True : f(x)=True g(x)=True True True False : f(x)=True g(x)=False False False True : f(x)=False g(x)=True False False False : f(x)=False g(x)=False False - Paddy. From nospam.themindstorm at gmail.com Thu Aug 2 18:20:46 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Thu, 2 Aug 2007 22:20:46 +0000 (UTC) Subject: Pythonic way for missing dict keys References: <mailman.938.1184958565.22759.python-list@python.org> <pan.2007.07.21.00.20.54.768439@REMOVE.THIS.cybersource.com.au> <mailman.954.1184989959.22759.python-list@python.org> <Xns99748CC2DB4AAduncanbooth@127.0.0.1> <1185041243.323915.161230@x40g2000prg.googlegroups.com> <mailman.984.1185101740.22759.python-list@python.org> <87lkd0eprj.fsf@pobox.com> <mailman.1279.1185623588.22759.python-list@python.org> <pan.2007.07.29.04.10.19.329342@REMOVE.THIS.cybersource.com.au> <46b0ed0b$0$2257$426a74cc@news.free.fr> <mailman.1493.1186042809.22759.python-list@python.org> <46b1b0ba$0$25340$426a74cc@news.free.fr> <1i27mku.1sc8l3x1dda3crN%aleax@mac.com> Message-ID: <Xns9981D5A0F001themindstorm@80.91.229.5> aleax at mac.com (Alex Martelli) wrote in news:1i27mku.1sc8l3x1dda3crN% aleax at mac.com: > Bruno Desthuilliers <bruno.42.desthuilliers at wtf.websiteburo.oops.com> > wrote: > >> Alex Popescu a ?crit : > > [... snip ...] > > > The mere check of whether an object possesses some important special > method is best accomplished through the abstract-base-classes machinery > (new in Python 3.0: see <http://www.python.org/dev/peps/pep-3119/>). At > this time there is no Callable ABC, but you're welcome to argue for it > on the python-3000 mailing list (please do check the archives and/or > check privately with the PEP owner first to avoid duplication). > This PEP sounds very similar to Java interfaces (well, as an enhanced version as you are allowed to programmatically control this inheritance chain). Interesting approach. And now I can agree that the removal of callable() makes sense! Thanks a lot for the pointer Alex. ./alex -- .w( the_mindstorm )p. > > Alex > From kyosohma at gmail.com Wed Aug 8 14:57:52 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 08 Aug 2007 18:57:52 -0000 Subject: Launch file from Python In-Reply-To: <1186596679.600526.172640@r34g2000hsd.googlegroups.com> References: <1186594137.971393.128780@57g2000hsv.googlegroups.com> <1186594611.490723.251870@m37g2000prh.googlegroups.com> <1186596679.600526.172640@r34g2000hsd.googlegroups.com> Message-ID: <1186599472.265527.26140@j4g2000prf.googlegroups.com> On Aug 8, 1:11 pm, jocago <joc... at gmail.com> wrote: > The application, however, never runs. I'll give the sub-process a > shot. Thanks. Well, that's a problem. I suppose the best thing to try is use some smaller sets of flags and see if they work. Instead of your long string, try something smaller, like: subprocess.Popen("xplanet-1.2.0/xplanet.exe -fontsize 24 -label - target earth", shell=True) Once you've gotten it to work on a smaller scale, you should be able to work your way up. Mike From gandalf at shopzeus.com Fri Aug 17 15:24:58 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 17 Aug 2007 21:24:58 +0200 Subject: Problem with directory recursion! In-Reply-To: <496954360708171116t4370c2ddra3d7905bc956c7eb@mail.gmail.com> References: <496954360708171116t4370c2ddra3d7905bc956c7eb@mail.gmail.com> Message-ID: <46C5F60A.6080305@shopzeus.com> > > Does anyone see anything immediately suspicious about the code? Yes. os.walk does the recursion for you. Either you should use os.listdir instead of os.walk, or use os.walk ONCE and iterate over the results. I prefer to use the former because usually I do not remember how os.walk works. Read and try the example that is given in the docs: http://docs.python.org/lib/os-file-dir.html Best, Laszlo From grante at visi.com Fri Aug 31 13:38:03 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 31 Aug 2007 17:38:03 -0000 Subject: Looking for Delaunay triangulation module... References: <13dge9m2339ka68@corp.supernews.com> Message-ID: <13dgkfr9n72sr32@corp.supernews.com> On 2007-08-31, Grant Edwards <grante at visi.com> wrote: > So for lack of a delaunay module, I'm stuck trying to port my > application to Win32. I've found that VTK contains a Delaunay triangulation module, and Entought Python includes VTK, so that's next on my list of things to try as soon as VTK finishes building on my Linux box (where I do all of my actual development). -- Grant Edwards grante Yow! hubub, hubub, HUBUB, at hubub, hubub, hubub, HUBUB, visi.com hubub, hubub, hubub. From db3l.net at gmail.com Wed Aug 29 16:08:25 2007 From: db3l.net at gmail.com (David Bolen) Date: Wed, 29 Aug 2007 16:08:25 -0400 Subject: Creating a multi-tier client/server application References: <1188360460.838635.186930@w3g2000hsg.googlegroups.com> <7xbqcqhqbw.fsf@ruckus.brouhaha.com> <46d54ed8$0$429$426a34cc@news.free.fr> <1188393925.007952.313110@r29g2000hsg.googlegroups.com> Message-ID: <m2642ygl3a.fsf@valheru.db3l.homeip.net> Jeff <jeff.fw at gmail.com> writes: > reasons, not the least of which is that I've been working almost > entirely on web apps for the past few years, and I am getting mighty > sick of it. A lot of that is due to the language (PHP, which I have > since grown to hate) I had to use. I've worked on a site for my self > in Python (using Pylons, actually--which is excellent) which was > vastly easier and more fun. But I'd really like to try something > different. To contribute a data point against your original question - I've a similar (structurally, not functionality) system I completed recently. Without trying to get too mired in the thick client v. web application debate, there were a handful of points that decided me in favor of the thick client: * Needed to automate QuickTime viewer for video previews and extraction of selected frames to serve as thumbnails on web approval page. * Needed to control transfers to server of multiple very large files (hundreds of MBs to GBs at a shot) But assuming a thick client, in terms of your original question of components to use, here's what I've got. My primary networking component is Twisted. The pieces are: Client (OS X Cocoa application): * PyObjC based. Twisted for networking, Twisted's PB for the primary management channel, with an independent direct network connections for bulk file transfers. (I needed to go Mac native for clean integration of QuickTime UI elements including frame extraction to thumbnails) Server: * Twisted for networking. PB and raw connections for clients, web server through twisted.web. Genshi for web templating, with Mochikit (might move to JQuery) for client-side JS/AJAX. Twisted for email transmission (email construction using normal Python email package). Small UI front-end module (Cocoa/PyObjC). The client accesses server-based objects through Twisted PB, which for some of the server objects also control session change lifetime (transactions). So at least in my case, having a stateful connection from the client worked out well, particularly since I needed to coordinate both database changes as well as filesystem changes through independent file uploads, each of which can fail independently. Right now a single server application contains all support for client connections as well as the web application, but I could fracture that (so the web server was independent for example) if needed. For the client, I package it using py2app, and put into an normal Mac installer, and distribute as a dmg. If it were a Windows client, I'd probably wrap with py2exe, then Inno Setup. The server's web server has a restricted URL that provides access to the DMG. The client has a Help menu item taking users to that URL. Clients are versioned and accepted/rejected by the server during initial connection - from the server side I can "retire" old client versions, at which point users get a message at signon with a button to take them to the download page for the latest DMG. So right now upgrades are executed manually by the user, and I can support older clients during any transition period. I may provide built-in support for automatically pulling down the new image and executing its installer, but haven't found it a hardship yet. I probably won't bother trying to automate smaller levels of updates. -- David From jon at turnthepage.org Sun Aug 12 13:12:04 2007 From: jon at turnthepage.org (Jon Rosebaugh) Date: Sun, 12 Aug 2007 12:12:04 -0500 Subject: Web based Reporting tool for Python References: <1186460956.945148.162610@k79g2000hse.googlegroups.com> <mailman.1722.1186522221.22759.python-list@python.org> <1186547726.383996.291360@d55g2000hsg.googlegroups.com> <2007080808575016807-jon@turnthepageorg> <1186891194.582444.222010@r34g2000hsd.googlegroups.com> <mailman.1871.1186916944.22759.python-list@python.org> Message-ID: <2007081212120450073-jon@turnthepageorg> On 2007-08-12 06:08:49 -0500, Steve Holden <steve at holdenweb.com> said: > Steve Holden wrote: >> Madhu Alagu wrote: >>> On Aug 8, 4:57 pm, Jon Rosebaugh <j... at turnthepage.org> wrote: >>>> On 2007-08-07 23:35:26 -0500, Madhu Alagu <alma... at gmail.com> said: >>>> >>>>> Thanking so much for all the informations and links.I would like to >>>>> use Mako Templates(www.makotemplates.org).Ilike to use simple and >>>>> python default module... >>>> Mako is an excellent template system, but you'll have a lot of work to >>>> do making it into a reporting system. >>> >>> >>> Any reporting template in python ? >>> >> >> Dabo (www.dabodev.com) is certainly heading that way, but I am not sure >> how far it's got yet. >> > Sorry, Dabo isn't web-based. You could look at Kid, Genshi, Cheetah, ... > > Or you could do a Google search for "python web template" and see what > comes up. There are many good contenders. Sure, but again, these aren't reporting engines; they're just template engines. And I don't think any of the web template engines have PDF output. From steve at holdenweb.com Thu Aug 23 17:29:02 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 23 Aug 2007 17:29:02 -0400 Subject: Putting #'s and variables together in 1 variable In-Reply-To: <eb79828c0708231309g7a7dd38fpb6dad836b8552cb0@mail.gmail.com> References: <eb79828c0708231309g7a7dd38fpb6dad836b8552cb0@mail.gmail.com> Message-ID: <faku72$8fs$2@sea.gmane.org> Lamonte Harris wrote: > File "Desktop\python\newsystem\init.py", line 51, in random_n > random_name = a+b+c+d+e+ 'temp.txt' > TypeError: unsupported operand type(s) for +: 'int' and 'str' > > import random > def random_name(): > a = random.randint(0,9) > b = random.randint(0,9) > c = random.randint(0,9) > d = random.randint(0,9) > e = random.randint(0,9) > random_name = a+b+c+d+e+ 'temp.txt ' > return random_name > print random_name > > How can i make it so that it adds the random numbers and the temp.txt to > random_name variable w/out causing any error? > random_name = "%d%d%d%d%dtemp.txt" % (a, b, c, d, e) or random_name = str(a)+str(b)+str(c)+str(d)+str(e)+"temp.txt" Unlike, for example, Perl, Python does not attempt many implicit conversions and instead forces you to say exactly what you mean. This has the advantage of clarity. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From iclark at mail.ewu.edu Mon Aug 13 19:22:00 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Mon, 13 Aug 2007 16:22:00 -0700 Subject: JPype - passing to Java main In-Reply-To: <1187040070.806416.75090@r34g2000hsd.googlegroups.com> References: <1187040070.806416.75090@r34g2000hsd.googlegroups.com> Message-ID: <f9qp2o$vkc$1@sea.gmane.org> unlikeablePorpoise at gmail.com wrote: > I am trying to get JPype to pass a String into a Java class main > function. Demonstration code below: > > =============JAVA============ > package com; > > public class JPypeTest { > > public static void main(String args[]) { > System.out.println(args[0]); > } > > public void printArgument(String arg) { > System.out.println(arg); > } > } > > ===========PYTHON=========== > from jpype import * > > startJVM("C:/Program Files/Java/jdk1.5.0_12/jre/bin/server/jvm.dll","- > Djava.class.path=C:/jpypetest/test/") > > com = JPackage("com"); > jp = com.JPypeTest(); > jp.printArgument('XXXX'); > #WANT TO CALL main("arg") HERE!!!! > shutdownJVM() > =============================== > > What I want is to be able to call main() with an argument from the > python file (using JPype) and have it echo > args[0]. I can get this to work for printArgument(), but not for > main(). > > Thanks, > Sarah > Try this: com.JPypeTest.main("arg") Ian From whamil1 at entergy.com Thu Aug 2 11:26:09 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Thu, 2 Aug 2007 10:26:09 -0500 Subject: Bug in Time module, or in my understanding? In-Reply-To: <f8qvua$pa5$1@sea.gmane.org> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CAF7@LITEXETSP001.etrsouth.corp.entergy.com> > From: Joshua J. Kugler > > I am getting results like these with the time module: > > >>> import time > >>> int(time.mktime(time.strptime('2007-03-11 02:00:00', '%Y-%m-%d %H:%M > %S'))) > 1173610800 > >>> int(time.mktime(time.strptime('2007-03-11 03:00:00', '%Y-%m-%d %H:%M > %S'))) > 1173610800 > >>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1173610800)) > '2007-03-11 03:00:00' > > I know it probably has something to do with daylight savings, but how can > I > get back out that which I put in? The times concerned are all standard > time, so how can I keep the time module from asserting its belief that I > want to convert to daylight savings? > > Incidentally, it only happens with times on 2007-03-11 from 02:00:00 to > 02:59:59, and not with time data from past years. > I get similar results, except with hours 01:00:00 and 02:00:00. I am in US Central time (GMT-6). >>> int(time.mktime(time.strptime('2007-03-11 00:00:00','%Y-%m-%d %H:%M:%S'))) 1173592800 >>> int(time.mktime(time.strptime('2007-03-11 01:00:00','%Y-%m-%d %H:%M:%S'))) 1173596400 >>> int(time.mktime(time.strptime('2007-03-11 02:00:00','%Y-%m-%d %H:%M:%S'))) 1173596400 >>> int(time.mktime(time.strptime('2007-03-11 03:00:00','%Y-%m-%d %H:%M:%S'))) 1173600000 -- -Bill Hamilton From hadronquark at googlemail.com Mon Aug 6 05:44:22 2007 From: hadronquark at googlemail.com (Hadron) Date: Mon, 06 Aug 2007 11:44:22 +0200 Subject: Emacs + python. Message-ID: <00tzrdm1zd.fsf@googlemail.com> Sorry to repeat, but I had to reinstall and lost all my news. I am looking for pointers on using emacs with python. I use emacs v 22.0.91 (Ubuntu snapshot). It comes with its own python mode. The problem is that the debugger just hangs when I start it. The interpreter runs fine. Any ideas? What versions of python.el or python-mode.el or ..... are you using and why? Many thanks for any pointers. From thorsten at thorstenkampe.de Sat Aug 11 14:58:03 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 11 Aug 2007 19:58:03 +0100 Subject: python 2.5 bug References: <1186825286.493878.80380@l70g2000hse.googlegroups.com> <5i5fktF3ml00gU1@mid.uni-berlin.de> <1186826980.346619.287670@r34g2000hsd.googlegroups.com> <46bdfb3f$0$5102$ba4acef3@news.orange.fr> Message-ID: <MPG.2128171394cc51d9989700@news.individual.de> * Laurent Pointal (Sat, 11 Aug 2007 20:09:03 +0200) > vedrandekovic at v-programs.com wrote: > > On 11 kol, 11:59, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote: > >> On Sat, 11 Aug 2007 02:41:26 -0700, vedrandekovic wrote: > >> > I was install Python 2.5 and uninstall Python 2.4 now I cannot run my > >> > scripts, only from idle > > IMHO Python 2.4 was registered for .py files, Python 2.5 take precedence > when installed, but when Python 2.4 has been removed, it remove .py files > association too (so break Python 2.5 association). > > * manually associate .py/.pyc/.pyo files to python.exe, .pyw files to > pythonw.exe. > > * or reinstall Python 2.5 so that it re-setup ad-hoc associations. Yeah. Did the Original Poster mention any details about his problem. Like - for instance - that he's using Windows? Thorsten From igorr at ifi.uio.no Wed Aug 29 10:15:45 2007 From: igorr at ifi.uio.no (Igor V. Rafienko) Date: 29 Aug 2007 16:15:45 +0200 Subject: non-blocking communication with imaplib References: <xjv8x84dm33.fsf@oinn.ifi.uio.no> <faud2f$5cn$1@lust.ihug.co.nz> Message-ID: <xjvk5rewhny.fsf@oinn.ifi.uio.no> [ Lawrence D'Oliveiro ] [ ... ] > According to the documentation > <http://docs.python.org/lib/imap4-objects.html>, you can override > the "read" and "readline" methods. How about replacing them with > routines that use select.select on the socket() object to implement > a timeout? Sounds like a plan. I'll try that. Thank you. ivr -- <+Kaptein-Dah> igorr: for f? parenteser <+Kaptein-Dah> igorr: parenteser virker som lubrication under iterasjon <+Kaptein-Dah> igorr: velkjent From thomas.lidebrandt at gmail.com Thu Aug 16 04:27:54 2007 From: thomas.lidebrandt at gmail.com (thomas.lidebrandt at gmail.com) Date: Thu, 16 Aug 2007 01:27:54 -0700 Subject: Changing button preferences after beeing pressed Message-ID: <1187252874.903820.79280@a39g2000hsc.googlegroups.com> Hello I'm using wxPython to consruct a GUI and want to change a button label and event handler to change after the button have been pressed. The only thing I can think of is a global variable that contrls the state of the program and constructs the button in accordance to the defined state. Is there a better solution to this problem? /Thomas From srikrishnamohan at gmail.com Thu Aug 2 03:51:10 2007 From: srikrishnamohan at gmail.com (km) Date: Thu, 2 Aug 2007 13:21:10 +0530 Subject: beginner in python In-Reply-To: <f8ro29$gl2$1@sea.gmane.org> References: <aa405c1f0708012127j471c9b2dl35b74cda9f595d09@mail.gmail.com> <f8ro29$gl2$1@sea.gmane.org> Message-ID: <f4cc03640708020051v7237e854ped7a0e9fc41e800a@mail.gmail.com> Hi Welcome to python ! there a a few suggestions in ur code which is a good practice to follow. In the snippet: > > for x in range(len(x_value)): > > x_co = float(x_value[x])-float(x_value[x+1]) > > y_co = float(y_value[x])-float(y_value[x+1]) > > z_co = float(z_value[x])-float(z_value[x+1]) > > data = math.sqrt(x_co)*(x_co)+(y_co)*(y_co)+(z_co)*(z_co) > > print data U suddenly change the indent from four spaces which u followed in previous for loop. pls maintain consistency in indent. Standard convention is to use four spaces for indent. Another problem is that u have not closed the filehandle in the program! HTH KM -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070802/f22b2d54/attachment.html> From bdesth.quelquechose at free.quelquepart.fr Mon Aug 20 13:11:58 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 20 Aug 2007 19:11:58 +0200 Subject: advice about `correct' use of decorator In-Reply-To: <mailman.2085.1187302439.22759.python-list@python.org> References: <mailman.2074.1187294411.22759.python-list@python.org> <2vydnTio1a9IWlnbnZ2dnUVZ_jKdnZ2d@comcast.com> <mailman.2085.1187302439.22759.python-list@python.org> Message-ID: <46cca037$0$422$426a74cc@news.free.fr> Gerardo Herzig a ?crit : > Steven Bethard wrote: > >> Gerardo Herzig wrote: >> >> >>> Hi all. I guess i have a conceptual question: >>> Im planing using a quite simple decorator to be used as a conditional >>> for the execution of the function. (snip) >>> >>> Something in my mind tells me that this is not the pythonic way...But >>> i like the idea, so please tell me that im in the right way :) >>> >> >> Django does it almost exactly this way: (snip) > > Great! So from now on, my idea is labeled as `djangothic' :) > Thanks a lot! Which doesn't necessarily imply it's pythonic !-) From martin at v.loewis.de Sun Aug 12 18:43:01 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 13 Aug 2007 00:43:01 +0200 Subject: Python not freeing memory (?) In-Reply-To: <mailman.1882.1186951800.22759.python-list@python.org> References: <mailman.1882.1186951800.22759.python-list@python.org> Message-ID: <46bf8cf5$0$29938$9b622d9e@news.freenet.de> > Is there *any* way of getting around this? Sure: Determine the bug, and fix it. A prerequisite is that you have the source code of all extension modules which you are using, but that seems to be the case. If you want others to help you in finding the bug, you need to provide more detail, e.g. a specific piece of code that reproducibly wastes memory. If you want to study how Python objects are allocated and released, you need to create a debug build of Python (and all extension modules), and start, e.g., with looking at the value of sys.gettotalrefcount() over time. HTH, Martin From martin at v.loewis.de Wed Aug 22 18:45:38 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 23 Aug 2007 00:45:38 +0200 Subject: MsiLib In-Reply-To: <mailman.141.1187816227.32294.python-list@python.org> References: <mailman.141.1187816227.32294.python-list@python.org> Message-ID: <46ccbc92$0$24474$9b622d9e@news.freenet.de> Charlie schrieb: > This doesn't seem to be my day for this. When I add view.Execute() to > the script, it gives me an error of Execute() takes exactly 1 argument > (0 given). I can't seem to find anything on the Microsoft page that > concerns the execute function that states what exactly needs to be > included as an argument, especially for a select statement. Thanks for > the help. It's ok to pass None as the parameter to Execute; this means that a null handle gets passed as hRecord to MsiViewExecute. Regards, Martin From pavlovevidence at gmail.com Fri Aug 17 20:02:31 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 17 Aug 2007 17:02:31 -0700 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: <1187316113.424465.34650@19g2000hsx.googlegroups.com> References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> <1187314114.873306.187500@e9g2000prf.googlegroups.com> <1187316113.424465.34650@19g2000hsx.googlegroups.com> Message-ID: <1187395351.199508.111720@m37g2000prh.googlegroups.com> On Aug 16, 10:01 pm, Paul McGuire <pt... at austin.rr.com> wrote: > On Aug 16, 8:28 pm, Jonathan Gardner > > > > <jgardner.jonathangardner.... at gmail.com> wrote: > > On Aug 16, 3:35 pm, beginner <zyzhu2... at gmail.com> wrote: > > > > In perl it is just one line: $a=$b->{"A"} ||={}. > > > a = b.setdefault('A', {}) > > > This combines all two actions together: > > - Sets b['A'] to {} if it is not already defined > > - Assigns b['A'] to a > > > More info on dict methods here: > > >http://docs.python.org/lib/typesmapping.html > > No, this has already been proposed and discarded. The OP does NOT > want this, because it always generates an empty {} whether it is > needed or not. Not really a big hardship, but if the default value > were some expensive-to-construct container class, then you would be > creating one every time you wanted to reference a value, on the chance > that the key did not exist. > > Carl Banks' post using defaultdict is the correct solution. The > raison d'etre for defaultdict, and the reason that it is the solution > to the OP's question, is that instead of creating a just-in-case > default value every time, the defaultdict itself is constructed with a > factory method of some kind (in practice, it appears that this factory > method is usually the list or dict class constructor). If a reference > to the defaultdict gives a not-yet-existing key, then the factory > method is called to construct the new value, that value is stored in > the dict with the given key, and the value is passed back to the > caller. No instances are created unless they are truly required for > initializing an entry for a never-before-seen key. When I made my response, it occurred to me that Python could be improved (maybe) if one could overload dict.get() to use a factory, like so: b = {} a = b.get(k,factory=dict) a['A'] = 1 That's a slight improvement (maybe) over defaultdict since it would still allow the same dict to have the membership check in other places. I'm not so sure overloading get to let it modify the dict is a good idea, though. Actually, it'd probably be fairly uncontroversial to add a factory keyword to dict.setdefault(). At least insofar as setdefault is uncontroversial. Carl Banks From gagsl-py2 at yahoo.com.ar Wed Aug 22 23:34:42 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 23 Aug 2007 00:34:42 -0300 Subject: Design philosophy of HTTPServer and BaseHTTPRequestHandler References: <1187776216.269456.310230@q4g2000prc.googlegroups.com> <1187790329.575480.14070@i38g2000prf.googlegroups.com> <1187814421.263942.202220@x35g2000prf.googlegroups.com> Message-ID: <op.txhtj4ikx6zn5v@gabriel2.softlabbsas.com.ar> En Wed, 22 Aug 2007 17:27:01 -0300, tzuchien.chiu <tzuchien.chiu at gmail.com> escribi?: > On 22 ago, 14:45, Gabriel Genellina <gagsl-... at yahoo.com.ar> wrote: >> The server is permanent; request handler instances are created and >> destroyed as HTTP requests arrive and are processed. >> You should store any permanent info in the server; your >> "BaseHTTPRequestHandler-derived class" can reference the server using >> its "server" attribute. > > I found the server attribute in the source code (/Lib), but it is not > documented in Python Library Reference 18.19. > > I wonder that if I can rely on this "undocumented" attribute? It is OK to use it, it's documented under the base class, SocketServer.RequestHandler -- Gabriel Genellina From kyosohma at gmail.com Mon Aug 6 09:56:42 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 06 Aug 2007 06:56:42 -0700 Subject: webbrowser.open question force Firefox In-Reply-To: <mailman.1665.1186396929.22759.python-list@python.org> References: <e75321bd0708060259p32249f96sa327ec4b505cc981@mail.gmail.com> <mailman.1665.1186396929.22759.python-list@python.org> Message-ID: <1186408602.487621.204400@i38g2000prf.googlegroups.com> On Aug 6, 5:42 am, Thomas Jollans <tho... at jollans.com> wrote: > On Monday 06 August 2007, dimitri pater wrote: > > > Hi, > > I have a question regarding the use of webbrowser.open. > > On a windows XP machine, MS-IE is set as the default browser so when I do: > > webbrowser.open('http://localhost:8080') IE starts with this address. > > But in stead of launching IE, I want to launch Firefox *without* setting > > Firefox as the default browser globally on this machine. > > > Any hints, ideas? Your help is most appreciated. > > take an educated guess where to find firefox, check if it's there, and do > something like > os.spawnl(os.P_NOWAIT, where_firefox_is, "http://localhost:8080") > > -- > Regards, Thomas Jollans > GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu > Hacker key <http://hackerkey.com/>: > v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6 > > signature.asc > 1KDownload Shouldn't you be using the subprocess module instead as it is replacing the os.spawn* functionality from 2.4 on? See http://docs.python.org/dev/lib/module-subprocess.html If so, then the code would be: subprocess.Popen(r'where_firefox_is http://localhost:8080') Mike From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Aug 10 18:03:41 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 11 Aug 2007 00:03:41 +0200 Subject: The Future of Python Threading References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <5i329uF3muir4U1@mid.individual.net> <slrnfbou9k.vkb.nick@irishsea.home.craig-wood.com> Message-ID: <5i45luF3mvdesU1@mid.individual.net> Nick Craig-Wood wrote: [GIL] > That is certainly true. However the point being is that running > on 2 CPUs at once at 95% efficiency is much better than running on > only 1 at 99%... How do you define this percent efficiency? >>> The truth is that the future (and present reality) of almost >>> every form of computing is multi-core, >> >> Is it? 8) > > Intel, AMD and Sun would have you believe that yes! Strange, in my programs, I don't need any "real" concurrency (they are network servers and scripts). Or do you mean "the future of computing hardware is multi-core"? That indeed may be true. >> The question is: If it really was, how much of useful >> performance gain would you get? > > The linux kernel has been through these growing pains already... > SMP support was initially done with the Big Kernel Lock (BKL) > which is exactly equivalent to the GIL. So, how much performance gain would you get? Again, managing fine-grained locking can be much more work than one simple lock. > The linux kernel has moved onwards to finer and finer grained > locking. How do you compare a byte code interpreter to a monolithic OS kernel? > I'd like to see a python build as it is at the moment and a > python-mt build which has the GIL broken down into a lock on each > object. python-mt would certainly be slower for non threaded > tasks, but it would certainly be quicker for threaded tasks on > multiple CPU computers. >From where do you take this certainty? For example, if the program in question involves mostly IO access, there will be virtually no gain. Multithreading is not Performance. > The user could then choose which python to run. > > This would of course make C extensions more complicated... Also, C extensions can release the GIL for long-running computations. Regards, Bj?rn -- BOFH excuse #391: We already sent around a notice about that. From ca.allen at gmail.com Fri Aug 3 15:05:29 2007 From: ca.allen at gmail.com (Chris Allen) Date: Fri, 03 Aug 2007 12:05:29 -0700 Subject: Global package variable, is it possible? In-Reply-To: <mailman.1581.1186165038.22759.python-list@python.org> References: <1186160415.065108.139160@e9g2000prf.googlegroups.com> <46b36b31$0$10622$4fafbaef@reader2.news.tin.it> <mailman.1581.1186165038.22759.python-list@python.org> Message-ID: <1186167929.165336.305380@d30g2000prg.googlegroups.com> On Aug 3, 11:16 am, Carsten Haese <cars... at uniqsys.com> wrote: > On Fri, 2007-08-03 at 17:51 +0000, Fabio Z Tessitore wrote: > > Heve you tried to do something like: > > > # module configure.py > > value1 = 10 > > value2 = 20 > > ... > > > # other module > > from configure import * > > > # now I'm able to use value1 value2 etc. > > var = value1 * value2 > > Right idea, wrong execution. Note that the OP said "I'd like to be able > to reload the config file dynamically and have all my modules > automatically receive the new config." > > "from configure import *" will import the settings into the current > namespace, and subsequent changes in the original namespace will, in > general, not have any effect in the current namespace. > > This should do the trick: > > # module configure.py > value1 = 10 > value2 = 20 > ... > > # other module > import configure > > var = configure.value1 * configure.value2 > > HTH, > > -- > Carsten Haesehttp://informixdb.sourceforge.net It does help thanks. Okay now after reading your post I really need to do some experimenting. I was under the impression when I wrote my last post that changing an attribute in one modules instance in __init__.py would not effect other modules. Sorry, I'm relatively new to python, and things like this are still sometimes "gotchas!" for me. From tuomas.vesterinen at pp.inet.fi Mon Aug 27 16:42:15 2007 From: tuomas.vesterinen at pp.inet.fi (Tuomas) Date: Mon, 27 Aug 2007 20:42:15 GMT Subject: sorting a list of lists In-Reply-To: <1188233798.684136.263640@22g2000hsm.googlegroups.com> References: <1188233798.684136.263640@22g2000hsm.googlegroups.com> Message-ID: <HGGAi.336$mg7.154@read3.inet.fi> >>> records = [['dog',1,2], ['chair',2,1], ['cat',1,3], ['horse',3,4], ... ['table',3,2], ['window',3,5]] >>> sorted(records, key = lambda x: (x[1], x[2])) [['dog', 1, 2], ['cat', 1, 3], ['chair', 2, 1], ['table', 3, 2], ['horse', 3, 4], ['window', 3, 5]] nicksavill at googlemail.com wrote: > Hi, > > i would like to sort a list of lists. The list is first sorted on the > second item in the sub-lists (which I can do), then on the third item > (which I can't). > > eg. records = [['dog',1,2], ['chair',2,1], ['cat',1,3], ['horse',3,4], > ['table',3,2], ['window',3,5]] > > I want sorted to [['dog',1,2], ['cat',1,3], ['chair',2,1], ['table', > 3,2], ['horse',3,4], ['window',3,5]] > > To sort on the second item in the sub-lists I do the following > > pass1 = itemgetter(1) > sorted(records, key=pass1) > > How can I then sort on the third item in the sub-lists whilst keeping > the order on the second item? > > Nick > From wgwigw at gmail.com Wed Aug 1 03:20:04 2007 From: wgwigw at gmail.com (momobear) Date: Wed, 01 Aug 2007 07:20:04 -0000 Subject: Any way to monitor windows network connection? In-Reply-To: <mailman.1416.1185942217.22759.python-list@python.org> References: <1185939997.135825.310080@z24g2000prh.googlegroups.com> <mailman.1416.1185942217.22759.python-list@python.org> Message-ID: <1185952804.420205.98080@e16g2000pri.googlegroups.com> On Aug 1, 12:22 pm, Jay Loden <pyt... at jayloden.com> wrote: > momobear wrote: > > hi, Is there any way to show me detailed listings of all TCP and UDP > > endpoints in my microsoft windows XP in python way? > > thanks. > > Not sure if it's exactly what you're looking for, but this might be of use as a starting point at least:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/392572 yes, I get it, iphelp api could do that for me. thanks for help. From boazin at gmail.com Fri Aug 10 12:07:46 2007 From: boazin at gmail.com (boazin at gmail.com) Date: Fri, 10 Aug 2007 16:07:46 -0000 Subject: building a rather simple server in python Message-ID: <1186762066.665768.215080@i38g2000prf.googlegroups.com> Hi all, I was trying to build a rather simple server (with a twist) using asyncore and got myself complicated. Well, here's the deal: My server will handle multiple connections, some require reply, and some not (they will disconnect by themselves) all the clients want to to deliver binary data to a socket we'll call P socket. this socket is a device that hopefully always wating for new data (It's actually a hardware). The replies will come on a different socket, we'll call socket T. When the server receives a reply (again binary data) it will send it to all the "wating for reply" clients (the client will determine if it is for him or not). My problems arise when I need to write to socket P and then somehow, somewhen, read the responses from socket T. Hopefully, the description is clear enough I tried to use asyncore and got tangled up with the reactiveness of it. Any ideas? how to use it with asyncore? other implementations? From ianare at gmail.com Mon Aug 13 02:30:17 2007 From: ianare at gmail.com (=?iso-8859-1?B?aWFuYXLp?=) Date: Mon, 13 Aug 2007 06:30:17 -0000 Subject: Colored text In-Reply-To: <1186984232.440419.207990@l22g2000prc.googlegroups.com> References: <1186970751.435970.189900@q3g2000prf.googlegroups.com> <1186981264.235988.40260@k79g2000hse.googlegroups.com> <1186984232.440419.207990@l22g2000prc.googlegroups.com> Message-ID: <1186986617.423025.28600@57g2000hsv.googlegroups.com> On Aug 13, 1:50 am, Rohan <vodela.... at gmail.com> wrote: > On Aug 12, 10:01 pm, ianar? <ian... at gmail.com> wrote: > > > On Aug 12, 10:05 pm, Rohan <vodela.... at gmail.com> wrote: > > > > Hello, > > > Can some one tell me how do I get colored text. Say when I want to > > > write something in a text file , how do I get it colored. > > > Plain text files don't have color. You could output in html ... > > Oh ok what about a csv file, I know its also a text file but I want > the color to be say blue in an excel sheet. CSV is also pretty much plain text. No support for formatting. You will need to write xls files. Personaly, I avoid proprietary file formats like the plague, but this may be what you're looking for: http://www.answermysearches.com/index.php/generate-an-excel-formatted-file-right-in-python/122/ From laurent.pointal at limsi.fr Fri Aug 3 04:00:13 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 03 Aug 2007 10:00:13 +0200 Subject: (no) fast boolean evaluation ? In-Reply-To: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> Message-ID: <f8unac$e3f$1@news2.u-psud.fr> Stef Mientki a ?crit : > hello, > > I discovered that boolean evaluation in Python is done "fast" > (as soon as the condition is ok, the rest of the expression is ignored). > > Is this standard behavior or is there a compiler switch to turn it on/off ? As it was replied, its standard behavior and cannot be modified. IMHO, if you really need all your expressions to be evaluated, the clean (most readable) way may be: a = <first_expression which must be evaluated> b = <second_expression(x,y,z) which must be evaluated> if a and b : ... A+ Laurent. From gerdusvanzyl at gmail.com Tue Aug 14 12:24:39 2007 From: gerdusvanzyl at gmail.com (Gerdus van Zyl) Date: Tue, 14 Aug 2007 16:24:39 -0000 Subject: pure python gaussian blur Message-ID: <1187108679.401416.224060@19g2000hsx.googlegroups.com> Does anyone have a relatively fast gaussian blur implemented in pure python? Below is my attempt but it takes 2.9 seconds for a 320x240 image. Image comes from byte string: self.array = array.array('B',srcstring). Would some sort of matrix multiplication be faster? I don't have experience in that. I don't want to use PIL or http://filters.sourceforge.net/ to avoid the 300kb dll just for a simple blur. def blur(self): # Convolution Kernels blurFilter = [[0,1,2,1,0], [1,2,4,2,1], [2,4,8,4,2], [1,2,4,2,1], [0,1,2,1,0]] blurDiv = 48 blurFilterSize = len(blurFilter) #5 blurFilterSize2 = blurFilterSize * blurFilterSize pixels = self.array stride = self.width * 4 w = self.width h = self.height red = 0 green = 0 blue = 0 sx = 0 ex = 0 sy = 0 ey = 0 ss = 0 f1 = 0 f2 = 0 ff = 0 idx = 0 samplesize = 0 offset1 = blurFilterSize/2 offset2 = blurFilterSize/2+2 clr = array.array('B',[255,255,255,255]) px = array.array('B',[255,255,255,255]) for x in xrange(0,w): #w sx = x - offset1 ex = x + offset2 if sx < 0: sx = x if ex > w: ex = w for y in xrange(0,h): sy = y - offset1 ey = y + offset2 if sy < 0: sy = y if ey > h: ey = h samplesize = (ex-sx) * (ey-sy) if samplesize > 0: ss = blurFilterSize2 / samplesize if ss > blurFilterSize - 2: ss = blurFilterSize - 2 else: ss = 0 idx = 0 ffx = 0 red = 0 green = 0 blue = 0 for vx in xrange(sx,ex): for vy in xrange(sy,ey): offset = vy * stride + vx * 4 px = pixels[offset:offset +4] f1 = idx / 5 f2 = (idx - f1) % 5 f1 += ss if f1 > 4: f1 = 4 ff = blurFilter[f1] [f2] #ff = 1 ffx += ff red += px[0] * ff green += px[1] * ff blue += px[2] * ff idx += 1 if samplesize > 0: red = red / ffx green = green / ffx blue = blue / ffx if red > 255: red = 255 if green > 255: green = 255 if blue > 255: blue = 255 clr[0] = red clr[1] = green clr[2] = blue self.setPixel(x, y, clr) From rschroev_nospam_ml at fastmail.fm Sat Aug 11 14:04:07 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 11 Aug 2007 18:04:07 GMT Subject: Augmented assignment (was Re: Something in the function tutorial confused me.) In-Reply-To: <Xns99896DB601AF1OKB@199.45.49.11> References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <mailman.1751.1186588156.22759.python-list@python.org> <m3hvi.37606$G23.6240@newsreading01.news.tds.net> <f9kdpq$drp$1@panix3.panix.com> <Xns99896DB601AF1OKB@199.45.49.11> Message-ID: <rSmvi.47406$XJ3.819294@phobos.telenet-ops.be> OKB (not okblacke) schreef: > Aahz wrote: > >>>>>>> tup=([],) >>>>>>> tup[0] += ['zap'] >>>> Traceback (most recent call last): >>>> File "<stdin>", line 1, in <module> >>>> TypeError: 'tuple' object does not support item assignment > <snip> >> Obviously, you can easily work around it: >> >>>>> t = ([],) >>>>> l = t[0] >>>>> l += ['foo'] >>>>> t >> (['foo'],) > > This is quite shocking to me, although after staring at the > documentation for a while I guess I understand it. But it seems to me > that the documentation is somewhat misleading on this point, where it > says: > > "An augmented assignment evaluates the target (which, unlike normal > assignment statements, cannot be an unpacking) and the expression list, > performs the binary operation specific to the type of assignment on the > two operands, and assigns the result to the original target." > > This sentence is phrased as though it is the whole story, but it > isn't, because the operation might not in fact wind up being an > assignment. The way I understand this now, the assignment really always is an assignment. 1. - For immutable objects, the 'binary operation specific to the type of assignment on the two operands' doesn't modify any object, but only returns a new object which is the result of the operation. - For mutable objects that support the inplace-version of the operator, the operator modifies the object and then returns it. 3. In both cases that result is assigned to the target. In the second case the object was already modified so the assignment doesn't accomplish very much, but it still happens. That explains why "tup[0] += ['zap']" both has an effect (tup[0] now contains 'zap') and raises an exception: tup[0] is modified because it is a list and lists support inplace addition, but the assignment fails because tuples don't support item assignment. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From oliver at ootbc.com Sat Aug 18 00:25:12 2007 From: oliver at ootbc.com (Oliver Nelson) Date: Fri, 17 Aug 2007 21:25:12 -0700 Subject: Canceling events on COM objects Message-ID: <Hwuxi.5287$924.707@newssvr23.news.prodigy.net> I have MapPoint working in Python, and I'm trying to cancel events on the map, but I can't seem to make that happen. I'm responding to the events successfully in my panel object. My code is like this: global MapPointMod MapPointMod = win32com.client.gencache.EnsureModule("{51C0A9CA-F7B7-4F5A-96F4-43927C6FA50F}", 0, 1, 0) class MyPanel(wx.Panel): def __init__(self, *args, **kwds): # begin wxGlade: MyPanel.__init__ kwds["style"] = wx.TAB_TRAVERSAL wx.Panel.__init__(self, *args, **kwds) self.frame = args[0] MyMap = MakeActiveXClass(MapPointMod.MappointControl, eventObj=self) self.window_1 = MyMap(self, -1) self.window_1.OpenMap("C:\\TEMP\\GPS_ON.ptt") ... ... def OnBeforeClick(self, Button, Shift, X, Y, Cancel): print "tada" My event fires just fine, but I can't seem to figure out how to cancel the event so that mappoint doesn't do its stuff with it...I've tried setting Cancel based on the mappoint specs, but it doesn't seem to get sent back anywhere... Any ideas please? Thanx, OLIVER From iapain at gmail.com Fri Aug 31 12:43:45 2007 From: iapain at gmail.com (iapain) Date: Fri, 31 Aug 2007 16:43:45 -0000 Subject: escaping only double quotes In-Reply-To: <1188575379.041219.177910@19g2000hsx.googlegroups.com> References: <1188575379.041219.177910@19g2000hsx.googlegroups.com> Message-ID: <1188578625.662799.57020@i13g2000prf.googlegroups.com> You could write a simple escape function. def escape(html): "Return the given TEXT with ampersands, quotes and carets encoded." return html.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", ''') From bborcic at gmail.com Wed Aug 15 10:01:57 2007 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 15 Aug 2007 16:01:57 +0200 Subject: make images with python In-Reply-To: <1i2vg8p.1d8t42r1jzvm9iN%raims@dot.com> References: <1187147338.400947.181010@x40g2000prg.googlegroups.com> <1i2vg8p.1d8t42r1jzvm9iN%raims@dot.com> Message-ID: <f9v12c$rb8$1@sea.gmane.org> Lawrence Oluyede wrote: > stefano <ssalvatori at gmail.com> wrote: >> I need make some images using python but i'm lost :P > > <http://www.pythonware.com/products/pil/> > If you want to do antialiased drawings into images, you might rather want to look for pil at http://effbot.org/downloads/ and grab PIL together with the aggdraw extension (while "core" PIL includes some drawing primitives, last time I tried they weren't antialiased). Best, BB From horpner at yahoo.com Wed Aug 15 11:47:55 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 15 Aug 2007 15:47:55 GMT Subject: Opinions about this new Python book? References: <mailman.1957.1187093157.22759.python-list@python.org> <1187096231.194685.86030@m37g2000prh.googlegroups.com> <20070814154913.D8C3C1E400A@bag.python.org> <8a6b8e350708141020q495b22der4c362ee3df618d82@mail.gmail.com> <mailman.1979.1187113641.22759.python-list@python.org> <1187117012.088495.247890@q4g2000prc.googlegroups.com> <1187191950.037749.8050@z24g2000prh.googlegroups.com> Message-ID: <slrnfc6884.22k.horpner@FIAD06.norwich.edu> On 2007-08-15, kyosohma at gmail.com <kyosohma at gmail.com> wrote: > For some reason, the author makes the claim that the term > "Predicate" is "bandied about quite a bit in the literature" of > Python. I have 17 or so Python books and I don't think I've > ever seen this used in conjunction with Python...or in any of > the docs I've skimmed. What the!? The document searching facility reveals that the term is bandied about in five places in the standard documentation. These uses seem approriate and uncontroversial to me. These document functions accepting predicates as aruments: 6.5.1 Itertools functions 6.5.3 Recipes 11.47 Creating a new Distutils command 26.10.1 Types and members The following provides a few predicate functions (weird! I'd have never thought to look there for, e.g., ismodule): 6.7 operator -- Standard operators as functions -- Neil Cerutti From oliver at ootbc.com Thu Aug 16 17:52:36 2007 From: oliver at ootbc.com (Oliver Nelson) Date: Thu, 16 Aug 2007 14:52:36 -0700 Subject: Events in Com Object for Python Message-ID: <DG3xi.1835$4w7.1312@newssvr22.news.prodigy.net> I have MapPoint working in Python, and I'm trying to cancel events on the map, but I can't seem to make that happen. I'm responding to the events successfully in my panel object. My code is like this: global MapPointMod MapPointMod = win32com.client.gencache.EnsureModule("{51C0A9CA-F7B7-4F5A-96F4-43927C6FA50F}", 0, 1, 0) class MyPanel(wx.Panel): def __init__(self, *args, **kwds): # begin wxGlade: MyPanel.__init__ kwds["style"] = wx.TAB_TRAVERSAL wx.Panel.__init__(self, *args, **kwds) self.frame = args[0] MyMap = MakeActiveXClass(MapPointMod.MappointControl, eventObj=self) self.window_1 = MyMap(self, -1) self.window_1.OpenMap("C:\\TEMP\\GPS_ON.ptt") ... ... def OnBeforeClick(self, Button, Shift, X, Y, Cancel): print "tada" My event fires just fine, but I can't seem to figure out how to cancel the event so that mappoint doesn't do its stuff with it...I've tried setting Cancel based on the mappoint specs, but it doesn't seem to get sent back anywhere... Any ideas please? Thanx, OLIVER From hniksic at xemacs.org Wed Aug 22 00:05:03 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 22 Aug 2007 06:05:03 +0200 Subject: File Read Cache - How to purge? References: <1187669203.698637.81990@i38g2000prf.googlegroups.com> <87veb9xb7y.fsf@mulj.homelinux.net> <slrnfcm1hv.4r1.nick@irishsea.home.craig-wood.com> Message-ID: <87ir781afk.fsf@mulj.homelinux.net> Nick Craig-Wood <nick at craig-wood.com> writes: > If you are running linux > 2.6.18 then you can use > /proc/sys/vm/drop_caches for exactly that purpose. > > http://www.linuxinsight.com/proc_sys_vm_drop_caches.html That URL claims that you need to run "sync" before dropping the cache, and so do other resources. I wonder if that means that dropping the cache is unsafe on a running system. From evan at yelp.com Fri Aug 24 17:56:31 2007 From: evan at yelp.com (Evan Klitzke) Date: Fri, 24 Aug 2007 14:56:31 -0700 Subject: Co-developers wanted: document markup language In-Reply-To: <87odgyyx9u.fsf@wilson.homeunix.com> References: <87odgyyx9u.fsf@wilson.homeunix.com> Message-ID: <cfb58d850708241456o78891487s3bd032d585da0d89@mail.gmail.com> On 8/23/07, Torsten Bronger <bronger at physik.rwth-aachen.de> wrote: > Some LaTeX users in Aachen thought about a general-use markup > language this spring. I wrote some code and a rough project > description, however, we could need some help. Torsten, I have another question about your markup language. Are there any plans on adding provisions for layout and positioning? The difficulty of learning advanced layout has been one of my major frustrations with LaTeX (I'm referring to LaTeX's weird box system, I'm not sure exactly what the proper terminology for it is). -- Evan Klitzke <evan at yelp.com> From danb_83 at yahoo.com Thu Aug 9 19:52:05 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Thu, 09 Aug 2007 16:52:05 -0700 Subject: beginner whitespace question In-Reply-To: <1186703261.136506.208660@x35g2000prf.googlegroups.com> References: <1186703261.136506.208660@x35g2000prf.googlegroups.com> Message-ID: <1186703525.591462.122140@m37g2000prh.googlegroups.com> On Aug 9, 6:47 pm, eggie5 <egg... at gmail.com> wrote: > I keep getting an error for line 7, what's wrong with this? > > from django.db import models > > class Poll(models.Model): > question = models.CharField(max_length=200) > pub_date = models.DateTimeField('date published') > > def __unicode__(self): > return self.question > The "def" statements have to be at the same indentation level as what's before it. From bronger at physik.rwth-aachen.de Thu Aug 23 18:16:21 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 24 Aug 2007 00:16:21 +0200 Subject: Co-developers wanted: document markup language References: <87odgyyx9u.fsf@wilson.homeunix.com> <fakrtb$2ts$1@panix3.panix.com> Message-ID: <87tzqpew22.fsf@wilson.homeunix.com> Hall?chen! Aahz writes: > In article <87odgyyx9u.fsf at wilson.homeunix.com>, > Torsten Bronger <bronger at physik.rwth-aachen.de> wrote: > >> Some LaTeX users in Aachen thought about a general-use markup >> language this spring. I wrote some code and a rough project >> description, however, we could need some help. > > http://docutils.sourceforge.net/ The provisional project page already points to http://docutils.sourceforge.net/rst.html which is sufficient I think. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From ricaraoz at gmail.com Sun Aug 5 14:33:35 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 05 Aug 2007 15:33:35 -0300 Subject: Formatting Results so that They Can be Nicely Imported into a Spreadsheet. In-Reply-To: <cec.159aaa5b.33e6c987@aol.com> References: <cec.159aaa5b.33e6c987@aol.com> Message-ID: <46B617FF.40908@bigfoot.com> Mensanator at aol.com wrote: > In a message dated 8/4/2007 11:50:05 PM Central Daylight Time, > ricaraoz at gmail.com writes: > > mensanator at aol.com wrote: > > On Aug 4, 6:35?pm, SMERSH009 <SMERSH0... at gmail.com> wrote: > >> Hi All. > >> Let's say I have some badly formatted text called doc: > >> > >> doc= > >> """ > >> friendid > >> Female > >> > >> 23 years old > >> > >> Los Gatos > >> > >> United States > >> friendid > >> Male > >> > >> 24 years old > >> > >> San Francisco, California > >> > >> United States > >> """ > >> > >> How would I get these results to be displayed in a format similar to: > >> friendid;Female;23 years old;Los Gatos;United States > >> friendid;Male; 24 years old;San Francisco, California;United States > >> > >> The latter is a lot easier to organize and can be quickly imported > >> into Excel's column format. > >> > >> Thanks Much, > >> Sam > > > > d = doc.split('\n') > > > > f = [i.split() for i in d if i] > > > > g = [' '.join(i) for i in f] > > > > rec = [] > > temprec = [] > > for i in g: > > if i: > > if i == 'friendid': > > rec.append(temprec) > > temprec = [i] > > else: > > temprec.append(i) > > rec.append(temprec) > > > > output = [';'.join(i) for i in rec if i] > > > > for i in output: print i > > > > ## friendid;Female;23 years old;Los Gatos;United States > > ## friendid;Male;24 years old;San Francisco, California;United > > States > > > > Also : > > docList = [ i.strip() for i in doc.split('\n') if i.strip()] > > lines = [i for i in xrange(len(docList)) if docList[i] == > 'friendid']+[len(docList)] > > docOut = '' > for k in [docList[lines[j]:lines[j+1]] for j in xrange(len(lines)-1)]: > docOut += '\n' + ';'.join(k) > > docOut = docOut[1:] # Get rid of initial '\n' > > Aren't you making an unwarranted assumption here? > That doc ALWAYS starts with EXACTLY one blank line? I guess you are referring to : docList = [ i.strip() for i in doc.split('\n') if i.strip()] Actually no, "doc.split('\n')" will split it a list member per line, whether there are blank lines or not. Then "i.strip()" will take care of redundant space, and "if i.strip()" will take care of blank lines. Try it in your shell, play with "doc" and you'll see (I did try it without the first blank line, and with a lot of blank lines and it's ok). > > That's why I didn't use a list comprehension in that > one section, to cover the possibility of any number > (including none) of blank lines. It works, didn't make a thorough testing but the cases you suggest were tested. > > By blindly coding [1:] you run the risk of data loss, > and that's a poor example for the OP. It is not "blindly". I guarantee the first byte will ALLWAYS be a '\n', that's because I'm putting it there with "docOut += '\n' + ';'.join(k)" (check the '\n' added at the beginning of each cycle), and I need to strip the beginning '\n' which is not necessary. Cheers Ricardo From laurent.pointal at limsi.fr Fri Aug 17 07:44:16 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 17 Aug 2007 13:44:16 +0200 Subject: clarification In-Reply-To: <fa41k8$10n$1@news2.u-psud.fr> References: <aa405c1f0708162332t7b6dbdd6o2cc0f512dc821d7b@mail.gmail.com> <mailman.2107.1187350363.22759.python-list@python.org> <fa41k8$10n$1@news2.u-psud.fr> Message-ID: <fa41mg$10n$2@news2.u-psud.fr> Laurent Pointal a ?crit : [cleaning] fh = open('sheet1') for line in fh: From steve at holdenweb.com Thu Aug 9 08:33:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 09 Aug 2007 08:33:43 -0400 Subject: Help with Dictionaries and Classes requested please. In-Reply-To: <46bb00d4$0$11943$7b0f0fd3@mistral.news.newnet.co.uk> References: <46bacae3$0$89254$7b0f0fd3@mistral.news.newnet.co.uk> <46bacf1b$0$54289$7b0f0fd3@mistral.news.newnet.co.uk> <46baf183$0$433$426a74cc@news.free.fr> <46baf384$0$11943$7b0f0fd3@mistral.news.newnet.co.uk> <46bb00d4$0$11943$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <f9f1j4$esj$1@sea.gmane.org> special_dragonfly wrote: > "special_dragonfly" <Dominic at PLEASEASK.co.uk> wrote in message > news:46baf384$0$11943$7b0f0fd3 at mistral.news.newnet.co.uk... >> "Bruno Desthuilliers" <bruno.42.desthuilliers at wtf.websiteburo.oops.com> >> wrote in message news:46baf183$0$433$426a74cc at news.free.fr... >>> special_dragonfly a ?crit : >>> (snip) >>>> I've managed to solve the problem, I really was just being a dunce. >>>> Here's how incase anyone is wondering: >>>> >>>> class MyClass: >>>> def __init__(self): >>>> name="" >>>> dict={} >>>> dict[0]=[] >>>> dict[0].append(MyClass()) >>>> dict[0][0].name="Hello" >>>> print dict[0][0].name >>>> >>>> I'm sorry if I've wasted anyones time, although if there's a better way >>>> of doing the above I'd still be interested to know. >>> # unless you need pre 2.3.x compat, better to use newstyle classes >>> class MyClass(object): >>> # use the initializer to initialize your instance >>> def __init__(self, name=''): >>> # the use of 'self' is mandatory, else you only have a local var >>> self.name = name >>> >>> # don't use builtin names as identifiers - unless you really want to >>> # shadow the builtins >>> d = {0:[MyClass('hello')} >>> d[0].append(MyClass('goodbye')) >>> d.setdefault(1, []).append(MyClass('Yo')) >>> print d >>> >>> HTH > > > Is there anyway for python to consider the values within a string when > entering the data into a dictionary. I know that isn't very clear so here's > an example: > > class MyClass(object): > def __init__(self,name="",age=""): > self.name=name > self.age=age > > data="Gary,50" > d={0:[MyClass(data)]} > data="Adam,25" > d[0].append(MyClass(data)) > > The data is coming from a text file working on a line by line basis. I've > just tried and I'm just getting the full string in the first field. That > seems logical, now I don't want it to though! > If you mean you would like to store a list of values then you could try something like d = {0: MyClass(*data.split(",")} to create the objects. The .split() method turns the string into a list of substrings, and the * unary operator turns that list into individual arguments passed to the __init__() method. However, your recent question history indicates that you would do well to study the Python tutorial and other beginner material, as you will find many valuable hints as to Python best practices which will save you a lot of time. Also there is the python-help at python.org list if you are having problems of a "beginner" nature, where you might get more practical help in your initial use of the language. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From rrs at researchut.com Fri Aug 10 17:53:40 2007 From: rrs at researchut.com (Ritesh Raj Sarraf) Date: Sat, 11 Aug 2007 03:23:40 +0530 Subject: Module imports during object instantiation Message-ID: <4c3vo4-u7k.ln1@learner.hq.netapp.com> Hi, I've been very confused about why this doesn't work. I mean I don't see any reason why this has been made not to work. class Log: def __init__(self, verbose, lock = None): if verbose is True: self.VERBOSE = True else: self.VERBOSE = False if lock is None or lock != 1: self.DispLock = False else: self.DispLock = threading.Lock() self.lock = True if os.name == 'posix': self.platform = 'posix' self.color = get_colors() elif os.name in ['nt', 'dos']: self.platform = 'microsoft' try: import SomeModule except ImportError: self.Set_Flag = None if self.Set_Flag is not None: self.color = SomeModule.get_colors_windows() else: self.platform = None self.color = None When I create an object the "import" part never gets executed. Is there a reason behind it ? I mean I'd like to keep my class as independent as I want. So that when later I need to use it somewhere else, I don't need to know if it depends on any modules. Currently, the way I'm left is to globally go and import the module and set a flag there. Ritesh -- If possible, Please CC me when replying. I'm not subscribed to the list. From goldtech at worldpost.com Fri Aug 31 19:54:02 2007 From: goldtech at worldpost.com (goldtech) Date: Fri, 31 Aug 2007 16:54:02 -0700 Subject: Parameter Passing - String Variable Truncated ? Message-ID: <1188604442.700651.94530@19g2000hsx.googlegroups.com> Hi, I'm passing what I think is a string parameter to another Python program (spawn.py) - see the code snip below. But only the counter part gets printed to a log file via spawn.py. Yet the echo print to the output window shows the whole string with the fc part. Better explained below I hope, there's the calling .py and the spawn script .py: ...snip... while fc: counter = counter + 1 fc_cntr = str(counter) + ' : ' + fc print fc_cntr + '\n' # Print to Pythonwin interactive window - eg. "1 : New York" - all is printed OK arglist = [] arglist.append(pythonPath) arglist.append(spawn_script) arglist.append(fc_cntr) # This gets sent to the spawn_script but only "1" gets printed os.spawnv(os.P_WAIT, pythonPath, arglist) fc = fcs.next() ... -------------------------- ## the spawn_script import win32com.client, sys, os, time, re in_featclass = sys.argv[1] handle = open('C:\\log_file.txt', 'a') handle.write(in_featclass + "\n") # ONLY the counter part gets printed to the log file! Why? -------------------------- Thanks, for help. From zentraders at gmail.com Thu Aug 23 15:40:49 2007 From: zentraders at gmail.com (Zentrader) Date: Thu, 23 Aug 2007 12:40:49 -0700 Subject: beginner, idiomatic python In-Reply-To: <13cqlqbbpn0dmea@corp.supernews.com> References: <13cqlqbbpn0dmea@corp.supernews.com> Message-ID: <1187898049.734696.9500@l22g2000prc.googlegroups.com> Does page count change? i.e. is it necessary to retrieve it in every loop or tempList = ['1','2','3','4','5','6','7','8'] sampleList=[] page_count = self.parent.GetPageCount() <snipped> for i in range(page_count): Also, once pagefound is set to True, all pages following will not be appended to sampleList because it is not initialized to False under the "for i in range(self.parent.GetPageCount())" loop. Finally, if I understand the logic and question correctly, you want something like tempList = ['1','2','3','4','5','6','7','8'] sampleList=[] page_count = self.parent.GetPageCount() for port in tempList: for i in range(page_count): page=self.parent.GetPage(i) if (hasattr(page, "port")) and (page.port != int(port)) : sampleList.append(port) or perhaps (I'm not sure) tempList = [1, 2, 3, 4, 5, 6, 7, 8] sampleList=[] page_count = self.parent.GetPageCount() for i in range(page_count): page=self.parent.GetPage(i) if (hasattr(page, "port")) and (page.port not in tempList) : sampleList.append(port) HTH From nytrokiss at gmail.com Tue Aug 28 19:34:07 2007 From: nytrokiss at gmail.com (James Matthews) Date: Tue, 28 Aug 2007 16:34:07 -0700 Subject: Gmane's been quiet ... In-Reply-To: <1i3l2k9.1j3tdgr1iz19yeN%raims@dot.com> References: <mailman.88.1188343014.28954.python-list@python.org> <1i3l2k9.1j3tdgr1iz19yeN%raims@dot.com> Message-ID: <8a6b8e350708281634r3520430l4ffa86ebb94917de@mail.gmail.com> Maybe they are sick of the spam! On 8/28/07, Lawrence Oluyede <raims at dot.com> wrote: > > Steve Holden <steve at holdenweb.com> wrote: > > ... so I was wondering if it's just me who hasn't seen any postings > today? > > I think so, through my usenet server I saw the usual lot of postings > > -- > Lawrence, oluyede.org - neropercaso.it > "It is difficult to get a man to understand > something when his salary depends on not > understanding it" - Upton Sinclair > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070828/5172a31b/attachment.html> From tjreedy at udel.edu Thu Aug 2 12:58:05 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 2 Aug 2007 12:58:05 -0400 Subject: i am new to python-Please somebody help References: <1186047103.673871.150460@z24g2000prh.googlegroups.com><pan.2007.08.02.12.51.13.363293@REMOVE.THIS.cybersource.com.au> <1186063842.827016.95030@q3g2000prf.googlegroups.com> Message-ID: <f8t2er$t5p$1@sea.gmane.org> "gregarican" <greg.kujawa at gmail.com> wrote in message news:1186063842.827016.95030 at q3g2000prf.googlegroups.com... | friendly than Python's. Your points are well-taken in how to properly | post and how to do your own homework. Message correct. Delivery | lacking... Sorry, I saw nothing rude in Steven's straightforward and indeed polite suggestion. Your post, however, .... tjr From arkanes at gmail.com Fri Aug 10 08:43:10 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 10 Aug 2007 07:43:10 -0500 Subject: wxPython before MainLoop In-Reply-To: <13bnh5bs4b9h427@corp.supernews.com> References: <13bl9a75laqcm70@corp.supernews.com> <13bnh5bs4b9h427@corp.supernews.com> Message-ID: <4866bea60708100543r3a18f7d3he38db8951a16cfeb@mail.gmail.com> On 8/9/07, [david] <david at nospam.spam> wrote: > I'm disappointed that I didn't get a wxPython solution. > > If the only way to get wxPython to correctly handle > this simple task is to code around it, I don't think > wxPython is really ready for Windows. > This sort of blathering is really just insulting. You don't know what you're doing, but that doesn't mean that "wxPython isn't really ready for Windows". You can't interact with a window without an event loop running. This is not (just) a wxPython limitation, it's intrinsic in guis in general and in the windows platform in particular. You need to do 2-step initialization, and you need to break it into bits (or threads) that can operate independently of the event loop. If you would like some suggestions as to how to do that in your particular case, please feel free to post details on the wx-python list, but leave your attitude at the door. From kyosohma at gmail.com Thu Aug 23 09:17:00 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 23 Aug 2007 06:17:00 -0700 Subject: How would I go about making a file open. Not the way you might think. In-Reply-To: <mailman.159.1187857019.32294.python-list@python.org> References: <eb79828c0708221959t18dd4024m251c1eac7732ec1f@mail.gmail.com> <mailman.159.1187857019.32294.python-list@python.org> Message-ID: <1187875020.332095.324530@x35g2000prf.googlegroups.com> On Aug 23, 2:09 am, "Hendrik van Rooyen" <m... at microcorp.co.za> wrote: > Lamonte Harris wrote: > >Basically you can open a file by double clicking, and by default it would open > > w/ what every program you have it set >to. Most text files would open in > notepad. How can I make a txt open so that notepad opens w/ the content in it > by >using just python. > > I asked this question just yesterday - and Tim Golden answered: > > os.startfile() > > - Hendrik Golden knows a lot. That's a good way to do it. I recommend it too! Mike From orsenthil at users.sourceforge.net Wed Aug 1 11:15:12 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Wed, 1 Aug 2007 20:45:12 +0530 Subject: Problem with subprocess.Popen() In-Reply-To: <1185959039.674882.210540@q75g2000hsh.googlegroups.com> References: <1185959039.674882.210540@q75g2000hsh.googlegroups.com> Message-ID: <20070801151511.GB3640@gmail.com> > I'm trying to run a windows batch file from a python script using > subprocess.popen(). > > The issue that I'm facing is that, if i give the batch file as > parameter to the popen function, the script runs, but if i provide a > parameter, it is not working. > > The actual windows command to be executed is: > > test.bat -t ABC_DE_FG_HI_001 "C:\ABCDEFGHIJKLMNOP.TXT" do something like: subprocess.Popen(r'test.bat -t ABC_DE_FG_HI_001 "C:\ABCDEFGHIJKLMNOP.TXT",shell=True) This is same as doing os.system() If even this results in any error (post back the error message) and try setting the executable argument explicit. subprocess.Popen(r'test.bat -t ABC_DE_001 "C:\ABCD.TXT",executable="test.bat",shell=True) -- O.R.Senthil Kumaran http://uthcode.sarovar.org From Shawn at Milochik.com Tue Aug 14 12:47:37 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Tue, 14 Aug 2007 12:47:37 -0400 Subject: Simple python iteration question In-Reply-To: <1187108787.998690.37500@q3g2000prf.googlegroups.com> References: <bFkwi.675$Oo.563@newssvr17.news.prodigy.net> <1187108787.998690.37500@q3g2000prf.googlegroups.com> Message-ID: <2dc0c81b0708140947s6542b68aw7e1fa8a3d22978e2@mail.gmail.com> <snip> > this will get index and item at index, > > for i in range(0, len(l)): > print i > print l[i] > > > -- > http://mail.python.org/mailman/listinfo/python-list > Enumerate is better here -- it provides the same result and that's what it's for. However, if you do use range, the zero is unnecessary -- beginning at zero is the default. From bronger at physik.rwth-aachen.de Thu Aug 16 01:47:14 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 16 Aug 2007 07:47:14 +0200 Subject: ElementTree surprise References: <7xd4xoxf16.fsf@ruckus.brouhaha.com> Message-ID: <87bqd89gkd.fsf@wilson.homeunix.com> Hall?chen! Paul Rubin writes: > I have a doc with a bunch of fields like: > > <foo bar="spam">stuff</foo> > <foo bar="penguin">other stuff</foo> > > and sometimes > > <foo bar="parrot"></foo> > > I use ElementTree to parse the doc and I use the .text attribute > to get "stuff" or "other stuff" in the spam and penguin examples. > > I'd expect .text to be the empty string in the parrot example, but > instead it is None. Technically, text is nodes as all other element nodes. In the parrot example, there is no empty textnode but no textnode at all. > I can fix my script to deal with this, but it's surprising. Is it > intentional? I could understand it being None if the doc had said > > <foo bar="parrot"/> > > but that is different. <foo bar="parrot"/> and <foo bar="parrot"></foo> are mapped to the same thing by any XML parser, and I think it wouldn't be standards conforming if an XML parser would pass this difference to a caller. > Disclaimer: I'm not even slightly an XML expert, I just find myself > having to deal with a lot of it. I think the question is how XMLish the access via ElementTree should be. While it is in principle correct that there is no text node in parrot, it may be sensible to set it to "" for practical reasons. As far as I can see, there is no empty text node in XML, so no ambiguity would occur. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From cajnnjonaj at fjireanjtjprodjuctijons.com Mon Aug 20 09:48:07 2007 From: cajnnjonaj at fjireanjtjprodjuctijons.com (Aaron) Date: Mon, 20 Aug 2007 08:48:07 -0500 Subject: yet another indentation proposal References: <fEZxi.8855$9W6.6492@fe103.usenetserver.com> <13ci0oesdtlh871@corp.supernews.com> <_49yi.9351$3x.6614@newssvr25.news.prodigy.net> <1187589173.410862.132580@o80g2000hse.googlegroups.com> Message-ID: <D_gyi.6547$sH3.154@fe091.usenetserver.com> "Michael Tobis" <mtobis at gmail.com> wrote in message news:1187589173.410862.132580 at o80g2000hse.googlegroups.com... > > Alternatively, you might also consider writing a simple pre and > postprocessor so that you could read and write python the way you > would prefer > > In that you could cope with the existing code base and the existing > compiler could cope with code you write. > > mt > Hi. That's probably what I'll end up doing. The only drawback to that is that it solves the problem for me only. Perhaps I will open source the scripts and write up some documentation so that other folks in a similar situation don't have to reinvent the wheel. The only unfortunate aspect to that is that blind newbies to the language will have to figure out setting up a shell script or batch file to pipe the output of the filter into Python on top of learning the language. I admit, it's probably not that much work, but it is one more stumblingblock that blind newcomers will have to overcome. Aaron From dejanews at email.com Wed Aug 15 07:40:24 2007 From: dejanews at email.com (samwyse) Date: Wed, 15 Aug 2007 06:40:24 -0500 Subject: wxPython before MainLoop In-Reply-To: <mailman.1843.1186775191.22759.python-list@python.org> References: <13bl9a75laqcm70@corp.supernews.com> <6a6dnfbbFJNzcCbbnZ2dnUVZ_oudnZ2d@comcast.com> <mailman.1843.1186775191.22759.python-list@python.org> Message-ID: <ADBwi.1237$%Y7.624@nlpi069.nbdc.sbc.com> Chris Mellon wrote: > On 8/9/07, Heikki Toivonen <heikki at osafoundation.org> wrote: > >>[david] wrote: >> >>>I'd like to refresh the display before I start the main loop. If your window isn't able to interact with the user, then I'd consider it a splash screen, no matter if it does look exactly like your main application interface. >>We have this kind of situation in Chandler, where we display and update >>the splash screen before we enter MainLoop. >> [...] >>3. The splash screen refresh is basically: draw new stuff, >>self.Layout(), self.Update(), wx.Yield() >>http://lxr.osafoundation.org/source/chandler/application/Application.py#1421 Looking at the Chandler code suggests a solution to [david]'s original problem. It is possible that, on Windows only, he may need to call Update to finish painting the display. 1432 self.Layout() 1433 if wx.Platform == '__WXMSW__': 1434 self.Update() 1435 wx.GetApp().Yield(True) > wxYield spins the event loop in place. This can have some serious > consequences if you aren't very careful with your usage, like > recursively entering event handlers. I generally consider it an > experts only interface, and avoid it. I'll confess to being one of those old-school programmers who, back in the day, wrote his code around big select loops instead of using threads, but I'm intriged by the "experts only" designation. Can someone explain further? Thanks! From stefan.behnel-n05pAM at web.de Wed Aug 1 03:50:58 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 01 Aug 2007 09:50:58 +0200 Subject: Iteration over strings In-Reply-To: <mailman.1378.1185905291.22759.python-list@python.org> References: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> <mailman.1378.1185905291.22759.python-list@python.org> Message-ID: <46B03B62.4080002@web.de> > Robert Dailey wrote: >> I have the following code: >> >> str = "C:/somepath/folder/file.txt" >> >> for char in str: >> if char == "\\": >> char = "/" >> >> The above doesn't modify the variable 'str' directly. I'm still pretty new >> to Python so if someone could explain to me why this isn't working and what >> I can do to achieve the same effect I would greatly appreciate it. I assume what you are actually looking for is the os.path module. http://docs.python.org/lib/module-os.path.html Especially the normpath() function should be of interest. Stefan From whamil1 at entergy.com Mon Aug 6 14:14:50 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Mon, 6 Aug 2007 13:14:50 -0500 Subject: Something in the function tutorial confused me. In-Reply-To: <1186422680.103021.105230@l70g2000hse.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CB00@LITEXETSP001.etrsouth.corp.entergy.com> > From: Lee Fleming > On Aug 6, 12:30 pm, "Hamilton, William " <wham... at entergy.com> wrote: > > When you call f(23), the variable y within it gets created and points at > > None. When f(23) exits, the y that it created gets destroyed. (Well, > > goes out of scope, but even if it's not garbage collected it won't ever > > come back into scope.) When you then call f(24), a new y is created > > that also points to None, and disappears forever when f(24) exits. > > > > The values in a def statement are created when the def is executed, but > > the variables are only created when the function is actually called, and > > new ones are created every time the function is called. > > > > -- > > -Bill Hamilton- Hide quoted text - > > > > - Show quoted text - > > why isn't the y in def f (x, y = []): something > garbage-collected? > The y is garbage-collected. However, the [] in the def statement is not. The list is created when the statement is evaluated. Every time that f() is called with a default value, the new y created will point to the same list. If that list is mutated into [23], it will still be [23] the next time f() is called, and the new y created in that call will point at the same list (now [23]) that the (now destroyed) y pointed to in the first call. -- -Bill Hamilton From uymqlp502 at sneakemail.com Fri Aug 31 15:48:41 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Fri, 31 Aug 2007 12:48:41 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <slrnfdg413.1e8.horpner@FIAD06.norwich.edu> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> <mailman.181.1188527203.28954.python-list@python.org> <slrnfdg413.1e8.horpner@FIAD06.norwich.edu> Message-ID: <1188589721.367781.322150@z24g2000prh.googlegroups.com> Neil Cerutti wrote: > Who watches the watchmen? The contracts are composed by the > programmers writing the code. Is it likely that the same person > who wrote a buggy function will know the right contract? The idea here is that errors in the self-testing code are unlikely to be correlated with errors in the primary code. Hence, you get a sort of multiplying effect on reliability. For example, if the chance of error in the primary code and the self-test code are each 0.01, the chance of an undetected error is approximately 0.01^2 or 0.0001. From ars at iki.fi Thu Aug 2 07:05:47 2007 From: ars at iki.fi (Antti Rasinen) Date: Thu, 2 Aug 2007 14:05:47 +0300 Subject: Use variable in regular expression In-Reply-To: <1186051401.122847.114690@d55g2000hsg.googlegroups.com> References: <1186051401.122847.114690@d55g2000hsg.googlegroups.com> Message-ID: <277962F2-5F20-4CEF-BD66-643433426182@iki.fi> On 2007-08-02, at 13:43, CarpeSkium at gmail.com wrote: > I know I can use a variable in regular expressions. I want to use a > regex to find something based on the beginning of the string. I am > using yesterday's date to find all of my data from yesterday. > Yesterday's date is 20070731, and assigned to the variable > "yesterday_date". I want to loop thru a directory and find all of the > yesterday's data ONLY IF the feature class has the date at the > BEGINNING of the filename. > > ... > I don't want the one's that start with "Copy". I can't figure out the > syntax of inserting the "^" into the regex. I've tried all of the > following, with no luck: > > re.compile(^yesterday_date) > re.compile(r'^yesterday_date') > re.compile(r'^[yesterday_date]') > re.compile(r'[^yesterday_date]') The first one is a syntax error (^ outside a string means the xor- operation). The rest are just strings containing the _string_ 'yesterday_date' and not the value of the variable. So you need to do some string formatting(* search_str = '^%s' % yesterday_date # I'm assuming yesterday_date is a string. re.compile(search_str) *) http://docs.python.org/lib/typesseq-strings.html -- [ ars at iki.fi <*> Antti Rasinen ] This drone-vessel speaks with the voice and authority of the Ur-Quan. From nguyenhuuthanh at gmail.com Fri Aug 24 23:04:12 2007 From: nguyenhuuthanh at gmail.com (Genie T) Date: Sat, 25 Aug 2007 03:04:12 -0000 Subject: Running daemon with zdaemon ... example help? Message-ID: <1188011052.347321.211890@r23g2000prd.googlegroups.com> Hi all, I'm looking at zdaemon to run my python scripts as a daemon but it seems to have few example that guide me how to follow. It would be great if you can give me a simple example of how to use. I'm newbie here :) Thanks From kyosohma at gmail.com Tue Aug 7 12:15:52 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 07 Aug 2007 09:15:52 -0700 Subject: python system subprocess win32 In-Reply-To: <f9a5c8$mvd$1@gemini.csx.cam.ac.uk> References: <f9a0on$dee$1@gemini.csx.cam.ac.uk> <1186500091.063514.178640@e9g2000prf.googlegroups.com> <f9a5c8$mvd$1@gemini.csx.cam.ac.uk> Message-ID: <1186503352.062314.89170@x35g2000prf.googlegroups.com> On Aug 7, 11:07 am, "mclaugb" <mcla... at nospm.yahoo.com> wrote: > At the moment, I cannot figure a way of running this precompiled "conv.exe" > using commandline arguments. > > Thus, I need Python to call the program, wait until it loads up, then enter > a known sequence of characters so that the function will run. > The program conv.exe I call looks like this. > -------------------------- > Welcome to conv.exe > This program was written by .... > > Please select from the following options: h- (help) r- (read) ...etc > Enter your request: > --------------------------------- > I need Python to start the program, wait a second and then issue a few > characters to the program. > > Hope this makes more sense! > Bryan > > <kyoso... at gmail.com> wrote in message > > news:1186500091.063514.178640 at e9g2000prf.googlegroups.com... > > > On Aug 7, 9:48 am, "mclaugb" <mcla... at nospm.yahoo.com> wrote: > >> Hello ALl, > >> I have a compiled program "conv.exe" that works as follows:>>conv.exe > > >> ----------------------------- > >> Please selection from the following options. press "h" for help, "p" for > >> print, "r" for readfile. > >> Enter your request now: > >> ... > >> -------------------- > >> Is there a way to script python using the subprocess method to start this > >> program "conv.exe" and then send a "r" to the command line to make it, > >> say, > >> readfile. > > >> I have tried the following but the .communicate("r) is not doing anything > > >> import subprocess > >> import time > > >> a=subprocess.Popen("c:\\mcml\\conv.exe") > >> time.sleep(1) > >> (stdout, stderr) = a.communicate("r") > > >> Many thanks, > >> Bryan > > > Use the sys.argv method. In the code that you have compiled, put the > > following lines in: > > > <code> > > > import sys > > default = sys.argv[1] > > if default: > > # check which option it is and run it appropriately > > else: > > # print your menu here > > > </code> > > > Then you should be able to do the subprocess Popen command: > > > subprocess.Popen("c:\\mcml\\conv.exe r") > > > You may need to turn the shell on... > > > subprocess.Popen("c:\\mcml\\conv.exe r", shell=True) > > > Hopefully that gives you some ideas anyway. > > > Mike Oh. I thought you had compiled the program yourself. I suppose you could use SendKeys then. I have a couple links here: http://pythonlibrary.org/python/SendKeys It's pretty hackneyed, but I've used the SendKeys module to automate Firefox to some degree. Mike From tjreedy at udel.edu Fri Aug 31 02:28:36 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 31 Aug 2007 02:28:36 -0400 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com><87hcmhebwv.fsf@benfinney.id.au> <5jn9qgFdmbcU3@mid.uni-berlin.de> Message-ID: <fb8cf7$cre$1@sea.gmane.org> "Marc 'BlackJack' Rintsch" <bj_666 at gmx.net> wrote in message news:5jn9qgFdmbcU3 at mid.uni-berlin.de... | On Thu, 30 Aug 2007 17:09:36 +1000, Ben Finney wrote: | | > zzbbaadd at aol.com writes: | > | >> What's with the index() function of lists throwing an exception on not | >> found? | > | > It's letting you know that the item isn't in the list. There's no | > sensible return value from an "index" function in that condition. | | What about -1? C programmers do this all the time. :-) Because they do not have exceptions. From ldo at geek-central.gen.new_zealand Wed Aug 29 04:36:17 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 29 Aug 2007 20:36:17 +1200 Subject: Jython 2.2 on Ubuntu References: <-YOdnW_k3p6Fy0nb4p2dnAA@bt.com> Message-ID: <fb3b1d$v9m$2@lust.ihug.co.nz> In message <-YOdnW_k3p6Fy0nb4p2dnAA at bt.com>, Neil Wallace wrote: > I have used the > GUI installer of Jython 2.2, and installed it to the default > /root/jython2.2 directory. You do realize that /root is the home directory of the root user, normally off-limits to normal users? Usually if you're installing your own packages, you would put them in /usr/local or /opt. From horpner at yahoo.com Mon Aug 6 07:27:28 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 06 Aug 2007 11:27:28 GMT Subject: Something in the function tutorial confused me. References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <slrnfbe1fd.n4.horpner@FIAD06.norwich.edu> Message-ID: <slrnfbe1jd.1so.horpner@FIAD06.norwich.edu> On 2007-08-06, Neil Cerutti <horpner at yahoo.com> wrote: > On 2007-08-06, Lee Fleming <countblabula at yahoo.com> wrote: >> def f(x, y=None): >> if y is None: y = [] >> y.append(x) >> return y > > >>> f(f(23)) > [23, 42] Sorry. That should've been: >>> f(42, f(23)) [23, 42] -- Neil Cerutti Scouts are saving aluminum cans, bottles, and other items to be recycled. Proceeds will be used to cripple children. --Church Bulletin Blooper From rcdailey at gmail.com Mon Aug 20 14:16:50 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 20 Aug 2007 13:16:50 -0500 Subject: str().join() isn't working In-Reply-To: <496954360708200905i2100b32ag5983ab729e5d216f@mail.gmail.com> References: <496954360708200905i2100b32ag5983ab729e5d216f@mail.gmail.com> Message-ID: <496954360708201116x5507358cr2f81710a62f2403e@mail.gmail.com> here is a more realized example of the lists I'm trying to join: _user_includes = [ "../src", "../resource", "../inc", "../src", "../data", "../gui", "../script", "../script/actions", "../gui/dispatch", "../gui/factories", "../gui/frames", "../gui/getters", "../gui/localization", "../gui/player", "../gui/setters", "../gui/utilities", "../sis", "../player", "../platform/ngi", "../../engine", "../../engine/audio/NGI", "../../engine/io", "../../engine/io\NGI", "../../engine/math", "../../engine/math/fixed", "../../engine/path/NGI", "../../engine/text/NGI", "../../engine/mem", "../../engine/text", "../../engine/observer", "../../sdk/tiny_xml", "../../sdk/zlib", "../../sdk/lpng", "../../sdk/IFDLib/Source/Precompile", "../../sdk/IFDLib/Source/CoreLib", "../../sdk/IFDLib/inc", "../../sdk/IFDLib/Source/UtilLib", "../../sdk/IFDLib/Source/GameLib", "../../sdk/IFDlib/Source/OSLib/_NGI", "../../sdk/stl-port/NGI", "../../sdk/mini-boost/NGI", "../../sdk/mini-boost/COMMON", ] _system_includes = [ "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include", "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include/osextensions/rga", "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include/osextensions/stdapis", "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include/osextensions/stdapis/stlport", "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/epoc32/include/variant" ] On 8/20/07, Robert Dailey <rcdailey at gmail.com> wrote: > Hi, > > First have a look at the following code: > > > In main.py: > ----------------------------------------------------------------------------------- > space = " " > > includes = space.join ( system._user_includes ) + " " + space.join( > system._system_includes ) > > > In system.py: > ----------------------------------------------------------------------------------- > _user_includes = [ > ] > > _system_includes = [ > ] > > > The above does not work. The interpreter states: "TypeError: sequence item > 0: expected string, list found". I'm not sure what this means. Can anyone > help me figure out what I'm doing wrong? Thanks. > > PS: I've also tried putting strings in the lists above just to make sure > that them being empty wasn't the problem. I got no different results. > From ptmcg at austin.rr.com Wed Aug 22 12:19:47 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 22 Aug 2007 09:19:47 -0700 Subject: Eval and raw string ?? In-Reply-To: <1187798806.029598.264740@q3g2000prf.googlegroups.com> References: <1187798806.029598.264740@q3g2000prf.googlegroups.com> Message-ID: <1187799587.101535.7530@x35g2000prf.googlegroups.com> On Aug 22, 11:06 am, Mark <cree... at gmail.com> wrote: > Eval() doesn't seem to recognize the r'string' format. Is there a way > around this. > Example: > If I input: ---------> eval("r'C:\tklll\ndfd\bll'") > I get the output: > > Traceback (most recent call last): > File "<pyshell#3>", line 1, in <module> > eval("r'C:\tklll\ndfd\bll'") > File "<string>", line 1 > r'C: klll > ^ > SyntaxError: EOL while scanning single-quoted string > > The same principle applies for exec. > > Thanks in advance, > Mark This is not a raw string: "r'\tsomething in quotes'". It is a string starting with an "r", a "'", a tab, and and "s". This is a raw string: r'\tsomething in quotes'. It is a string starting with a "\", a "t" and an "s". Notice that the \t and \n in c:\tkllll\ndfd\bll were treated like tab and newline? Try eval(r'c:\tkllll\ndfd\bll') (You will get a different error now, but it wont be a raw string problem.) -- Paul From kyosohma at gmail.com Fri Aug 3 16:06:50 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 03 Aug 2007 13:06:50 -0700 Subject: os.listdir path error In-Reply-To: <1186170609.001778.15230@l70g2000hse.googlegroups.com> References: <1186170609.001778.15230@l70g2000hse.googlegroups.com> Message-ID: <1186171610.333624.103640@e9g2000prf.googlegroups.com> On Aug 3, 2:50 pm, vedrandeko... at v-programs.com wrote: > Hello > > Here is my simple listdir example: > > >>> import os > >>> os.listdir("C:\Python24\") # This directory relly exists > > Here is my error: > > WindowsError: [Errno 3] The system cannot find the path specified: 'l/ > *.*' > > Regards, > Vedran I get "SyntaxError: EOL while scanning single-quoted string", which is what should happen when you escape the double-quotes at the end. Not sure how you're getting that WindowsErrors. If I do os.listdir('c:\python24') instead, it works fine. Mike From rdm at rcblue.com Sun Aug 12 18:30:02 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 12 Aug 2007 15:30:02 -0700 Subject: A dumb question about a class In-Reply-To: <TqSdnWYzVdWvGCLbnZ2dnUVZ_saknZ2d@comcast.com> References: <mailman.1887.1186955369.22759.python-list@python.org> <TqSdnWYzVdWvGCLbnZ2dnUVZ_saknZ2d@comcast.com> Message-ID: <20070812223007.15D161E400B@bag.python.org> At 03:09 PM 8/12/2007, Steven Bethard wrote: >Here's how I'd write the recipe:: > > import itertools > > def iter_primes(): > # an iterator of all numbers between 2 and +infinity > numbers = itertools.count(2) > > # generate primes forever > while True: > > # get the first number from the iterator (always a prime) > prime = numbers.next() > yield prime > > # remove all numbers from the (infinite) iterator that are > # divisible by the prime we just generated > numbers = itertools.ifilter(prime.__rmod__, numbers) > > > class PrimeList(object): > def __init__(self): > # infinite iterator of primes > self._prime_iter = iter_primes() > > # the last prime we've seen > self._last_prime = None > > # all primes seen so far > self._prime_set = set() > > # add the first prime (so that _last_prime is set) > self._add_prime() > > def __contains__(self, n): > # add primes to the list until we exceed n > while n > self._last_prime: > self._add_prime() > > # return True if n is one of our primes > return n in self._prime_set > > def _add_prime(self): > # take a prime off the iterator and update the prime set > self._last_prime = self._prime_iter.next() > self._prime_set.add(self._last_prime) I'm afraid my next question is "How do I run this"? Dick From DustanGroups at gmail.com Sat Aug 11 08:26:12 2007 From: DustanGroups at gmail.com (Dustan) Date: Sat, 11 Aug 2007 12:26:12 -0000 Subject: Deleting objects on the fly In-Reply-To: <mailman.1842.1186771794.22759.python-list@python.org> References: <1186705500.227658.163170@q3g2000prf.googlegroups.com> <46BC35F2.4070600@metavr.com> <mailman.1842.1186771794.22759.python-list@python.org> Message-ID: <1186835172.396997.210710@d55g2000hsg.googlegroups.com> On Aug 10, 1:49 pm, "Terry Reedy" <tjre... at udel.edu> wrote: > "Campbell Barton" <cbar... at metavr.com> wrote in message > > news:46BC35F2.4070600 at metavr.com...| Michele Simionato wrote: > > | > Probably not, 'del x' just decrements the reference count, > > Or ashttp://docs.python.org/ref/del.html > puts it, " Deletion of a name removes the binding of that name from the > local or global namespace," > > | del x will remove x from memory if nothing else is refering to it, > > This is implementation dependent: true for CPython, not for Jython, ??? for > IronPython. Wait a second; do you mean to say that in Jython, del x will never remove x from memory? How do you free up RAM? From byte8bits at gmail.com Tue Aug 14 09:18:37 2007 From: byte8bits at gmail.com (brad) Date: Tue, 14 Aug 2007 09:18:37 -0400 Subject: Assignments and Variable Substitution In-Reply-To: <mailman.1947.1187053596.22759.python-list@python.org> References: <f9q2qn$i4v$1@solaris.cc.vt.edu> <cfb58d850708131223y37ccb61y465fc2f964ad05e4@mail.gmail.com> <mailman.1947.1187053596.22759.python-list@python.org> Message-ID: <f9sa6b$4pc$1@solaris.cc.vt.edu> Steve Holden wrote: > Evan Klitzke wrote: >> On 8/13/07, brad <byte8bits at gmail.com> wrote: >>> I'd like to do something like this: >>> >>> var = '123' >>> %s = [], %var >>> >>> So that, in the end, var is '123' and an empty list is named '123' as >>> well. The list assignments are created during a loop. >> >> You can't assign a variable whose name is 123, but you can do this >> sort of thing with setattr. >> > And why would you want a variable whose name is '123'? Just an example. From carsten at uniqsys.com Thu Aug 30 21:15:27 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 30 Aug 2007 21:15:27 -0400 Subject: list index() In-Reply-To: <fb7osg$jb7$2@lust.ihug.co.nz> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <46d674c2$0$417$426a34cc@news.free.fr> <1188496588.750629.208100@g4g2000hsf.googlegroups.com> <mailman.154.1188497511.28954.python-list@python.org> <1188498073.997168.282420@q5g2000prf.googlegroups.com> <mailman.158.1188499243.28954.python-list@python.org> <fb7osg$jb7$2@lust.ihug.co.nz> Message-ID: <1188522927.3258.15.camel@localhost.localdomain> On Fri, 2007-08-31 at 12:57 +1200, Lawrence D'Oliveiro wrote: > In message <mailman.158.1188499243.28954.python-list at python.org>, Steve > Holden wrote: > > > But why would you want to ignore built-in support like "value in dict"? > > Because a function can be passed as a value in its own right, a built-in > construct cannot. ...and that's why we have operator.contains(): >>> import operator >>> help(operator.contains) Help on built-in function contains in module operator: contains(...) contains(a, b) -- Same as b in a (note reversed operands). -- Carsten Haese http://informixdb.sourceforge.net From gnewsg at gmail.com Tue Aug 28 13:55:59 2007 From: gnewsg at gmail.com (billiejoex) Date: Tue, 28 Aug 2007 10:55:59 -0700 Subject: tempfile.mkstemp and os.fdopen Message-ID: <1188323759.955043.317630@19g2000hsx.googlegroups.com> Hi there. I'm trying to generate a brand new file with a unique name by using tempfile.mkstemp(). In conjunction I used os.fdopen() to get a wrapper around file properties (write & read methods, and so on...) but 'name' attribute does not contain the correct file name. Why? >>> import os >>> import tempfile >>> fileno, name = tempfile.mkstemp(prefix='ftpd.', dir=os.getcwd()) >>> fd = os.fdopen(fileno, 'wb') >>> fd.name <fdopen> Moreover, I'd like to know if I'm doing fine. Does this approach avoid race conditions or other types of security problems? Thanks in advance From Dominic at PLEASEASK.co.uk Thu Aug 9 04:40:03 2007 From: Dominic at PLEASEASK.co.uk (special_dragonfly) Date: Thu, 9 Aug 2007 09:40:03 +0100 Subject: Help with Dictionaries and Classes requested please. References: <46bacae3$0$89254$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <46bacf1b$0$54289$7b0f0fd3@mistral.news.newnet.co.uk> "special_dragonfly" <Dominic at PLEASEASK.co.uk> wrote in message news:46bacae3$0$89254$7b0f0fd3 at mistral.news.newnet.co.uk... > Hello, > I'm new to this group, I've read through the subject of a lot of the group > but can't find anything relevant. Perhaps my question is too basic but I'm > still stuck. > Classes and Dictionaries. > If I have a dictionary, how do I instantiate many instances of a class per > dictionary key? Either at run-time or dynamically. > Can anyone help me please? > Thank you > Dominic > > I've managed to solve the problem, I really was just being a dunce. Here's how incase anyone is wondering: class MyClass: def __init__(self): name="" dict={} dict[0]=[] dict[0].append(MyClass()) dict[0][0].name="Hello" print dict[0][0].name I'm sorry if I've wasted anyones time, although if there's a better way of doing the above I'd still be interested to know. Dominic From chrispwd at gmail.com Sun Aug 5 14:10:13 2007 From: chrispwd at gmail.com (chrispwd at gmail.com) Date: Sun, 05 Aug 2007 11:10:13 -0700 Subject: Buffering HTML as HTMLParser reads it? In-Reply-To: <1185998888.811319.15150@l70g2000hse.googlegroups.com> References: <1185993078.651180.298620@19g2000hsx.googlegroups.com> <1185998888.811319.15150@l70g2000hse.googlegroups.com> Message-ID: <1186337413.343863.257890@g4g2000hsf.googlegroups.com> On Aug 1, 4:08 pm, Paul McGuire <pt... at austin.rr.com> wrote: > On Aug 1, 1:31 pm, chris... at gmail.com wrote: > <snip> > > > > > I'm thinking maybe somehow haveHTMLParserappend each character it > > reads except for data inside tags in some kind of buffer? This way I > > can have the HTML contents read into a buffer, then when I do my own > > handle_ overrides, I can also append to that buffer with the > > transformed data. Once the HTML page is finished parsing, ideally I > > would be able to print the contents of the buffer and the HTML would > > be identical except for the string transformations. > > > I also need to make sure that all newlines, tags, spacing, etc are > > kept in tact -- this part is a requirement for other reasons. > > > Thanks! > > What you describe is almost exactly how pyparsing implements > transformString. See below: > > from pyparsing import * > > boldStart,boldEnd = makeHTMLTags("B") > > # convert <B> to <div class="bold"> and </B> to </div> > boldStart.setParseAction(replaceWith('<div class="emphatic">')) > boldEnd.setParseAction(replaceWith('</div>')) > converter = boldStart | boldEnd > > html = "Display this in <b>bold</b>" > print converter.transformString(html) > > Prints: > > Display this in <div class="emphatic">bold</div> > > All text not matched by a pattern in the converter is left as-is. (My > CSS style/form may not be up to date, but I hope you get the idea.) > > -- Paul Hello, Sorry for the delay in reply, and that you for the info. Though, I think either I am mis-understanding your post or its not the solution I'm looking for. How does this fit into what I'm looking to do with HTMLParser? Thanks! From philippe.martin at att.net Mon Aug 27 00:58:12 2007 From: philippe.martin at att.net (hg) Date: Mon, 27 Aug 2007 04:58:12 GMT Subject: ANN: SCF released GPL In-Reply-To: <7x3ay5d1mn.fsf@ruckus.brouhaha.com> References: <2qnAi.21495$eY.19028@newssvr13.news.prodigy.net> <7x3ay5d1mn.fsf@ruckus.brouhaha.com> Message-ID: <ERsAi.47759$Um6.7114@newssvr12.news.prodigy.net> Paul Rubin wrote: > hg <hg at nospam.org> writes: >> I am looking for a free subversion server resource to put the code >> ... if you know of any. > > Does it have to be SVN? I think Savannah and Sourceforge both still > use CVS. I'm not sure what Launchpad uses. I guess if necessary I > could set up a subversion repo for you on a server that I use. I've > been wanting to put together some GNU security tools under the name > Fort GNOX, so maybe this can be a start. Nope CVS would be fine ... I guess I've made the switch in my head. I'll check SourceForge. Thanks. hg From zyzhu2000 at gmail.com Wed Aug 1 12:11:37 2007 From: zyzhu2000 at gmail.com (beginner) Date: Wed, 01 Aug 2007 16:11:37 -0000 Subject: Awkward format string Message-ID: <1185984697.605529.157110@g12g2000prg.googlegroups.com> Hi, In order to print out the contents of a list, sometimes I have to use very awkward constructions. For example, I have to convert the datetime.datetime type to string first, construct a new list, and then send it to print. The following is an example. x=(e[0].strftime("%Y-%m-%d"), e[1].strftime("%Y-%m-%d"))+e[2:] print >>f, "%s\t%s\t%d\t%f\t%f\t%f\t%d" % x e is a tuple. x is my new tuple. Does anyone know better ways of handling this? Thanks, Geoffrey From paul at boddie.org.uk Wed Aug 8 12:08:40 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 08 Aug 2007 09:08:40 -0700 Subject: Misleading wikipedia article on Python 3? In-Reply-To: <1186583168.447608.114040@d55g2000hsg.googlegroups.com> References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <mailman.1660.1186380664.22759.python-list@python.org> <7xzm15q8fy.fsf@ruckus.brouhaha.com> <1186583168.447608.114040@d55g2000hsg.googlegroups.com> Message-ID: <1186589320.335950.142880@b79g2000hse.googlegroups.com> On 8 Aug, 16:26, Istvan Albert <istvan.alb... at gmail.com> wrote: > On Aug 6, 6:11 am, Paul Rubin <http://phr... at NOSPAM.invalid> wrote: > > > Why on earth did they make this change? It just seems gratuitous. > > Having print a function (with parameters) makes is very easy to modify > where the output goes. I'm not arguing with this. > Say you want to have some prints go to one particular file, today you > cannot easily do it, you have to either do a regex based search/ > replace or fiddle with the sys.stdout etc. both have substantial > drawbacks. Well, you could find all print statements reliably using various parsing solutions provided with Python. It's interesting that for this reason, migrating from the print statement is not particularly difficult whereas identifying invocations of the upcoming print built- in function will not be a trivial task. I'm not passing judgement on the introduction of the print function here, but I find such properties of the language very interesting - it's not too far removed from the static typing debate or people's fascination with making domain-specific languages. > A solution would be writing the code with a logging function to begin > with, alas many times that is out of one's hand. I wished print was a > function great many times. I bet Guido has had similar experiences, > note that attempt to keep print in the current form but have it print > to a file ... with that crazy syntax, print >>f, ... alas that did not > solve anything Yes, print >>f is a bit of a hack which I must admit to using occasionally. However, for every enthusiast of one approach, there will always be an enthusiast for another (see point #6): http://mechanicalcat.net/cgi-bin/log/2003/09/02#anti-pitfalls > It is time to fix it for good. Well, it has always been possible to use a logging function, just not one called "print" exactly. Paul From steve at holdenweb.com Sat Aug 18 21:25:06 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 18 Aug 2007 21:25:06 -0400 Subject: "constructor" or initialization function for module In-Reply-To: <1187484559.935316.125050@j4g2000prf.googlegroups.com> References: <1187484559.935316.125050@j4g2000prf.googlegroups.com> Message-ID: <fa865a$mq7$1@sea.gmane.org> beginner wrote: > Hi Everyone, > > An extended module (.pyd) written in C have an init function that is > called when the module is imported. Does anyone know if there is a way > to provide an init function for a module written in python? > The body of a Python module is executed the first time it is imported (that's how the functions and classes get defined: class and def statements are executable), so just put your initialization code inline. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From ladaan at iptel.org Thu Aug 23 12:27:40 2007 From: ladaan at iptel.org (Ladislav Andel) Date: Thu, 23 Aug 2007 18:27:40 +0200 Subject: comparing two lists Message-ID: <46CDB57C.9080701@iptel.org> Hi, what would be the most efficient way to do following? I have a list of dictionaries taken from DB e.g. dblist = [{'id:1, 'host':'google.com','ip_address':'1.2.3.4'}, {'id:3, 'host':'yahoo.com','ip_address':'5.6.7.8'}, {'id:9, 'host':'msn.com','ip_address':'11.3.2.3'}] and list of object instances in memory(it's just for example) which are looping within itself and testing particular hosts memlist = [<instance 1>,<instance 2>] memlist[0].id is 1 and memlist[0].host is google.com etc. memlist[1].id is 9 and memlist[1].host is msn.com etc. Now I want to add a new instance to memlist since id=3(in dblist) is not in memlist. How would you iterate through it and insert a new instance? The result should be: memlist = [<instance 1>,<instance 2>, <instance 3>] memlist[0].id is 1 and memlist[0].host is google.com etc. memlist[1].id is 3 and memlist[1].host is yahoo.com etc. memlist[2].id is 9 and memlist[2].host is msn.com etc. Furthermore, I can have the opposite situation. This time I need to remove from memlist a host which is not in dblist. How would you do this? The way how it works is that DBlist is loaded every 10 minutes and compares with memlist. The memlist should be the same as dblist. Could you help me, please? I'm working on my version of this but somebody might be quicker than me. In case I have it done I will post it. Thanks, Lada There is and wt From vinya.jag at gmail.com Thu Aug 9 02:57:34 2007 From: vinya.jag at gmail.com (Vinay Sagar Prakash) Date: Thu, 9 Aug 2007 12:27:34 +0530 Subject: Expect Telnet Message-ID: <a31681b60708082357s40bd4b28lf03fd077c0c3d9ac@mail.gmail.com> Hi all, I am not sure how this works, but am composing my query here. I am trying to expect the below snippet using telnetlib. ################# bash# install blah blah blah do you want to continue [y/n]? y blah blah blah blah blah blah blah blah blah blah blah blah Installation complete bash# ################## For the above, i am doing t.read_until("bash#") t.write("install\n") t.read_until("n]? ") t.write("y\n") t.read_until("bash#") t.write('exit\n") However, from the time i key 'y/n' till the install script exits, there is a lot of data that is to be logged. I takes around 1 hour for the whole script to exit. Is there some way i can read whats happening behind the scenes until it hits the read_until? Thanks for the help -- Vinay -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070809/614d49a6/attachment.html> From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Aug 11 17:37:07 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 11 Aug 2007 23:37:07 +0200 Subject: Public Telnet Server? References: <1186844845.304731.18300@x40g2000prg.googlegroups.com> Message-ID: <5i6og3F3mr9f4U2@mid.individual.net> Dave wrote: > Hi there. I'm a beginner at Python and I'm writing my first Python > script. It's a text adventure about coffee and mixing drinks and > being crazy and such. I keep updating it and want my friends to > beta test it for me, but some of them don't have the right version > of Python or don't want to get Python at all. Sounds like Windows users. Isn't py2exe an option? Regards, Bj?rn -- BOFH excuse #339: manager in the cable duct From afriere at yahoo.co.uk Tue Aug 28 22:22:39 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 28 Aug 2007 19:22:39 -0700 Subject: Pythonic way of reading a textfile line by line without throwing an exception In-Reply-To: <mailman.90.1188344955.28954.python-list@python.org> References: <1ab7b8470708281647g59e685ect371f20aaea30b070@mail.gmail.com> <mailman.90.1188344955.28954.python-list@python.org> Message-ID: <1188354159.471066.11470@q3g2000prf.googlegroups.com> On Aug 29, 9:49 am, "Deivys Ramirez" <deivys.rami... at gmail.com> wrote: > What's the "pythonic" way of reading a text file, line by line, > without throwing an exception when there's nothing to be read? > > I've been trying to map my while(!eof(fp)) mindset to the file object > Python gives me when I call open() but have had no good results. As the previous posts have indicated the idiomatic (and highly readable) way to read a file is simply to iterate across it. Just in case you are ever in the position of having to use .readline() directly, you might want to note that this method returns empty lines as '\n' (go figure) and the EOF simply as ''. So you test of EOF using 'if not line :' rather than anything like 'if eof :' Historically, ie. before file objects were iterables, you would have written something like this: fobj = open('foo.txt') while 1 : line = fobj.readline() if not line : break #do stuff to line fobj.close() Obviously iterating 'for line in fobj : ' is neater. From Michael.J.Fromberger at Clothing.Dartmouth.EDU Sun Aug 12 13:48:21 2007 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Sun, 12 Aug 2007 13:48:21 -0400 Subject: Regular Expression Grouping References: <1186939262.144073.182450@z24g2000prh.googlegroups.com> Message-ID: <Michael.J.Fromberger-B02D00.13482112082007@localhost> In article <1186939262.144073.182450 at z24g2000prh.googlegroups.com>, linnewbie at gmail.com wrote: > Fairly new to this regex thing, so this might be very juvenile but > important. > > I cannot understand and why 'c' constitutes a group here without being > surrounded by "(" ,")" ? > > >>>import re > >>> m = re.match("([abc])+", "abc") > >>> m.groups() > ('c',) > > Grateful for any clarity. Hello! I believe your confusion arises from the placement of the "+" operator in your expression. You wrote: '([abc])+' This means, in plain language, "one or more groups in which each group contains a string of one character from the set {a, b, c}." Contrast this with what you probably intended, to wit: '([abc]+)' The latter means, in plain language, "a single group containing a string of one or more characters from the set {a, b, c}." In the former case, the greedy property of matching attempts to maximize the number of times the quantified expression is matched -- thus, you match the group three times, once for each character of "abc", and the result shows you only the last occurrence of the matching. Compare this with the following: ] import re ] m = re.match('([abc]+)', 'abc') ] m.groups() => ('abc',) I suspect the latter is what you are after. Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From wolf_tracks at invalid.com Sun Aug 19 15:32:17 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sun, 19 Aug 2007 12:32:17 -0700 Subject: Python on Computation, Math and Statistics In-Reply-To: <5irgvaF3oi5dpU2@mid.uni-berlin.de> References: <m_%xi.34088$2v1.7394@newssvr14.news.prodigy.net> <5irgvaF3oi5dpU2@mid.uni-berlin.de> Message-ID: <DU0yi.1286$Oo.199@newssvr17.news.prodigy.net> Google? What's that? Thanks. I like to get a insider's view when I know experts are out there. So now I ask a deeper question. Are there matrix computation libraries or even statistical (regression, factor analysis) libraries? Diez B. Roggisch wrote: > W. Watson schrieb: >> I would hope Python is doing a lot of standard computations beyond >> arithmetic. Trig functions and more. Comments? > > Bad google day? > > http://docs.python.org/lib/numeric.html > > Additionally, there are several scientific extensions, like SciPy, > Numeric/Numpy and so forth. > > > Diez -- Wayne Watson (Nevada City, CA) Web Page: <speckledwithStars.net> From mail at timgolden.me.uk Fri Aug 31 08:36:20 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 31 Aug 2007 13:36:20 +0100 Subject: win32com problem: more than one instance In-Reply-To: <1188562822.741578.139370@d55g2000hsg.googlegroups.com> References: <1188562822.741578.139370@d55g2000hsg.googlegroups.com> Message-ID: <46D80B44.3050708@timgolden.me.uk> Thomas Rademacher wrote: > Hello, > > I start my script convert.py simultaneously in any dos-shells several > times. But I get every time the same solidworks instance. > I see in the proccess (task) manager only one solidworks.exe > Therefore I get for all simultaneous conversions the same output file. I *think* -- and I'm really hoping someone more knowledgeable can chip in here -- that it's down to the particular COM object implementation. ie Excel may choose to offer you separate instances (or whatever they're called) while SolidWorks may not. TJG From paul.heslop at blueyonder.co.uk Mon Aug 13 08:06:59 2007 From: paul.heslop at blueyonder.co.uk (Paul Heslop) Date: Mon, 13 Aug 2007 12:06:59 GMT Subject: Air conditioners for free!??!?!!! References: <1187002521.547470.50160@22g2000hsm.googlegroups.com> Message-ID: <46C0494D.9AEF7824@blueyonder.co.uk> fritz wrote: > > http://goodgrief -- Paul (We won't die of devotion) ------------------------------------------------------- Stop and Look http://www.geocities.com/dreamst8me/ From tenax.raccoon at gmail.com Tue Aug 28 11:27:14 2007 From: tenax.raccoon at gmail.com (Jason) Date: Tue, 28 Aug 2007 08:27:14 -0700 Subject: Check for dict key existence, and modify it in one step. In-Reply-To: <1188311810.226363.295500@w3g2000hsg.googlegroups.com> References: <1188311810.226363.295500@w3g2000hsg.googlegroups.com> Message-ID: <1188314834.777923.236070@r34g2000hsd.googlegroups.com> On Aug 28, 8:36 am, rodrigo <rodrigo... at gmail.com> wrote: > Im using this construct a lot: > > if dict.has_key(whatever): > dict[whatever] += delta > else: > dict[whatever] = 1 > > sometimes even nested: > > if dict.has_key(whatever): > if dict[whatever].has_key(someother): > dict[whatever][someother] += delta > else: > dict[whatever][someother] = 1 > else: > dict[whatever]={} > dict[whatever][someother] = 1 > > there must be a more compact, readable and less redundant way to do > this, no? > > Thanks, > > Rodrigo As Bruno said, don't shadow the built-in objects. When things inevitably go south because the dict class has been replaced by your dictionary, it will be difficult for you to find out what went wrong. Under Python 2.5, you have the defaultdict class in the collections module [1]. (This class is trivial to implement in prior versions of Python, too.) >>> from collections import defaultdict >>> myDict = defaultdict(lambda: 1) >>> myDict['spam'] = 5 >>> myDict['spam'] += 10 >>> myDict['vikings'] += 20 >>> myDict defaultdict(<function <lambda> at 0x00AAC970>, {'vikings': 21, 'spam': 15}) >>> --Jason [1] The module documentation is at "http://docs.python.org/lib/module- collections.html" From aleax at mac.com Thu Aug 30 22:54:46 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 30 Aug 2007 19:54:46 -0700 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <mailman.135.1188474634.28954.python-list@python.org> <1188495863.242815.236900@o80g2000hse.googlegroups.com> <1i3ob5k.dm3jmoqx1z68N%aleax@mac.com> <mailman.182.1188527911.28954.python-list@python.org> Message-ID: <1i3ocjx.1wnfv2po5t466N%aleax@mac.com> Ricardo Ar?oz <ricaraoz at gmail.com> wrote: ... > Alex Martelli wrote: > > <zzbbaadd at aol.com> wrote: > > ... > >> In my case of have done os.listdir() on two directories. I want to see > >> what files are in directory A that are not in directory B. > > > > So why would you care about WHERE, in the listdir of B, are to be found > > the files that are in A but not B?! You should call .index only if you > > CARE about the position. > > > > def inAnotB(A, B): > > inA = os.listdir(A) > > inBs = set(os.listdir(B)) > > return [f for f in inA if f not in inBs] > > > > is the "one obvious way to do it" (the set(...) is just a simple and > > powerful optimization -- checking membership in a set is roughly O(1), > > while checking membership in a list of N items is O(N)...). > > And what is the order of passing a list into a set? O(N)+? Roughly O(N), yes (with the usual caveats about hashing costs, &c;-). So, when A has M files and B has N, your total costs are roughly O(M+N) instead of O(M*N) -- a really juicy improvement for large M and N! Alex From kyosohma at gmail.com Tue Aug 21 13:01:05 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 21 Aug 2007 10:01:05 -0700 Subject: str().join() isn't working In-Reply-To: <1187659123.397704.195900@m37g2000prh.googlegroups.com> References: <496954360708200905i2100b32ag5983ab729e5d216f@mail.gmail.com> <mailman.4.1187633821.32294.python-list@python.org> <1187634895.387910.179500@m37g2000prh.googlegroups.com> <1187659123.397704.195900@m37g2000prh.googlegroups.com> Message-ID: <1187715665.155599.152170@j4g2000prf.googlegroups.com> On Aug 20, 8:18 pm, Asun Friere <afri... at yahoo.co.uk> wrote: > On Aug 21, 4:34 am, kyoso... at gmail.com wrote: > > > to concatenate 2 lists to each other before it does the join, ... is > > impossible in Python. The "+" operator is only for addition and for > > two or more strings. > > Really? > > >>> [1,2,3] + [4,5,6] > > [1, 2, 3, 4, 5, 6] Yeah...my bad. I was coming down with a cold when I wrote that. Mike From steve at holdenweb.com Fri Aug 31 10:59:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 31 Aug 2007 10:59:51 -0400 Subject: strings (dollar.cents) into floats In-Reply-To: <87ps14bddb.fsf@benfinney.id.au> References: <mailman.140.1188483282.28954.python-list@python.org> <877incd20i.fsf@benfinney.id.au> <46d75cf3$0$7698$9b4e6d93@newsspool2.arcor-online.net> <87ps14bddb.fsf@benfinney.id.au> Message-ID: <fb9ada$e3l$1@sea.gmane.org> Ben Finney wrote: > Wildemar Wildenburger <lasses_weil at klapptsowieso.net> writes: > >> But what use is there for floats, then? When is it OK to use them? > > When one is willing to sacrifice decimal precision for speed of > calculation, and doesn't need the numbers to stay precise. E.g. when > performing millions of calculations on real-world (analogue) > measurements. > Traditionally, mainframe computers used BCD arithmetic to handle currency, and the Decimal module is probably the best way to proceed if your Python is recent enough to include it. That isn't to say that currencies can't be handled using floating-point. The important thing then becomes to round after each calculation rather than allowing the errors to build up until they become significant enough to make a difference to the final result. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From arkanes at gmail.com Tue Aug 14 08:57:55 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 14 Aug 2007 07:57:55 -0500 Subject: wxPython before MainLoop In-Reply-To: <13c1v79hs0dob3@corp.supernews.com> References: <13bl9a75laqcm70@corp.supernews.com> <13bnh5bs4b9h427@corp.supernews.com> <5i3b1jF3n5bdtU1@mid.individual.net> <13c1v79hs0dob3@corp.supernews.com> Message-ID: <4866bea60708140557v5b2acfd1y7af068845f43c529@mail.gmail.com> On 8/13/07, [david] <david at nospam.spam> wrote: > Well yes, I have tried this app with native windows, > and I know how to do it. > I don't believe you. If you meant "I copied something that does this off of code project", that I'll believe. > But if all wxPython can offer is a poor imitation > of MFC, I'm better off using MFC aren't I? > MFC offers no special support at all for anything you're doing. wxPython actually does have some, but that may or may not be helpful since you haven't been exactly clear as to what your needs are (Show() should never be slow, and if it is you're doing something wrong) and you've got an egregiously bad attitude that cuts my interest in helping you down rather a lot. > And too all those people who wrote back to insist > that users MUST explicitly build a multi-threaded > framework for wxPython: > > It's supposed to already be a framework :~) > wxPython doesn't *need* a multi-threading framework. It's got a threadsafe way to schedule events, and the Python standard library has all the other synchronization primitives you need, including a queue. There's nothing special that needs to be done to it. Nobody told you to "build a multi-threaded framework", they told you to use the threading framework which already exists. From steve at holdenweb.com Thu Aug 2 06:32:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 02 Aug 2007 06:32:33 -0400 Subject: Wing IDE for Python v. 3.0 beta1 released In-Reply-To: <20070801224219.GD25065@spookie1.spookiegate> References: <46AF8ED7.2070206@wingware.com> <20070801212840.GA25065@spookie1.spookiegate> <f8quug$m7j$1@sea.gmane.org> <496954360708011453h2a68dee4x48dcb15bb25ea717@mail.gmail.com> <f8r0du$qhn$1@sea.gmane.org> <f8r147$rvm$1@sea.gmane.org> <20070801224219.GD25065@spookie1.spookiegate> Message-ID: <f8sbs5$8c3$1@sea.gmane.org> John K Masters wrote: > On 18:23 Wed 01 Aug , Steve Holden wrote: >> Joshua J. Kugler wrote: >>> On Wednesday 01 August 2007 13:53, Robert Dailey wrote: >>>> He's secretly an employee of Wing IDE in disguise!!! >>> Sorry to destroy your conspiracy theories, but no, I've never been employed >>> by Wing IDE in any fashion, nor have I ever received any monetary >>> compensation from them in any form. Just a satisfied user. That's all. >>> >>> j >>> >> Me too, and I have to say the response I have had to all my technical >> support requests has been first-class. Maybe they are busy because >> they're in beta? I know they aren't the largest company, but they can >> stand comparison with most when it comes to support. >> >> I can't think of any other products I use where you can contact the >> support team from right inside the software. And get answers without >> paying per-incident support fees! >> >> regards >> Steve >> -- > > I am happy to hear that you have had a good experience with wingide and > I wish I could say the same as I have found the product to be excellent > as far as the concept goes but lacking in the implementation. > > To suggest that, because the autocompletion worked on one method of a > module and not on another was because I had not configured the > PYTHONPATH properly is at least insulting. > > Regards, John We must all be guided by personal experience, I suppose. Personally I wouldn't get insulted if someone suggested I might have made a mistake, since I have made enough in my life to recognize it as a pattern. Problem identification has to start with the most likely causes. I am sure that had you written back to say you had checked the PYTHONPATH and were still looking for the problem cause they would have answered you civilly and with other possible causes. regards steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From jstroud at mbi.ucla.edu Sat Aug 4 00:06:10 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 03 Aug 2007 21:06:10 -0700 Subject: How to pass a reference to the current module In-Reply-To: <mailman.1600.1186193779.22759.python-list@python.org> References: <f90gsg$ek4$1@zinnia.noc.ucla.edu> <mailman.1597.1186189477.22759.python-list@python.org> <f90ktr$hic$1@zinnia.noc.ucla.edu> <mailman.1600.1186193779.22759.python-list@python.org> Message-ID: <f90tvj$nt7$1@zinnia.noc.ucla.edu> Carsten Haese wrote: > On Fri, 2007-08-03 at 18:31 -0700, James Stroud wrote: >>Carsten Haese wrote: >>You sound like my former thesis adviser. > > > Thanks. I guess. Yes, its a compliment in disguise--just check his CV. >>OK. From an external source, such as configuration file, the user will >>specify the *name* of a function somehow with the assumption that the >>function will be coded somewhere (in the present or other modules) by >>that name. > > Does the configuration file indicate which module contains the function? > It is possible. Please see my latest response to Paul Rubin. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From hyugaricdeau at gmail.com Wed Aug 22 10:22:28 2007 From: hyugaricdeau at gmail.com (Hyuga) Date: Wed, 22 Aug 2007 14:22:28 -0000 Subject: How to optimise this code? In-Reply-To: <mailman.105.1187772731.32294.python-list@python.org> References: <mailman.68.1187711977.32294.python-list@python.org> <faf33r$rb8$01$1@news.t-online.com> <1187750385.511936.318560@i13g2000prf.googlegroups.com> <mailman.105.1187772731.32294.python-list@python.org> Message-ID: <1187792548.846045.14040@l22g2000prc.googlegroups.com> On Aug 22, 4:52 am, "David N Montgomery" <monty.pyt... at fastmail.fm> wrote: > unittest is the best choice for my needs and works perfectly in Eclipse. > Unfortunately though it (and many other things) does not work under the > application we have to use to run our python scripts. > > This leaves me with 'functionToCall = getattr(self, "testCase%s" % tc)'. > This achieves the optimisation/simplification I had been looking for. > > Thank you once again. Just out of curiosity, what about your environment prevents you from using unittest? Hyuga From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Aug 19 17:32:17 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 19 Aug 2007 23:32:17 +0200 Subject: Hot subject: a good python editor and/or IDE? References: <mailman.2162.1187525764.22759.python-list@python.org> <5iqreuF3qanv6U1@mid.individual.net> <mailman.2166.1187530711.22759.python-list@python.org> Message-ID: <5irr71F3r2m8aU1@mid.individual.net> Buchoux S?bastien wrote: > Yeah, I know this is a FAQ, but, as you mention, there is a whole > bunch of editors, every one of them being updated constantly (+ > the new ones getting out). Are you really sure that you know the meaning of the word "frequently"? > So I am quite sure that looking through the archives is THE > solution since it will only reflect what people thought when > question was asked. Just type "best Python editor" on Google and > you will see that almost all hits are completely out of date. Fair > enough though! ;) I spoke of this MAILING LIST'S ARCHIVES, not of some web forum you'll get with google. Bj?rn -- BOFH excuse #119: evil hackers from Serbia. From carsten at uniqsys.com Fri Aug 10 00:25:34 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 10 Aug 2007 00:25:34 -0400 Subject: accessing static attributes In-Reply-To: <1186714304.352882.40520@j4g2000prf.googlegroups.com> References: <1186714304.352882.40520@j4g2000prf.googlegroups.com> Message-ID: <20070810040618.M49202@uniqsys.com> On Fri, 10 Aug 2007 02:51:44 -0000, james_027 wrote > hi, > > for example an request object ... is request.user the same as > request.__class__.user? Not in general: >>> class Request(object): ... user = "somebody" ... >>> request = Request() >>> request.user == request.__class__.user True >>> request.user = "nobody" >>> request.user == request.__class__.user False -- Carsten Haese http://informixdb.sourceforge.net From richardlev at gmail.com Fri Aug 10 21:26:14 2007 From: richardlev at gmail.com (Richard Levasseur) Date: Sat, 11 Aug 2007 01:26:14 -0000 Subject: Extending logging module In-Reply-To: <1186675688.291944.299060@z24g2000prh.googlegroups.com> References: <1186675688.291944.299060@z24g2000prh.googlegroups.com> Message-ID: <1186795574.657771.42170@x40g2000prg.googlegroups.com> On Aug 9, 9:08 am, jay <titleistf... at gmail.com> wrote: > Hello, > > I've been using the python logging module a lot lately, and I've come > across an instance where I need some new levels. Specifically, python > does not include ALERT and NOTICE in the default set of logging > levels. I am wondering how trivial it would be to extend the logging > module to include these 2 levels that are standard with syslog? > > My first test was just to use the addLevelName method to add the two > new levels, but syslog ignores them and logs at the next highest > priority, no matter what I use. > > Looking further into the code and as a test, I changed the following > to see if this would even work > > lib/python2.5/logging/__init__.py > -> class Logger > -> add new notice and alert root level functions > -> new _levelNames for notice and alert > -> new default level names for notice and alert > > lib/python2.5/logging/handlers.py > -> class SysLogHandler priority_map was changed to include notice > and alert > > It actually worked, but this is not the way I would like to handle the > problem. I would prefer to extend the classes instead. However, I'm > not too familiar with that, and I had to change things in so many > places, I'm wondering if its even possible? I don't like changing the > standard libraries, what happens if I have to upgrade python? My > changes get overwritten. > > Can anyone offer some help or suggestions? Thanks > > Jay Try looking at module new, i did the same to add a 'profile' level. If push comes to shove, you can always wrap your logger object up or access the __dict__ directly. http://docs.python.org/lib/module-new.html hope this helps, richard From rcdailey at gmail.com Wed Aug 1 17:53:29 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 1 Aug 2007 16:53:29 -0500 Subject: Wing IDE for Python v. 3.0 beta1 released In-Reply-To: <f8quug$m7j$1@sea.gmane.org> References: <46AF8ED7.2070206@wingware.com> <20070801212840.GA25065@spookie1.spookiegate> <f8quug$m7j$1@sea.gmane.org> Message-ID: <496954360708011453h2a68dee4x48dcb15bb25ea717@mail.gmail.com> He's secretly an employee of Wing IDE in disguise!!! On 8/1/07, Joshua J. Kugler <joshua at eeinternet.com> wrote: > > On Wednesday 01 August 2007 13:28, John K Masters wrote: > > > On 15:34 Tue 31 Jul , Wingware wrote: > >> Hi, > >> > >> I'm happy to announce the first beta release of Wing IDE 3.0. It is > >> available from http://wingware.com/wingide/beta > > If their support for paid customers is anything like their support for > > prospective customers then I would leave well alone. > > I've had excellent support from them. I'm sorry to hear your experiences > have not been stellar. Questions submitted to the bug or comment list > usually get a response in one day or less. And there are frequently > respones by WingWare people to just about every question asked on the > WingWare mailing list. > > > I have been trying wing for a few days but have noticed that > > auto-completion does not work on all modules. I submitted this to wing > > and was told that probably my PYTHONPATH was wrong. > > It may also not work if the IDE isn't sure what kind of object you are > dealing with. You can "clarify" this as documented with an > assert(isinstance()) statement. > > > I subsequently submitted a question about the licensing, i.e. whether I > > could use wing on a home setup using Debian Etch, where I develop my > > apps, and a work setup, using Debian Etch, with no net access. > > From http://www.wingware.com/wingide/license: > > "Each Wing IDE user may run Wing on as many machines as needed for their > own > work, for all the operating systems which they have licensed. In order to > reduce casual license sharing, which is a unfortunately a problem for > small > businesses like Wingware, licenses must be activated after installation on > each machine." > > "We've worked hard to make this flexible and forgiving for valid > customers. > For example, reinstalling an OS and/or altering hardware usually should > not > break your activation. Also, activation can be done directly from Wing IDE > and off-line activation is available if your machine does not have TCP > port > 80 (http) access to wingware.com. Each license is allowed three > activations > by default and more can be obtained on request from identifiable > customers." > > > So far I have had no response > > I tend to let questions slide when they are answered in the documentation > or > on the web site. Maybe the Wing developers/support personnel are the same > way. > > j > > -- > Joshua Kugler > Lead System Admin -- Senior Programmer > http://www.eeinternet.com > PGP Key: http://pgp.mit.edu/ ID 0xDB26D7CE > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070801/513408a8/attachment.html> From conspiracy.black6 at gmail.com Mon Aug 6 14:22:57 2007 From: conspiracy.black6 at gmail.com (conspiracy.black6 at gmail.com) Date: Mon, 06 Aug 2007 18:22:57 -0000 Subject: Conspiracies Revealed! Shadow governments Message-ID: <1186424577.505694.105290@r34g2000hsd.googlegroups.com> http://nasaconspiracy.net/conspiracy - Find out who really shot JFK!, learn how they faked the lunar landing, see what they are putting in our milk to enlarge young womens breasts in a goal to raise the declining birth rate. Proof of extraterrestrial life and much more revealed here. From sebzzz at gmail.com Wed Aug 8 13:06:37 2007 From: sebzzz at gmail.com (sebzzz at gmail.com) Date: Wed, 08 Aug 2007 10:06:37 -0700 Subject: Removing tags with BeautifulSoup Message-ID: <1186592797.471030.308410@l70g2000hse.googlegroups.com> Hi, I'm in the process of cleaning some html files with BeautifulSoup and I want to remove all traces of the tables. Here is the bit of the code that deals with tables: def remove(soup, tagname): for tag in soup.findAll(tagname): contents = tag.contents parent = tag.parent tag.extract() for tag in contents: parent.append(tag) remove(soup, "table") remove(soup, "tr") remove(soup, "td") It works fine but leaves an empty table structure at the end of the soup. Like: <table> <tr> <td></td> </tr> <tr> <td></td> </tr> <tr> ... And the extract method of BeautifulSoup seems the extract only what is in the tags. So I'm just looking for a quick and dirty way to remove this table structure at the end of the documents. I'm thinking with re but there must be a way to do it with BeautifulSoup, maybe I'm missing something. An other thing that makes me wonder, this code: for script in soup("script"): soup.script.extract() Works fine and remove script tags, but: for table in soup("table"): soup.table.extract() Raises AttributeError: 'NoneType' object has no attribute 'extract' Oh, and BTW, when I extract script tags this way, all the tag is gone, like I want it, it doesn't only removes the content of the tag. Thanks in advance From bignose+hates-spam at benfinney.id.au Sat Aug 25 02:20:12 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 25 Aug 2007 16:20:12 +1000 Subject: Online documentation split onto many small pages (was: py2exe/distutils: how to include a tree of files?) References: <13cuhdr58m5one7@corp.supernews.com> <13cukd39lgsfgb4@corp.supernews.com> <1188000252.290854.289870@q4g2000prc.googlegroups.com> <13cv0jpdot6fo20@corp.supernews.com> Message-ID: <87absgjftv.fsf_-_@benfinney.id.au> Grant Edwards <grante at visi.com> writes: > I don't really understand what the advantage for splitting up > documentation into screen-sized chunks is supposed to be -- all the > web browsers I've ever seen can scroll. The issue is the time to download the page. Most of the world does not have fast internet access. > One page per module or chapter sure would make it easier to > search... Fortunately online documentation in multiple HTML pages is indexable by the major search engines; most of those can search within one domain, or even within one path prefix of a domain. -- \ "Listen: we are here on Earth to fart around. Don't let anybody | `\ tell you otherwise." -- _Timequake_, Kurt Vonnegut | _o__) | Ben Finney From programmer.py at gmail.com Tue Aug 14 12:55:04 2007 From: programmer.py at gmail.com (programmer.py at gmail.com) Date: Tue, 14 Aug 2007 16:55:04 -0000 Subject: module: zipfile.writestr - line endings issue In-Reply-To: <1187107452.905165.45700@l70g2000hse.googlegroups.com> References: <1187107452.905165.45700@l70g2000hse.googlegroups.com> Message-ID: <1187110504.154878.317460@19g2000hsx.googlegroups.com> On Aug 14, 11:04 am, towers <damondo... at googlemail.com> wrote: > Hi > > I'm probably doing something stupid but I've run into a problem > whereby I'm trying to add a csv file to a zip archive - see example > code below. > > The csv just has several rows with carriage return line feeds (CRLF). > > However after adding it to an archive and then decompressing the line > endings have been converted to just line feeds (LF). > > Does anyone know if this is a bug or am I just doing something wrong? > > Many Thanks, > Damon > > **************************************************************************** > import zipfile > > zipFile = zipfile.ZipFile('LocalZipFile.zip', 'a', > zipfile.ZIP_DEFLATED) > dfile = open('LocalCSVFile.csv', 'r') > zipFile.writestr('test.csv',dfile.read()) > dfile.close() > zipFile.close() > **************************************************************************** Line endings will drive you up the wall. Anyway, the python zipfile library does not seem to be doing any translations. The code below works for me. # begin code import zipfile import os.path # First create some work data... csv_data = '1,2\r\n3,4\r\n5,6\r\n' # Now, create the zipfile zip_file = zipfile.ZipFile(r'c:\tmp\test.zip', 'w', zipfile.ZIP_DEFLATED) zip_file.writestr('test.csv',csv_data) zip_file.close() # Now, extract the info zip_file = zipfile.ZipFile(r'c:\tmp\test.zip') assert len(zip_file.read('test.csv')) == len(csv_data) # end code Something else must be tweaking your line endings. HTH! jw From johnmasters at oxtedonline.net Wed Aug 15 18:15:12 2007 From: johnmasters at oxtedonline.net (John K Masters) Date: Wed, 15 Aug 2007 23:15:12 +0100 Subject: replacement for string.printable In-Reply-To: <5ih0vlF3mc1akU2@mid.uni-berlin.de> References: <mailman.2026.1187204186.22759.python-list@python.org> <5ih0vlF3mc1akU2@mid.uni-berlin.de> Message-ID: <20070815221512.GB9275@spookie1.spookiegate> On 19:03 Wed 15 Aug , Marc 'BlackJack' Rintsch wrote: > On Wed, 15 Aug 2007 19:56:01 +0100, John K Masters wrote: > > > From what I have read the string module is obsolete and [???] > > The `string` module isn't obsolete. It even contains a more or less > recent new addition: `Template`. Only the functions that are also > available as methods on `str` are deprecated. > > Ciao, > Marc 'BlackJack' Rintsch > -- > http://mail.python.org/mailman/listinfo/python-list help('string') DESCRIPTION Warning: most of the code you see here isn't normally used nowadays. Beginning with Python 1.6, many of these functions are implemented as methods on the standard string object. They used to be implemented by a built-in module called strop, but strop is now obsolete itself. <quote> Beginning with Python 1.6 </quote> We are now way past 1.6. Are you sure the string module is still being added to? Regards, John -- War is God's way of teaching Americans geography Ambrose Bierce (1842 - 1914) From bj_666 at gmx.net Wed Aug 29 10:08:04 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 29 Aug 2007 14:08:04 GMT Subject: What's the difference ? References: <1188394767.333396.129020@r29g2000hsg.googlegroups.com> Message-ID: <5jlcu4F31aaU2@mid.uni-berlin.de> On Wed, 29 Aug 2007 13:39:27 +0000, Alex wrote: > Hye, > > I was just wondering what is the difference between > >>> if my_key in mydict: >>> ... > > and > >>> if mydict.has_keys(my_key): >>> ... > > I've search a bit in the python documentation, and the only things I > found was that they are "equivalent". > > But in this (quiet old) sample ( "http://aspn.activestate.com/ASPN/ > Cookbook/Python/Recipe/59875" ), there is difference between the two > notation. The comments in this recipes source code are misleading. Difference is not the ``in`` but that it is used on ``another_dict.keys()`` in the "bad" example. That is a linear search on a list with all keys instead asking the dictionary directly like you did above. The difference in your code above is that ``in`` works on other types too that implement `__contains__()`, like lists or sets for example, and that it is a bit faster as the second example has to look up the `has_key()` method on the object first. Ciao, Marc 'BlackJack' Rintsch From jcd at sdf.lonestar.org Wed Aug 22 11:35:40 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Wed, 22 Aug 2007 11:35:40 -0400 Subject: for statement on empty iterable In-Reply-To: <slrnfcoam7.14g.horpner@FIAD06.norwich.edu> References: <1187760507.951994.50310@q4g2000prc.googlegroups.com> <7xabsk3zgm.fsf@ruckus.brouhaha.com> <1187761270.713307.224570@i38g2000prf.googlegroups.com> <7xejhw15r9.fsf@ruckus.brouhaha.com> <1187761957.636211.107060@x40g2000prg.googlegroups.com> <7xd4xgnldp.fsf@ruckus.brouhaha.com> <1187765372.361411.249990@z24g2000prh.googlegroups.com> <5j2679F3s7lbpU1@mid.uni-berlin.de> <slrnfcoam7.14g.horpner@FIAD06.norwich.edu> Message-ID: <46CC57CC.4060101@sdf.lonestar.org> Neil Cerutti wrote: > On 2007-08-22, Diez B. Roggisch <deets at nospam.web.de> wrote: > >> While it is desireable to not only write working, but also >> aesthetically pleasing code, as a beginner you shouldn't worry >> too much. The sense of aesthetics develops with time. Important >> is to try and grasp the idioms of the language, around here >> ofter referred to as "beeing pythonic." >> > > It's hard to keep up with the new buzzwords that keep popping up > in this group. > > Ouch. That stings. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070822/a0665454/attachment.html> From steve at holdenweb.com Thu Aug 2 08:42:44 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 02 Aug 2007 08:42:44 -0400 Subject: Use variable in regular expression In-Reply-To: <1186051401.122847.114690@d55g2000hsg.googlegroups.com> References: <1186051401.122847.114690@d55g2000hsg.googlegroups.com> Message-ID: <46B1D144.8060108@holdenweb.com> CarpeSkium at gmail.com wrote: > I know I can use a variable in regular expressions. I want to use a > regex to find something based on the beginning of the string. I am > using yesterday's date to find all of my data from yesterday. > Yesterday's date is 20070731, and assigned to the variable > "yesterday_date". I want to loop thru a directory and find all of the > yesterday's data ONLY IF the feature class has the date at the > BEGINNING of the filename. > > Sample strings: > 20070731_test1 > Copy20070731_test1 > 20070731_test2 > Copy20070731_test2 > 20070731_test3 > Copy20070731_test3 > > I don't want the one's that start with "Copy". I can't figure out the > syntax of inserting the "^" into the regex. I've tried all of the > following, with no luck: > > re.compile(^yesterday_date) > re.compile(r'^yesterday_date') > re.compile(r'^[yesterday_date]') > re.compile(r'[^yesterday_date]') > > I don't know what I'm doing and I'm just guessing at this point. Can > anyone help? Thanks. > As is often the case, taking a larger look at the problem can reveal that Python has features that can help you without even getting down to more complex stuff. You appear to require a list of the files whose names begin with a string representation of yesterday's date. If you take a look at the glob module you will see that it has a glob() function, and if you were to call it as names = glob.glob(yesterday_date + "*") it would return a list of the names of the files you are interested in. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From ldo at geek-central.gen.new_zealand Sat Aug 25 08:39:40 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 26 Aug 2007 00:39:40 +1200 Subject: curses library References: <mailman.1980.1187115104.22759.python-list@python.org> Message-ID: <fap7po$tr0$1@lust.ihug.co.nz> In message <mailman.1980.1187115104.22759.python-list at python.org>, Ghirai wrote: > I need to write a console application. Why not just use VT100 escape sequences directly? Terminal emulators don't support anything else. From thomas.rademacher at nikocity.de Fri Aug 31 08:20:22 2007 From: thomas.rademacher at nikocity.de (Thomas Rademacher) Date: Fri, 31 Aug 2007 05:20:22 -0700 Subject: win32com problem: more than one instance Message-ID: <1188562822.741578.139370@d55g2000hsg.googlegroups.com> Hello, I start my script convert.py simultaneously in any dos-shells several times. But I get every time the same solidworks instance. I see in the proccess (task) manager only one solidworks.exe Therefore I get for all simultaneous conversions the same output file. I tested the same code with excel (test_excel.py) and her I get many instances of excel in proccess (task) manager. How can I get many instances of solidworks? Is it a problem of python? Or is it a problem of the Solidworks-COM-Implemention and I get the same problem with an C++ client implementation? Thanks for your help, Thomas convert.py import pythoncom pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) sldworks = gencache.EnsureModule('{83A33D31-27C5-11CE- BFD4-00400513BB57}', 0x0, 13, 0) sw = sldworks.ISldWorks(DispatchEx('SldWorks.Application')) swmodel, errors, warnings = sw.OpenDoc6(sourceName, constants.swDocPART, constants.swOpenDocOptions_Silent, "") activeDoc = sw.ActiveDoc retval, errors, warnings = swmodel.SaveAs4(targetName, constants.swSaveAsCurrentVersion , constants.swOpenDocOptions_Silent ) pythoncom.CoUninitialize() test_excel.py import pythoncom pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) myExcel = win32com.client.DispatchEx('Excel.Application') myExcel.Visible = 1 Excel = myExcel.Workbooks.Open(excelfile, 0, False, 2) Excel.Saved = 1 Excel.Close() myExcel.Quit() del myExcel del Excel pythoncom.CoUninitialize() From evan at yelp.com Tue Aug 28 11:43:12 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 28 Aug 2007 08:43:12 -0700 Subject: Check for dict key existence, and modify it in one step. In-Reply-To: <1188311810.226363.295500@w3g2000hsg.googlegroups.com> References: <1188311810.226363.295500@w3g2000hsg.googlegroups.com> Message-ID: <1188315792.6440.3.camel@thinkpad> On Tue, 2007-08-28 at 14:36 +0000, rodrigo wrote: > Im using this construct a lot: > > if dict.has_key(whatever): > dict[whatever] += delta > else: > dict[whatever] = 1 In Python 2.5 there's a defaultdict class, otherwise you can subclass dict like this: class CountingDictionary(dict): def increment(self, key, delta=1): self[key] = self.get(key, 0) + delta Hope this helps! -- Evan Klitzke <evan at yelp.com> From pacman128 at gmail.com Wed Aug 15 08:39:22 2007 From: pacman128 at gmail.com (Paul Carter) Date: Wed, 15 Aug 2007 12:39:22 -0000 Subject: module: zipfile.writestr - line endings issue In-Reply-To: <1%xwi.1232$4w7.433@newssvr22.news.prodigy.net> References: <1187107452.905165.45700@l70g2000hse.googlegroups.com> <1187110504.154878.317460@19g2000hsx.googlegroups.com> <1187112768.095414.223640@w3g2000hsg.googlegroups.com> <1187120956.574400.99170@g4g2000hsf.googlegroups.com> <1%xwi.1232$4w7.433@newssvr22.news.prodigy.net> Message-ID: <1187181562.451366.311840@r29g2000hsg.googlegroups.com> On Aug 15, 3:33 am, Suresh Babu Kolla <kollasb+n... at gmail.com> wrote: > Paul Carter wrote: > > > The problem is with how you are opening the file. You need to open in > > binary mode if you wish to read your file unaltered. Also, file() is > > preferred over open() these days I think. Use: > > > dfile = file('test.csv', 'rb') > > From Python 2.5 library documentation. > > <quote> > When opening a file, it's preferable to use `open()' instead of > invoking this constructor directly. `file' is more suited to type > testing (for example, writing `isinstance(f, file)'). > </quote> > > Python documentation seem to recommend using open(). I personally prefer > to use open, just because python open has same signature as POSIX open, > even beginner programmers can understand the intent of the code clearly. > > Kolla Yeah, you're right. I know I had read that file() was preferred somewhere, but obviously it wasn't a good source. Thanks for the correction! -- Paul From hyugaricdeau at gmail.com Thu Aug 2 12:26:43 2007 From: hyugaricdeau at gmail.com (Hyuga) Date: Thu, 02 Aug 2007 16:26:43 -0000 Subject: i am new to python-Please somebody help In-Reply-To: <pan.2007.08.02.12.51.13.363293@REMOVE.THIS.cybersource.com.au> References: <1186047103.673871.150460@z24g2000prh.googlegroups.com> <pan.2007.08.02.12.51.13.363293@REMOVE.THIS.cybersource.com.au> Message-ID: <1186072003.352710.68310@e16g2000pri.googlegroups.com> On Aug 2, 8:51 am, Steven D'Aprano <st... at REMOVE.THIS.cybersource.com.au> wrote: > On Thu, 02 Aug 2007 09:31:43 +0000, cool.vimalsmail wrote: > > [snip] > > You would be better off actually writing a sensible subject line instead > of grovelling. > > Subject: How to use gzip in Python? [beginner] > > Then, having written a good subject line, it might have suggested a good > search string for Google: "gzip python" > > http://www.google.com.au/search?&q=gzip+python > > The first two links found will answer your question. > > -- > Steven. <OT> Unlike gregarican, I mostly agree with the content of your post. Except for your subject line suggestion. Why on earth would you recommend someone use the obnoxious "How to ______ ?" question format? Yes, I know it's extremely common, but it's completely nonsensical English. Just try saying it out loud with an inquiring inflection on the last word. Sounds ridiculous doesn't it? At least without the question mark it means that the thread is on the topic of "How to _____". </OT> From rschroev_nospam_ml at fastmail.fm Sat Aug 11 13:21:28 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 11 Aug 2007 17:21:28 GMT Subject: Augmented assignment (was Re: Something in the function tutorial confused me.) In-Reply-To: <f9khib$kvq$1@panix3.panix.com> References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <m3hvi.37606$G23.6240@newsreading01.news.tds.net> <f9kdpq$drp$1@panix3.panix.com> <bAjvi.47120$wv5.1434653@phobos.telenet-ops.be> <f9khib$kvq$1@panix3.panix.com> Message-ID: <semvi.47351$Wo7.893986@phobos.telenet-ops.be> Aahz schreef: >>>> def foo(bar): bar[0] += ['zap'] > ... >>>> import dis >>>> dis.dis(foo) > 1 0 LOAD_FAST 0 (bar) > 3 LOAD_CONST 1 (0) > 6 DUP_TOPX 2 > 9 BINARY_SUBSCR > 10 LOAD_CONST 2 ('zap') > 13 BUILD_LIST 1 > 16 INPLACE_ADD > 17 ROT_THREE > 18 STORE_SUBSCR > 19 LOAD_CONST 0 (None) > 22 RETURN_VALUE > > Notice the critical sequence: BINARY_SUBSCR, INPLACE_ADD, STORE_SUBSCR. > It has to work that way to allow this: > >>>> l = [7] >>>> l[0] += 1 >>>> l > [8] > > There's simply no way to get augmented assignment to work correctly with > both lists and tuples when you allow both mutable and immutable elements. > Someone will always get surprised, and overall with strings and numbers > being the canonical list elements, I think making augmented assignment > work correctly with lists and immutables was the best decision. Thank you, I get it now. With that disassembled code in mind I had another look at the relevant section in the Language Reference; now I have a much better understanding of what's really happening. I used to interpret the target in 'The target is only evaluated once' more like an L-value in C/C++. That's not correct, of course, but I didn't understand exactly how wrong it was until now. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From ninja.krmenadl at nes.com Tue Aug 21 12:37:32 2007 From: ninja.krmenadl at nes.com (Boris Ozegovic) Date: Tue, 21 Aug 2007 18:37:32 +0200 Subject: I Need help from all the group participants References: <fac7nj$ci9$1@localhost.localdomain> <s1Eyi.6409$r5.4111@fe111.usenetserver.com> Message-ID: <faf4bh$kkp$1@localhost.localdomain> Aaron wrote: [...] > Good luck. Thanks a lot for your help. -- Ne dajte da nas la?ljivac Bandi? truje: http://cnn.blog.hr/arhiva-2007-06.html#1622776372 From jmtulloss at gmail.com Thu Aug 9 22:12:33 2007 From: jmtulloss at gmail.com (Justin T.) Date: Fri, 10 Aug 2007 02:12:33 -0000 Subject: Threaded Design Question In-Reply-To: <1186709917.157105.310050@g12g2000prg.googlegroups.com> References: <1186683909.797328.68770@i13g2000prf.googlegroups.com> <1186686575.192491.82820@e16g2000pri.googlegroups.com> <1186709917.157105.310050@g12g2000prg.googlegroups.com> Message-ID: <1186711953.893176.95300@e16g2000pri.googlegroups.com> > approach. That sounds the easiest, although I'm still interested in > any idioms or other proven approaches for this sort of thing. > > ~Sean Idioms certainly have their place, but in the end you want clear, correct code. In the case of multi-threaded programming, synchronization adds complexity, both in code and concepts, so figuring out a clean design that uses message passing tends to be clearer and more robust. Most idioms are just a pattern to which somebody found a simple, robust solution, so if you try to think of a simple, robust solution, you're probably doing it right. Especially in trivial cases like the one above. Justin From wollez at gmx.net Fri Aug 10 07:38:28 2007 From: wollez at gmx.net (WolfgangZ) Date: Fri, 10 Aug 2007 13:38:28 +0200 Subject: subprocess.Popen(cmd) question In-Reply-To: <f9h9fa$3i8$1@sea.gmane.org> References: <f9h9fa$3i8$1@sea.gmane.org> Message-ID: <f9hink$a0$1@sea.gmane.org> WolfgangZ schrieb: > Hello, > > I'm starting some subprocesses inside a loop. The processes run > independent and dont need any communication between each other. Due to > memory issues I need to limit the number of running processes to around > 10. How can I insert a break into my loop to wait until some processes > are finished? > > Some minimal examplecode: > > import subprocess > for i in range(0,100): > cmd='ping localhost' > p=subprocess.Popen(cmd) > p.wait() > > Thanks for any ideas. > > Wolfgang > Problem solved by using "threading" Wolfgang From ca.allen at gmail.com Fri Aug 3 13:00:15 2007 From: ca.allen at gmail.com (Chris Allen) Date: Fri, 03 Aug 2007 10:00:15 -0700 Subject: Global package variable, is it possible? Message-ID: <1186160415.065108.139160@e9g2000prf.googlegroups.com> Hello fellow pythoneers. I'm stumped on something, and I was hoping maybe someone in here would have an elegant solution to my problem. This is the first time I've played around with packages, so I'm probably misunderstanding something here... Here's what I'd like to do in my package. I want my package to use a configuration file, and what I'd like is for the config file to appear magically in each module so I can just grab values from it without having to load and parse the config file in each package module. Not quite understanding how the __init__.py file works, I expected it to be as easy as just setting up the ConfigParser object and then I figured (since a package is a module) that it would now be global to my package and I could access it in my modules, but I was wrong... I don't want to have to pass it in to each module upon init, or anything lame like that. A main reason for this is that I'd like to be able to reload the config file dynamically and have all my modules automatically receive the new config. There must be a way to do this, but seeing how __init__.py's namespace is not available within the package modules, I don't see a simple and elegant way to do this. Does anybody have any suggestions? Thanks! From sbellon at sbellon.de Thu Aug 2 08:19:06 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Thu, 2 Aug 2007 14:19:06 +0200 Subject: Catching SystemExit in C API code when embedding Python? Message-ID: <20070802141906.2581c099@cube.tz.axivion.com> Hi all! I am embedding Python into a GUI application in a way that the GUI is scriptable using Python. Now I have come to a problem that when the user puts a "sys.exit(0)" into his script to end the script, not only the script is terminated, but also the GUI application itself. This is not the intended behaviour. As in Python itself you can catch SystemExit, I think this should be the way to go. But how do I catch this exception from within the C API? Thanks in advance for any hints. -- Stefan Bellon From coolmann123 at hotmail.com Sat Aug 11 19:14:50 2007 From: coolmann123 at hotmail.com (Hasipups) Date: Sat, 11 Aug 2007 16:14:50 -0700 Subject: New Programms for free Message-ID: <1186874090.159064.85290@22g2000hsm.googlegroups.com> http://www.pennergame.de/ref.php?uid=5572 From ptmcg at austin.rr.com Fri Aug 17 10:53:20 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 17 Aug 2007 07:53:20 -0700 Subject: Naming dictionaries recursively In-Reply-To: <1187354296.177606.273300@22g2000hsm.googlegroups.com> References: <1187354296.177606.273300@22g2000hsm.googlegroups.com> Message-ID: <1187362400.939540.40650@w3g2000hsg.googlegroups.com> On Aug 17, 7:38 am, TYR <a.harrow... at gmail.com> wrote: > I'd like to do something like this; iterate through a file which > consists of data stored in dictionary format, one dict on each line, > and read each line into a new dict using one of the values in the dict > as its name... > > for example: > > stuff = open('data.txt') > for eachLine in stuff: > name{} > name = eachLine > ....and then do something clever to extract the value of the key > (name) from the line and use it as the dictionary's name. > > A line from data.txt would look like this: {'name' : Bob, 'species' : > Humboldt, 'colour' : red, 'habits' : predatory}. Aim is to call one of > them by name, and merge the values in that dictionary into a string > pulled from another source. Pyparsing includes an example that is very similar to this. Here is that example adapted to your specific data: from pyparsing import * line = """{'name' : Bob, 'species' : Humboldt, 'colour' : red, 'habits' : predatory}""" LBRACE,RBRACE,COLON,COMMA = map(Suppress,"{}:,") key = sglQuotedString.setParseAction(removeQuotes) value = OneOrMore(Word(alphanums))\ .setParseAction(keepOriginalText) entry = Group(key + COLON + empty + value) lineExpr = LBRACE + Dict(delimitedList(entry)) + RBRACE parsedData = lineExpr.parseString(line) # some examples of accessing the parsed data print "Keys:", parsedData.keys() print parsedData.name print parsedData.colour print "Name: %(name)s \nSpecies: %(species)s \n" \ "Colour: %(colour)s \nHabits: %(habits)s" % parsedData Prints: Keys: ['colour', 'habits', 'name', 'species'] Bob red Name: Bob Species: Humboldt Colour: red Habits: predatory -- Paul From getelectronic at gmail.com Wed Aug 8 10:23:03 2007 From: getelectronic at gmail.com (getgroup) Date: Wed, 08 Aug 2007 07:23:03 -0700 Subject: making a opc client in Python and use opc server Events In-Reply-To: <1186496239.764001.259880@57g2000hsv.googlegroups.com> References: <1180949568.305737.175350@n4g2000hsb.googlegroups.com> <1183042522.949829.19840@m36g2000hse.googlegroups.com> <1186496239.764001.259880@57g2000hsv.googlegroups.com> Message-ID: <1186582983.518428.262180@b79g2000hse.googlegroups.com> On 7 ao?t, 07:17, jp.eugs... at googlemail.com wrote: > On 28 juin, 16:55, jp.eugs... at googlemail.com wrote: > > > > > > > On 4 juin, 11:32, getelectro... at gmail.com wrote: > > > > Hi all > > > I have a sample code to implementopcclientinPython. i use a > > > file .py making by makepy with pythonwin for Com Interface. > > > i can get all server in machine, connect to serveropc, disconnect, > > > add group, add item, read, write item in serveropc. > > > > import win32com.client # librairie pour utiliser l'interface COM/DCOM > > > from win32com.clientimport gencache > > > gencache.EnsureModule('{DFB83232-A952-11D2-A46B-00C04F796375}', 0, 1, > > > 0) > > > > for svr in opcserver.GetOPCServers(): > > > print svr > > > > #connect to serverOPCDemo Simulation from Matrikon > > > opcserver.Connect('Matrikon.OPC.Simulation.1') > > > > # Instance object Groups > > > groups=opcserver.OPCGroups > > > #add group > > > group=groups.Add('Group1') > > > > #instance onject Items > > > items=group.OPCItems > > > # add item in serveropc > > > tem=items.AddItem('File1.item1',1) > > > > #read item value > > > item.Read(win32com.client.constants.OPCDevice) > > > > # write a new value > > > item.Write(100) > > > > #read item value > > > item.Read(win32com.client.constants.OPCDevice) > > > #if no pb you have 100 :) > > > > #Disconnect > > > #opcserver.Disconnect() > > > > BUT, and BUT, i want to use a event fromopcserver for uodating item > > > value with this below class. And i don't konw how make it!!!!!!!! > > > help me plz > > > > opcserver=win32com.client.Dispatch('OPC.Automation.1') > > > and now i want to use events fromopcserver. in a class: > > > class DIOPCGroupEvent: > > > class DIOPCGroupsEvent: > > > class DIOPCServerEvent: > > > Try this: > > > # Event Handlers > > class ServerEvent: > > def __init__(self): > > print 'Init ServerEvent' > > > def OnServerShutDown(self, Reason): > > print 'OnServerShutDown', Reason > > > class GroupEvent: > > def __init__(self): > > print 'Init GroupEvent' > > > def OnAsyncCancelComplete(self, CancelID): > > print 'OnAsyncCancelComplete', CancelID > > > def OnDataChange(self, TransactionID, NumItems, ClientHandles, > > ItemValues, Qualities, TimeStamps): > > print 'OnDataChange', zip(ClientHandles, ItemValues, Qualities) > > > def OnAsyncReadComplete(self, TransactionID, NumItems, ClientHandles, > > ItemValues, Qualities, > > TimeStamps, Errors): > > print 'OnAsyncReadComplete', zip(ClientHandles, ItemValues, > > Qualities) > > > def OnAsyncWriteComplete(self, TransactionID, NumItems, > > ClientHandles, Errors): > > print 'OnAsyncWriteComplete', zip(ClientHandles, Errors) > > > class GroupsEvent: > > def __init__(self): > > print 'Init GroupsEvent' > > > def OnGlobalDataChange(self, TransactionID, GroupHandle, NumItems, > > ClientHandles, ItemValues, > > Qualities, TimeStamps): > > print 'OnGlobalDataChange', zip(ClientHandles, ItemValues, > > Qualities) > > >opc= DispatchWithEvents('Matrikon.OPC.Automation.1', ServerEvent) > > > groups = DispatchWithEvents(opc.OPCGroups, GroupsEvent) > > groups.DefaultGroupIsActive = True > > groups.DefaultGroupUpdateRate = 2000 > > > group1 = DispatchWithEvents(groups.Add('G1'), GroupEvent) > > group2 = DispatchWithEvents(groups.Add('G2'), GroupEvent) > > #etc ... > > > It works for the GroupsEvents but I don't get the GroupEvent for each > > group, I may still do someting wrong..- Masquer le texte des messages pr?c?dents - > > > - Afficher le texte des messages pr?c?dents - > > In order to get the GroupEvent, you have to keep a reference to the > group you add > eg: > g1 = groups.Add('G1') > group1 = DispatchWithEvents(g1, GroupEvent) > etc...- Masquer le texte des messages pr?c?dents - > > - Afficher le texte des messages pr?c?dents - Hi Yes i try it. But when a client get a datachange the script is bloked you must kill a main thread, this solution is not good. i have experimented this programme: http://groups.google.fr/group/cn.bbs.comp.lang.python/browse_thread/thread/7904c9e48e50bf4d/1ecb94a0aca9e8d6?lnk=st&q=client+opc+python&rnum=25&hl=fr#1ecb94a0aca9e8d6 it run when a item in Group is changed But you can't do anything in a loop WHEN. From jmg3000 at gmail.com Tue Aug 21 17:06:03 2007 From: jmg3000 at gmail.com (John) Date: Tue, 21 Aug 2007 21:06:03 -0000 Subject: Call for advice on how to start PyOpenGL! In-Reply-To: <1187589198.616866.280500@j4g2000prf.googlegroups.com> References: <1187589198.616866.280500@j4g2000prf.googlegroups.com> Message-ID: <1187730363.799335.190340@w3g2000hsg.googlegroups.com> On Aug 20, 1:53 am, math2life <QJing... at gmail.com> wrote: > I work with python for two years, are familiar with image processing, > but beginner on PyOpenGL and OpenGL. > > Any advice appreciated! Here's a little "hello world" PyOpenGL program I had lying around that might be useful: http://www.milliwatt-software.com/jmg/files/pyopengl_template.py ---John From gtcopeland at gmail.com Tue Aug 21 15:48:56 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: Tue, 21 Aug 2007 12:48:56 -0700 Subject: Shed Skin Python-to-C++ compiler 0.0.23 In-Reply-To: <mailman.3.1187613108.26576.python-list@python.org> References: <mailman.3.1187613108.26576.python-list@python.org> Message-ID: <1187725736.061893.318420@57g2000hsv.googlegroups.com> On Aug 20, 7:31 am, "Mark Dufour" <mark.duf... at gmail.com> wrote: > Hi all, > > I have just released Shed Skin 0.0.23. It doesn't contain the type > inference scalability improvements I was working on, but it does have > quite a few bug fixes and minor feature additions. Here's a list of > changes: > > -support for __iadd__, __imul__ and such (except __ipow__ and __imod__) > -some overdue set optimizations > -fix for string formatting problem (%% did not always work) > -extension module stability fixes > -fix for particular inheritance problem > -other minor bugfixes, cleanups, and error messages > > I could really use some systematic help in pushing Shedskin further. Some ideas: > > -send in bug reports - these are extremely valuable and motivating to > me, yet I don't receive many.. > -find out why test 148 is currently broken under windows > -add datetime, re or socket support > -look into supporting custom classes in generated extension modules > -write a Shedskin tutorial for 'novice' programmers > -systemically test performance and suggest and work on improvements > -investigate replacements for std::string and __gnu_cxx::hash_set > -perform janitorial-type work in ss.py and lib/builtin.?pp > -support extension modules under OSX (OSX gives me accute mental RSI) > -add more tests to unit.py > > Thanks, > Mark Dufour. > -- > "One of my most productive days was throwing away 1000 lines of code" > - Ken Thompson One more thing. Please include a link to the current project page when you make these postings. Greg From __peter__ at web.de Mon Aug 27 12:06:16 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 27 Aug 2007 18:06:16 +0200 Subject: How to free memory ( ie garbage collect) at run time with Python 2.5.1(windows) References: <1188224306.863247.127890@50g2000hsm.googlegroups.com> <1i3hujk.ulsjt32wqtq0N%aleax@mac.com> <faus7d$hda$00$1@news.t-online.com> Message-ID: <fauspo$hda$00$2@news.t-online.com> Peter Otten wrote: > Alex Martelli wrote: > >> Integer objects that are once generated are kept around in a "free list" >> against the probability that they might be needed again in the future (a > > Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) > [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> x = 1000 >>>> y = 1000 >>>> x is y > False > > Why don't x and y point to the same object then? > > Peter Oops, I think I got it now. The actual objects are freed, only the memory is kept around for reuse with other ints... Peter From software at ginstrom.com Thu Aug 30 20:23:47 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Fri, 31 Aug 2007 09:23:47 +0900 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188518054.298017.90610@x35g2000prf.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com><-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com><1188364909.397692.209170@q4g2000prc.googlegroups.com><1188367108.393207.241970@g4g2000hsf.googlegroups.com><1188369928.755777.142690@i38g2000prf.googlegroups.com><46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> Message-ID: <00a001c7eb65$32b25240$0303a8c0@MOUSE> > On Behalf Of Russ > Once you have the conditions in place, all you need to do in > your unit tests is to send inputs to the unit and wait to see > if exceptions are thrown. That sounds a little ambitious to me... However, you may want to look at the typecheck module (you can get it via easy_install). I think you could probably extend it to do DBC. http://oakwinter.com/code/typecheck/ >>> from typecheck import accepts, returns, Any >>> @accepts(str, int, Any()) @returns(list) def makelist(a, b, c): return [a, b, c] >>> makelist("spam", 42, object()) ['spam', 42, <object object at 0x00AE0470>] >>> makelist(42, "spam", 3.4) Traceback (most recent call last): File "<pyshell#25>", line 1, in <module> makelist(42, "spam", 3.4) File "C:\Python25\lib\site-packages\typecheck-0.3.5-py2.5.egg\typecheck\__init__. py", line 1340, in fake_function File "C:\Python25\lib\site-packages\typecheck-0.3.5-py2.5.egg\typecheck\__init__. py", line 1419, in __check_args TypeCheckError: Argument a: for 42, expected <type 'str'>, got <type 'int'> >>> I tried using DBC for a time in C++ (using a library with a clever assembly-language hack). I personally found it neater having such code in unit tests, but obviously, it's a matter of preference. Regards, Ryan Ginstrom From steveo at syslang.net Fri Aug 17 09:38:50 2007 From: steveo at syslang.net (Steven W. Orr) Date: Fri, 17 Aug 2007 09:38:50 -0400 (EDT) Subject: Need to generate some functions. Message-ID: <alpine.LFD.0.999.0708170858320.21497@saturn.syslang.net> Given a list of names ll = ("n1", "n2", "n3", "n4") I want to create a pair of functions based off of each name. An example of what I want to happen would look like this: def mkn1dict(address): return {'Address': address, 'Control': SOME_CONST} def mkn1Classobj(address): return Classobj( mkn1classobj(address) ) I know how to do this in a preprocessor, but I'd like to do it directly in python. Can this be done? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From deets at nospam.web.de Tue Aug 7 02:41:51 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 07 Aug 2007 08:41:51 +0200 Subject: read(size=-1) In-Reply-To: <1186466817.747723.87910@19g2000hsx.googlegroups.com> References: <1186466817.747723.87910@19g2000hsx.googlegroups.com> Message-ID: <5hqihjF3kjes7U1@mid.uni-berlin.de> 7stud schrieb: > Suppose I write: > > f = open("myimg.jpg") > f.read(10) > > > According to the docs, > ----------- > read([size]) > > Read at most size bytes from the file....The bytes are returned as a > string object. > ---------- > > How does python convert a byte to a string? A string _is_ a sequence of bytes - there is nothing to convert. Diez From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Aug 28 18:12:20 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 29 Aug 2007 00:12:20 +0200 Subject: localhost, ?! References: <fb1id4$kpp$1@localhost.localdomain> <5jjbpfF3sm4m7U2@mid.individual.net> <fb1vh2$lqg$1@localhost.localdomain> Message-ID: <5jjku4F3tpdfrU1@mid.individual.net> Boris Ozegovic wrote: > Bjoern Schliessmann wrote: >> Definitely a problem with the web server (503 means "service >> unavailable"). > > I did try on two servers, Apache and simple python server. There > was identically error on both servers. Also try to look at the logs, you're bound find something there too. >> Try using wireshark or a similar tool to see what's going on on >> protocol level. > > Ok. And don't forget to report back :) Regards, Bj?rn -- BOFH excuse #307: emissions from GSM-phones From rodrigo.cr at gmail.com Tue Aug 21 08:45:56 2007 From: rodrigo.cr at gmail.com (rodrigo) Date: Tue, 21 Aug 2007 12:45:56 -0000 Subject: Retrieving a variable's name. In-Reply-To: <fado06$a1e$1@zinnia.noc.ucla.edu> References: <1187658202.236626.93600@50g2000hsm.googlegroups.com> <fado06$a1e$1@zinnia.noc.ucla.edu> Message-ID: <1187700356.974638.234550@50g2000hsm.googlegroups.com> You're right, Paul, Evan, James, I should just use a dictionary. Thanks! Rodrigo From Graham.Dumpleton at gmail.com Wed Aug 8 20:17:41 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Thu, 09 Aug 2007 00:17:41 -0000 Subject: Destruction of generator objects In-Reply-To: <20070808002852.6228ae91@cube.tz.axivion.com> References: <20070808002852.6228ae91@cube.tz.axivion.com> Message-ID: <1186618661.845525.225010@x35g2000prf.googlegroups.com> On Aug 8, 8:28 am, Stefan Bellon <sbel... at sbellon.de> wrote: > Hi all, > > I'm generating a binding from Python to C using SWIG. On the C side I > have iterators over some data structures. On the Python side I > currently use code like the following: > > def get_data(obj): > result = [] > iter = make_iter(obj) > while more(iter): > item = next(iter) > result.append(item) > destroy(iter) > return result > > Now I'd like to transform it to a generator function like the following > in order to make it more memory and time efficient: > > def get_data(obj): > iter = make_iter(obj) > while more(iter): > yield next(iter) > destroy(iter) > > But in the generator case, I have a problem if the generator object is > not iterated till the StopIteration occurs, but if iteration is stopped > earlier. In that case, the C iterator's destroy is not called, thus the > resource is not freed. > > Is there a way around this? Can I add some sort of __del__() to the > generator object so that in case of an early destruction of the > generator object, the external resource is freed as well? > > I'm looking forward to hearing your hints! > > -- > Stefan Bellon Perhaps read through: http://www.python.org/dev/peps/pep-0325/ http://www.python.org/dev/peps/pep-0342/ The latter superseding the first. Based on these what the WSGI specification: http://www.python.org/dev/peps/pep-0333/ did was mandate that the consumer of data from the generator explicitly call the close() method on the generator no matter whether all data was consumed or not, or whether an exception occurred. result = application(environ, start_response) try: for data in result: if data: # don't send headers until body appears write(data) if not headers_sent: write('') # send headers now if body was empty finally: if hasattr(result,'close'): result.close() That the consumer called close() allowed generators to provide a close() method to cleanup resources even though older version of Python was being used which didn't support automatic means of close() being called. In other words, it allowed the required cleanup and was forward compatible with newer versions of Python. Graham From dobedani at gmx.net Wed Aug 1 07:58:59 2007 From: dobedani at gmx.net (Dobedani) Date: Wed, 01 Aug 2007 04:58:59 -0700 Subject: Plain old SAX and minidom useable? But how then? Message-ID: <1185969539.653078.287360@w3g2000hsg.googlegroups.com> Dear All, I guess I don't know where to look for the right information. I hope you guys can help me on the way. I want to retrieve a string from an XML-file. If Python were to have XPath available, my problem would be solved. The xquery string would be enough and I have already obtained that the string. The problem is that I cannot use any add-on - like xmllib, sax2 or elementtree - as my customers only have the so-called stock Python install - i.e. version 2.4.1. I've seen some posts from 2? years ago by Nelson Minar and also by Uche Ogbuji who wrote: "Nelson says: There's the stock Python install, which barely does anything [for XML]. That's overstated. Plain old SAX and minidom may not be ideal, but they're useable." Please: where then can I find examples of such use? If I cannot use xpath, I would not mind to browse a bit - e.g. using functions like getElementByTag() but I don't even know how to use those. TIA Kind regards, Dobedani From almadhu at gmail.com Mon Aug 13 00:35:44 2007 From: almadhu at gmail.com (Madhu Alagu) Date: Mon, 13 Aug 2007 04:35:44 -0000 Subject: python + XUL In-Reply-To: <1186966451.081184.63490@r34g2000hsd.googlegroups.com> References: <1186894004.913359.132000@b79g2000hse.googlegroups.com> <46BEA6FC.9050907@web.de> <1186966451.081184.63490@r34g2000hsd.googlegroups.com> Message-ID: <1186979744.039833.213840@r34g2000hsd.googlegroups.com> On Aug 13, 3:54 am, Luis M. Gonz?lez <luis... at gmail.com> wrote: > On Aug 12, 3:21 am, Stefan Behnel <stefan.behnel-n05... at web.de> wrote: > > > Madhu Alagu wrote: > > > Hi > > > > Python + XUL Success Stories > > > > Thanks > > > > Madhu Alagu > > > Any chance you forgot to ask a question? > > > Stefan > > My telepatic powers tell me that this means: > "I don't really feel like googling, so just give me the info, ok?" I am very sorry for the short word... Has anyone had any success in getting XUL to work with python? From laurent.pointal at limsi.fr Tue Aug 14 09:20:30 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 14 Aug 2007 15:20:30 +0200 Subject: LEGB rule, totally confused ... In-Reply-To: <mailman.1959.1187094797.22759.python-list@python.org> References: <mailman.1959.1187094797.22759.python-list@python.org> Message-ID: <f9sa70$i2h$1@news2.u-psud.fr> stef mientki a ?crit : > hello, > > I've thought many times I finally understood the import / namespace rules, > but again I'm totally lost :-( > > This is my library file > > # Module lib_test.py > > X = 1 > > def Init(): > global X > X = 3 > print 'Init', X > > def Run (): > print X <=== UnboundLocalError: local variable > 'X' referenced before assignment > X = X + 1 > print ' Run', X > > > > And this my main program in another file: > > import lib_test > lib_test.Init() > print lib_test.X > > lib_test.Run() > print lib_test.X > > Why do I get the error ? > Printing isn't assigning anything or am I missing something. If you use a global to *modify* it, you MUST declare "global X", either Python consider using a local. So for your error: at compile time, in Run(), it see that it must use a local X (because you set it) and generate ad-hoc bytecode, but when running X is not defined locally, so the error. > Now if I remove "X = X + 1" I don't get an error ??? If you remove the "X =..." statement, then the compiler dont know a-priori if its local or global, so it search X in both namespaces. > Is this a problem of the traceback procedure or the IDE, > or is Python not completely an interpreter, that reads line by line ??? Its compiled to buyte-code then interpreted from the byte-code. > > Please explain this to me. > > thanks, > Stef Mientki A+ Laurent. From coyote_x at artcom.pl Fri Aug 31 08:03:48 2007 From: coyote_x at artcom.pl (Adam Kubica) Date: Fri, 31 Aug 2007 14:03:48 +0200 Subject: Pylons, SQLAlchemy, too many connections problem. Message-ID: <pan.2007.08.31.12.03.48.18688@artcom.pl> Hello. I have pylons 0.96 (SVN) and current SQLAlchemy (0.3.10), and I have bug that doesn't exist earlier. My connection code: <code> import sqlalchemy.mods.threadlocal from sqlalchemy import DynamicMetaData, objectstore metadata = DynamicMetaData( case_sensitive = False ) def db_connect( dsn ): engine = create_engine( dsn, echo=False, echo_pool=False, encoding='latin2', convert_unicode=True ) metadata.connect( engine ) </code> command "netstat -an|grep 5432|grep ESTABLISHED|wc -l" displays one more connection after each refresh of page until I have exceptions such as: sqlalchemy.exceptions.DBAPIError: (Connection failed) (OperationalError) FATAL: sorry, too many clients already What is wrong? From carl at 29degrees.co.uk Tue Aug 28 13:26:03 2007 From: carl at 29degrees.co.uk (Carl Drinkwater | 29degrees) Date: Tue, 28 Aug 2007 18:26:03 +0100 Subject: National grid to lat long conversion In-Reply-To: <1188295755.877801.217710@r29g2000hsg.googlegroups.com> References: <1188295755.877801.217710@r29g2000hsg.googlegroups.com> Message-ID: <E9CFDD38-0BBB-415B-8ED0-33BEEB7530B8@29degrees.co.uk> > I have a load of British National Grid references that I want to > convert to decimal degrees so I can create a google KML file. Does > anyone know of a module to do this? If there isn't a module available, you could roll your own. The equations are to be found at : http://www.ordnancesurvey.co.uk/oswebsite/gps/docs/ convertingcoordinatesEN.pdf They shouldn't be too hard to Pythonise. Regards, Carl. From dickinsm at gmail.com Thu Aug 30 16:55:53 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 30 Aug 2007 20:55:53 -0000 Subject: Biased random? In-Reply-To: <1188506180.227794.20030@q5g2000prf.googlegroups.com> References: <favd0c$fcu$1@ss408.t-com.hr> <mailman.80.1188332647.28954.python-list@python.org> <fb77bq$jtk$1@ss408.t-com.hr> <1188506180.227794.20030@q5g2000prf.googlegroups.com> Message-ID: <1188507353.877677.79500@r23g2000prd.googlegroups.com> > One possible fix: do > > x = randint(0, 10) - randint(0, 10) > x = abs(x) - (x<0) > > This collapses -1 and 0 to 0, -2 and 1 to 1, etc. Or a slightly simpler formula that ends up producing the same distribution: x = min(randint(0, 10), randint(0, 10)) Mark From horpner at yahoo.com Thu Aug 9 13:15:08 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 09 Aug 2007 17:15:08 GMT Subject: Stackless Integration References: <1186650027.043779.276520@i38g2000prf.googlegroups.com> <mailman.1786.1186660119.22759.python-list@python.org> <1186678419.594781.149190@g12g2000prg.googlegroups.com> Message-ID: <slrnfbmj19.1bg.horpner@FIAD06.norwich.edu> On 2007-08-09, Justin T. <jmtulloss at gmail.com> wrote: > >> It's not Pythonic. >> >> Jean-Paul > > Ha! I wish there was a way to indicate sarcasm on the net. You > almost got people all riled up! Sorry. There's NO WAY to show sarcasm on the net. ;) -- Neil Cerutti From Shawn at Milochik.com Thu Aug 16 09:55:33 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Thu, 16 Aug 2007 09:55:33 -0400 Subject: Python Book Recommendations In-Reply-To: <1187271201.262706.132080@i38g2000prf.googlegroups.com> References: <d5506a9f0708141439v6a30d4c8l5092b30d269c1af4@mail.gmail.com> <Pine.LNX.4.44.0708141556370.5396-100000@violet.rahul.net> <1b31ae500708141638w77614014o6f382d0389bc69df@mail.gmail.com> <mailman.2015.1187189280.22759.python-list@python.org> <1187191803.845011.30400@x35g2000prf.googlegroups.com> <fa0ruu$65r$1@news2.u-psud.fr> <1187271201.262706.132080@i38g2000prf.googlegroups.com> Message-ID: <2dc0c81b0708160655n437500d5iefdd46ee5ffec3b9@mail.gmail.com> I should add that "Dive Into Python" is also available for free online: http://www.diveintopython.org/ It's a great book. It is not a linear book -- it doesn't start you off talking about variable types and structure. It starts you right off with a piece of working code. If you already have some programming experience, it's actually a refreshing change from all the others which basically waste 50 - 100 pages on stuff you already know. From geoff.bache at pobox.com Tue Aug 28 05:08:22 2007 From: geoff.bache at pobox.com (geoffbache) Date: Tue, 28 Aug 2007 02:08:22 -0700 Subject: Getting subprocesses to be hidden on Windows In-Reply-To: <1188250115.875160.276780@r29g2000hsg.googlegroups.com> References: <1188246076.131276.292010@r34g2000hsd.googlegroups.com> <1188250115.875160.276780@r29g2000hsg.googlegroups.com> Message-ID: <1188292102.065625.82670@22g2000hsm.googlegroups.com> On Aug 27, 11:28 pm, kyoso... at gmail.com wrote: > On Aug 27, 3:21 pm, geoffbache <geoff.ba... at pobox.com> wrote: > > > > > Hi, > > > As part of my efforts to write a test tool that copes with GUIs > > nicely, I'm trying to establish how I can start a GUI process on > > Windows that will not bring up the window. So I try to hide the window > > as follows: > > > info = subprocess.STARTUPINFO() > > info.dwFlags |= subprocess.STARTF_USESHOWWINDOW > > info.wShowWindow = subprocess.SW_HIDE > > > proc = subprocess.Popen(..., startupinfo=info) > > > This works, in a way, but doesn't work recursively. I.e. if the > > started process itself starts a window, that second window will not be > > hidden. This even applies to dialog boxes within the application. So > > instead of a lot of windows popping up I now get a lot of disembodied > > dialogs appearing, which is a slight improvement but not much. > > > Also, certain processes (e.g. tkdiff) seem to ignore the directive to > > be hidden altogether. > > > This is dead easy on UNIX with virtual displays like Xvfb. Can someone > > shed any light if it's possible on Windows from python? > > > Regards, > > Geoff Bache > > I'm confused. Why would you create a GUI if you're not going to > actually display it? Isn't that the point of a GUI? Or are you talking > about the command window popping up? > > Mike Only in the context of testing it. If I run lots of GUI tests on my computer I want the tested GUIs to remain hidden so I can still use my computer in the meantime... Though if you can tell me how to stop the command window popping up on Windows I'll be grateful for that too (though it wasn't the original question). Geoff From ssalvatori at gmail.com Wed Aug 1 10:43:19 2007 From: ssalvatori at gmail.com (stefano) Date: Wed, 01 Aug 2007 14:43:19 -0000 Subject: http client module In-Reply-To: <mailman.1415.1185937817.22759.python-list@python.org> References: <1185936595.262806.269290@19g2000hsx.googlegroups.com> <mailman.1415.1185937817.22759.python-list@python.org> Message-ID: <1185979399.641093.98590@k79g2000hse.googlegroups.com> On 31 jul, 23:07, Steve Holden <st... at holdenweb.com> wrote: > stefano wrote: > > Hello i'm looking for a http client for python i found this one call > > httplib2 > > >http://64.233.169.104/search?q=cache:0jJWNfodK6gJ:bitworking.org/proj... > > > but is too old > > Look at urllib and urllib2 in the standard library. If they don't give > you what you want, think about using mechanize and ClientForm, or > possible beautifulsoup, all of which Google should be able to find for you. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- thanks From rhamph at gmail.com Thu Aug 30 16:31:08 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: Thu, 30 Aug 2007 20:31:08 -0000 Subject: Is LOAD_GLOBAL really that slow? In-Reply-To: <mailman.152.1188497059.28954.python-list@python.org> References: <aac2c7cb0708291823h15e3f675mbeae9ecf37d653b6@mail.gmail.com> <mailman.130.1188441225.28954.python-list@python.org> <1188495447.083333.271540@q4g2000prc.googlegroups.com> <mailman.152.1188497059.28954.python-list@python.org> Message-ID: <1188505868.337081.319790@q4g2000prc.googlegroups.com> On Aug 30, 12:04 pm, "Chris Mellon" <arka... at gmail.com> wrote: > On 8/30/07, Rhamphoryncus <rha... at gmail.com> wrote: > > > On Aug 29, 8:33 pm, Carsten Haese <cars... at uniqsys.com> wrote: > > > On Wed, 2007-08-29 at 19:23 -0600, Adam Olsen wrote: > > > There is no loop overhead here, and after subtracting the function call > > > overhead, I get 31 nanoseconds per local lookup and 63 nanoseconds per > > > global lookup, so local lookups are just about twice as fast as global > > > lookups. > > __builtins__ lookups are an extra dict lookup slower than just global > variables, too. Don't forget those. Heh right, I forgot that. That's what my benchmark was actually testing. > > > True, whether this difference is significant does depend on how many > > > name lookups your code makes and how much else it's doing, but if you're > > > doing a lot of number crunching and not a lot of I/O, the difference > > > might be significant. Also, even if using local names is only slightly > > > faster than using globals, it's still not slower, and the resulting code > > > is still more readable and more maintainable. Using locals is a win-win > > > scenario. > > > You get very small speed gains (assuming your code is doing anything > > significant), for a lot of effort (trying out different options, > > seeing if they're actually faster on different boxes.) The > > readability cost is there, even if it is smaller than many of the > > other obfuscations people attempt. If the speed gains were really > > that important you should rewrite in C, where you'd get far greater > > speed gains. > > I've doubled the speed of a processing loop by moving globals lookups > out of the loop. Rewriting in C would have taken at least a day, even > with Pyrex, localizing the lookup took about 2 minutes. I'm guessing that was due to deep voodoo involving your processor's pipeline, branch prediction, caching, etc. I'd be interested in seeing small examples of it though. > > So it only seems worthwhile when you really, *really* need to get a > > slight speedup on your box, you don't need to get any more speedup > > than that, and C is not an option. > > It's not a huge optimization, but it's really easy to write if you > don't mind adding fake kwargs to your functions. Just for the heck of > it I also wrote a decorator that will re-write the bytecode so that > any global that can be looked up at function definition will be > re-written as a local (actually with LOAD_CONST). You can see it athttp://code.google.com/p/wxpsvg/wiki/GlobalsOptimization. Disclaimer: > While I've tested it with a variety of functions and it's never broken > anything, I've never actually used this for anything except an > intellectual exercise. Use at your own risk. Doubling the throughput while doing *real work* is definitely more significant than maybe-or-maybe-not-quite-doubling without any real work. -- Adam Olsen, aka Rhamphoryncus From arkanes at gmail.com Wed Aug 15 15:02:24 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 15 Aug 2007 14:02:24 -0500 Subject: Move files/directories to Recycle Bin using standard Python libs In-Reply-To: <f9va80$ciu$1@foggy.unx.sas.com> References: <f9va80$ciu$1@foggy.unx.sas.com> Message-ID: <4866bea60708151202t65a05d14w2c1234259e81db3@mail.gmail.com> On 8/15/07, Kevin D.Smith <Kevin.Smith at sas.com> wrote: > I would like to move files and directories to the Recycle Bin on > Windows from Python. I have found some older articles describing how > to do this, but they require additional packages to be installed. I'm > working on a plugin for an existing project and only have the standard > library to work with. Is there a way to use the Recycle Bin using > standard Python? > > -- > Kevin D. Smith Not easily. The recycle bin is part of the shell, and the shell api calls have very complicated struct parameters that are cumbersome to use correctly from ctypes. If you do the work to map the fileop structs to ctypes you can call the shell API file operation functions in shell32.dll. This assumes that "standard" for you is Python 2.5, which has ctypes. Otherwise you are out of luck. From fonnesbeck at gmail.com Sun Aug 12 21:22:40 2007 From: fonnesbeck at gmail.com (Chris Fonnesbeck) Date: Mon, 13 Aug 2007 01:22:40 +0000 (UTC) Subject: Python not freeing memory (?) References: <mailman.1882.1186951800.22759.python-list@python.org> <46bf8cf5$0$29938$9b622d9e@news.freenet.de> Message-ID: <loom.20070813T031422-6@post.gmane.org> Martin v. L?wis <martin <at> v.loewis.de> writes: > If you want others to help you in finding the bug, you > need to provide more detail, e.g. a specific piece of > code that reproducibly wastes memory. If you want to > study how Python objects are allocated and released, > you need to create a debug build of Python (and all > extension modules), and start, e.g., with looking at the > value of sys.gettotalrefcount() over time. I tried monitoring the refcount at every iteration, but it does not change; at the same time, the memory use by the python process increases. This is why I suspected that python was not returning memory. Below is the method that gets called iteratively; the *_like methods are statistical likelihoods implemented in f2py. I dont see anything that is obviously responsible: def model(self): # Specification of joint log-posterior #alpha3 = concatenate(([0], self.alpha3)) # Linear model for surfacing wait time #self.lamda = exp(self.alpha0 + self.alpha1 * self.wind + self.alpha2 * self.air + alpha3[self.series-1]) gamma3 = concatenate(([0], self.gamma3)) # Linear model for at-surface probability self.theta = invlogit(self.gamma0 + self.gamma1 * self.wind + self.gamma 2 * self.air + gamma3[self.series-1]) x, n, theta = transpose([[z[1], sum(z), t] for z, t in zip(self.downup, self.theta) if type(z)!=type(0.0)]) # Binomial likelihood of available animals self.binomial_like(x, n, theta, name='theta') # Probability of availability (per survey) self.pa = 1.0 - (1 - self.theta)**10 beta3 = concatenate(([0], self.beta3)) # Linearmodel for probability of detection self.pd = invlogit(self.beta0 + self.beta1 * self.wind + self.beta2 * (s elf.cloud>0) + beta3[self.series-1]) # Binomial likelihood of detection self.binomial_like(self.obs, self.present, self.pd * self.pa, name='pd') zeta1 = concatenate(([0], self.zeta1)) # Probability of presence self.pp = invlogit(self.zeta0 + zeta1[self.series-1] + self.zeta2 * self .intake + self.zeta3 * (self.discharge - self.intake)) # Binomial likelihood of presence self.binomial_like(self.present, self.absent + self.present, self.pp, na me='pp') # Correct flight counts for detection self.N_flight = self.count / (self.pd * self.pa) # Aggregate counts by series N_series = [self.N_flight[self.series==i+1] for i in range(6)] # Log-normal likelihood for N #sum(self.lognormal_like(X, log(N), T) for X, N, T in zip(N_series, self .N, self.T)) for N, mu in zip(N_series, self.N): self.poisson_like(N, mu) Thanks in advance for anything that you might suggest. cf From skip at pobox.com Sat Aug 18 18:27:28 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 18 Aug 2007 17:27:28 -0500 Subject: PEP 11 update - Call for port maintainers to step forward Message-ID: <18119.29264.543717.894262@montanaro.dyndns.org> I made a quick update to PEP 11, "Removing support for little used platforms". I added details about ending support for AtheOS/Syllable and BeOS. I also added a yet-to-be-fleshed out section entitled "Platform Maintainers". I intend that to the extent possible we document the responsible parties for various platforms. Obviously, common platforms like Windows, Mac OS X, Linux and common Unix platforms (Solaris, *BSD, what else?) will continue to be supported by the core Python developer community, but lesser platforms should have one or more champions, and we should be able to get ahold of them to determine their continued interest in supporting Python on their platform(s). If you are the "owner" of a minor platform, please drop me a note. Ones I'm aware of that probably need specialized support outside the core Python developers include: IRIX Tru64 (aka OSF/1 and other names (what else?)) OS2/EMX (Andrew MacIntyre?) Cygwin MinGW HP-UX AIX Solaris < version 8 SCO Unixware IRIX and Tru64 are likely to go the way of the dodo if someone doesn't step up soon to offer support. I don't expect the others to disappear soon, but they tend to need more specialized support, especially in more "challenging" areas (shared library support, threading, etc). If you maintain the platform-specific aspects for any of these platforms, please let me know. If you aren't that person but know who is, please pass this note along to them. If I've missed any other platforms (I know I must have have missed something), let me know that as well. Thanks, -- Skip Montanaro - skip at pobox.com - http://www.webfast.com/~skip/ From gherron at islandtraining.com Tue Aug 21 11:42:08 2007 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 21 Aug 2007 08:42:08 -0700 Subject: Python Path Dictionary In-Reply-To: <1187706985.476483.292820@g4g2000hsf.googlegroups.com> References: <1187706985.476483.292820@g4g2000hsf.googlegroups.com> Message-ID: <46CB07D0.7020507@islandtraining.com> aine_canby at yahoo.com wrote: > Hi, > > Do the Python Paths come in the form of a dictionary where I can > access a particular path my its key in the registry? > > For example, in PythonWin Tools>>Edit Python Paths shows the name as > well of the address of each path > > Thanks, > > Aine > > If by "Python Paths" you mean the list of directories searched when doing an import, then it is a list (not a dictionary and you can access it as sys.path. Here it is on both my Linux and Windows systems: >>> import sys >>> sys.path ['', '/usr/lib/portage/pym', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/Numeric', '/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/gtk-2.0'] >>> import sys >>> sys.path ['', 'C:\\WINDOWS\\system32\\python24.zip', 'C:\\cygwin\\home\\Gary', 'c:\\python24\\DLLs', 'c:\\python24\\lib', 'c:\\python24\\lib\\plat-win', 'c:\\python24\\lib\\lib-tk', 'c:\\python24', 'c:\\python24\\lib\\site-packages', 'c:\\python24\\lib\\site-packages\\Numeric', 'c:\\python24\\lib\\site-packages\\PIL', 'c:\\python24\\lib\\site-packages\\gtk-2.0', 'c:\\python24\\lib\\site-packages\\win32', 'c:\\python24\\lib\\site-packages\\win32\\lib', 'c:\\python24\\lib\\site-packages\\Pythonwin'] From Afro.Systems at gmail.com Tue Aug 14 05:12:42 2007 From: Afro.Systems at gmail.com (Tzury) Date: Tue, 14 Aug 2007 02:12:42 -0700 Subject: ctypes, windll question Message-ID: <1187082762.132865.43630@r34g2000hsd.googlegroups.com> I followed the tutorial about ctypes and I still cannot figure out how to call a method of a calss within the dll. For example: a dll named 'foo' contain a class named 'bar' which expose a method named 'baz'. if I either do: mydll = windll.foo mycls = mydll.bar or mycls = windll.foo.bar or mycls = windll.foo.bar() I get an erros: "function 'bar' not found " which is true since while bar is a class. Yet, I need to know how to create an instance of this inner class so I can access its public methods. From arkanes at gmail.com Thu Aug 30 14:57:09 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 30 Aug 2007 13:57:09 -0500 Subject: list index() In-Reply-To: <1188499525.827573.128170@x35g2000prf.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <46d674c2$0$417$426a34cc@news.free.fr> <1188496588.750629.208100@g4g2000hsf.googlegroups.com> <mailman.154.1188497511.28954.python-list@python.org> <1188498073.997168.282420@q5g2000prf.googlegroups.com> <mailman.156.1188498891.28954.python-list@python.org> <1188499525.827573.128170@x35g2000prf.googlegroups.com> Message-ID: <4866bea60708301157u10ddba4ay14dd003650312450@mail.gmail.com> On 8/30/07, zzbbaadd at aol.com <zzbbaadd at aol.com> wrote: > > > That wish will only come true if you maintain your own fork of Python 3. > > has_key() will go away, period. It has been made obsolete by "in", which > > is faster and more concise. > > Is there really some reason "key" IN dict can be implemented faster > than dict.has_key("key")??? > Yes. As an exercise, I wont tell you the first most obvious reason - see if you can figure it out. The dis module may help. From arunmail at gmail.com Thu Aug 2 15:43:58 2007 From: arunmail at gmail.com (lazy) Date: Thu, 02 Aug 2007 19:43:58 -0000 Subject: Berkely Db. How to iterate over large number of keys "quickly" Message-ID: <1186083838.318952.254370@q3g2000prf.googlegroups.com> I have a berkely db and Im using the bsddb module to access it. The Db is quite huge (anywhere from 2-30GB). I want to iterate over the keys serially. I tried using something basic like for key in db.keys() but this takes lot of time. I guess Python is trying to get the list of all keys first and probbaly keep it in memory. Is there a way to avoid this, since I just want to access keys serially. I mean is there a way I can tell Python to not load all keys, but try to access it as the loop progresses(like in a linked list). I could find any accessor methonds on bsddb to this with my initial search. I am guessing BTree might be a good choice here, but since while the Dbs were written it was opened using hashopen, Im not able to use btopen when I want to iterate over the db. From jstroud at mbi.ucla.edu Thu Aug 30 21:21:42 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 30 Aug 2007 18:21:42 -0700 Subject: Setting a read-only attribute In-Reply-To: <1188509700.915517.178440@z24g2000prh.googlegroups.com> References: <1188509700.915517.178440@z24g2000prh.googlegroups.com> Message-ID: <fb7qf6$7pq$1@daisy.noc.ucla.edu> tleeuwenburg at gmail.com wrote: > I have an object and wish to set an attribute on it which, > unfortunately for me, is read-only. > > How can I go about this? Can you simply subclass the object's class, intercept __setattr__ and __getattribute__, and spoof the read-only attribute? E.g.: class A(object): def get_ro(self): return 'readonly' ro = property(get_ro) class B(A): def __setattr__(self, anatt, aval): if anatt == 'ro': anatt = '_ro' super(A, self).__setattr__(anatt, aval) def __getattribute__(self, anatt): if anatt == 'ro' and hasattr(self, '_ro'): anatt = '_ro' return super(A, self).__getattribute__(anatt) The output: py> class A(object): ... def get_ro(self): ... return 'readonly' ... ro = property(get_ro) ... py> class B(A): ... def __setattr__(self, anatt, aval): ... if anatt == 'ro': ... anatt = '_ro' ... super(A, self).__setattr__(anatt, aval) ... def __getattribute__(self, anatt): ... if anatt == 'ro' and hasattr(self, '_ro'): ... anatt = '_ro' ... return super(A, self).__getattribute__(anatt) ... py> a = A() py> print a.ro readonly py> a.ro = 4 ------------------------------------------------------------ Traceback (most recent call last): File "<ipython console>", line 1, in <module> <type 'exceptions.AttributeError'>: can't set attribute py> py> b = B() py> b.x = 10 py> print b.x 10 py> print b.ro readonly py> b.ro = 4 py> print b.ro 4 I'm not so sure this is the least clunky way to do this. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Aug 28 04:24:00 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 28 Aug 2007 10:24:00 +0200 Subject: How to free memory ( ie garbage collect) at run time with Python 2.5.1(windows) In-Reply-To: <1i3hujk.ulsjt32wqtq0N%aleax@mac.com> References: <1188224306.863247.127890@50g2000hsm.googlegroups.com> <1i3hujk.ulsjt32wqtq0N%aleax@mac.com> Message-ID: <46d3db9b$0$30521$426a74cc@news.free.fr> Alex Martelli a ?crit : > rfv-370 <robert.vergnes at yahoo.fr> wrote: (snip) >> So how can I force Python to clean the memory and free the memory that >> is not used? > > On Windows, with Python 2.5, I don't know of a good approach (on Linux > and other Unix-like systems I've used a strategy based on forking, doing > the bit that needs a bazillion ints in the child process, ending the > child process; but that wouldn't work on Win -- no fork). IIRC, Windows has it's own way to let you launch other processes, so a similar strategy might apply here... From esj at harvee.org Fri Aug 24 00:17:34 2007 From: esj at harvee.org (Eric S. Johansson) Date: Fri, 24 Aug 2007 00:17:34 -0400 Subject: unifying many packages under one name Message-ID: <falm5n$59d$1@sea.gmane.org> I have a collection of packages and I want to put them under single unifying name. my goal is to reduce namespace pollution and make all these packages accessible as 'import vvv.aaa'. In more detail, if I have packages 'aaa' and 'bbb', what do I do to put those packages under unifying name such as 'vvv'? the only way I can see to do it is to create 'vvv' as a directory with its own __init__.py but I'm not sure that were work right either. thanks. From seun.osewa at gmail.com Tue Aug 21 20:30:03 2007 From: seun.osewa at gmail.com (Seun Osewa) Date: Wed, 22 Aug 2007 00:30:03 -0000 Subject: subprocess (spawned by os.system) inherits open TCP/UDP/IP port In-Reply-To: <mailman.928.1184946783.22759.python-list@python.org> References: <OuidnfFc6OjhKD3bnZ2dnUVZ_oimnZ2d@comcast.com> <mailman.928.1184946783.22759.python-list@python.org> Message-ID: <1187742603.908139.311350@j4g2000prf.googlegroups.com> Is it possible to cause this sort of thing to happen on Windows. Specifically, I'm looking for a way to cause multiple processes to accept new connections on a bound socket. on UNIX, I can just fork() after binding the server socket to a port and the children can accept() on that same socket, but on Windows, I don't know how to make that work. Any ideas? Thanks! > It doesn't actually move. Thefiledescriptor is a handle onto the port. > A port can have multiple handles which refer to it. When you fork, you > effectively copy the handle into another process. Now there are two > handles onto the same port. If one of the processes exits, the other one > still has a handle, and so the port still exists. If a process forks > multiple times, then multiple copies are made. Each process can accept > connections on the port through its own handle. Exiting just drops the > handle, it doesn't close the port. From mccredie at gmail.com Tue Aug 14 16:42:53 2007 From: mccredie at gmail.com (Matt McCredie) Date: Tue, 14 Aug 2007 13:42:53 -0700 Subject: try/finally exceptions dying In-Reply-To: <1187118591.965164.6120@w3g2000hsg.googlegroups.com> References: <1187118591.965164.6120@w3g2000hsg.googlegroups.com> Message-ID: <9e95df10708141342u4c1d3d5dj9e11e5e5e40fc7d7@mail.gmail.com> > I thought finally always propagated the > exception all the way up the stack until it was handled. Finally will propagate the exception up, unless another exception occurs within the finally block. Since there is not (yet: http://www.python.org/dev/peps/pep-3134/) exception chaining in Python, only the last exception to be raised is held onto. The finally block combined with the recursion makes it impossible to catch every exception that way. Something like this might work: [code] def dostuff(args): stuff return status def run_with_error_handling(): exceptions = [] done = False while 1: try: status = dostuff(args) except (exception1, exception2), data: exceptions.append(data) modify status finally: update args based on status break if done [/code] Note that in the above example, status could be just a tuple of args. Then you just need to figure out how to modify the args in the exception case. The above leaves a lot of holes though. If you want more help you will have to send a more complete example. Matt From ratchetgrid at googlemail.com Tue Aug 21 18:33:32 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Tue, 21 Aug 2007 23:33:32 +0100 Subject: Tokenizer for python? In-Reply-To: <496954360708211405j4ddbf4bfxd0710efbc58682b0@mail.gmail.com> References: <496954360708211405j4ddbf4bfxd0710efbc58682b0@mail.gmail.com> Message-ID: <676224240708211533h4507f94bg596cc27808070370@mail.gmail.com> Hi, >From your description I think something like PyParsing might be useful to you. http://pyparsing.wikispaces.com/ If not then I guess I m not understanding your question right. Hope this helps Nathan On 21/08/07, Robert Dailey <rcdailey at gmail.com> wrote: > Hi, > > I am looking for a sort of "tokenizer" for python. I've taken a look at the > tokenize module, but that seems to parse python code from what I read. I > want a tokenizer that works a little like boost::tokenizer, however for > python. Basically I want to be able to pass in an arbitrary string (or line > from readline()) and specify tokens that cause the string to be separated > into parts, much like the regular expression split() method (I think that's > the name of it). Is there anything that already exists that does this, or do > I need to implement it myself with regular expressions? > > Thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list > From rkmr.em at gmail.com Fri Aug 10 18:49:59 2007 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Fri, 10 Aug 2007 15:49:59 -0700 Subject: AttributeError: 'module' object has no attribute 'HTTPSHandler' In-Reply-To: <9e95df10708101352h45076f1cm36550126b1b548e3@mail.gmail.com> References: <e04d2e90708100957t79ed5a72s259281d912508fc1@mail.gmail.com> <9e95df10708101153j74eb6431kd216503ab6c770ae@mail.gmail.com> <9e95df10708101352h45076f1cm36550126b1b548e3@mail.gmail.com> Message-ID: <e04d2e90708101549y50640f1aic067389992c6d73e@mail.gmail.com> On 8/10/07, Matt McCredie <mccredie at gmail.com> wrote: > > I built and installed python 2.5 from source and when I do this: > > opener = urllib2.build_opener(SmartRedirectHandler(), > > DefaultErrorHandler(), urllib2.HTTPSHandler()) > > I get this error. > > AttributeError: 'module' object has no attribute 'HTTPSHandler' > You need `_ssl.pyd' for HTTPSHandler to work. I guess, try to figure > out why that wasn't built, then build it. I suppose I _might_ be able > to give a little more help, but you haven't mentioned what platform > you are using. Even then, I'm not an expert on building Python. I am using Fedora Core 4 linux. Where should I look for _ssl.pyd ? I am trying to build and use Python-2.5.1 From bgoldenberg at gmail.com Thu Aug 9 17:58:54 2007 From: bgoldenberg at gmail.com (Benjamin Goldenberg) Date: Thu, 09 Aug 2007 21:58:54 -0000 Subject: Querying Graphics Card Name In-Reply-To: <5i1f4cF3mbqqdU1@mid.individual.net> References: <1186686984.160312.175270@i13g2000prf.googlegroups.com> <5i1f4cF3mbqqdU1@mid.individual.net> Message-ID: <1186696734.059152.131080@d30g2000prg.googlegroups.com> On Aug 9, 3:26 pm, Bjoern Schliessmann <usenet- mail-0306.20.chr0n... at spamgourmet.com> wrote: > Benjamin Goldenberg wrote: > > I would like to find out the name of the graphics card of the > > machine my program is running on. I have looked into the pyopengl > > module, and using them to query the card, but it seems like there > > ought to be a simpler way to find this out without setting up a > > glcontext. Does anyone have any ideas? > > You could execute glxinfo and look for the renderer string. If > that's sharp enough for your purpose. Another option is lspci. I should have clarified. I would like a cross platform implementation, Windows and *nix. It doesn't seem as if glxinfo is available under Windows, at least not without installing X11 under cygwin. If necessary, I can write the *nix and Windows queries separately. Thanks, Benjamin From mikael at isy.liu.se Wed Aug 15 08:45:57 2007 From: mikael at isy.liu.se (Mikael Olofsson) Date: Wed, 15 Aug 2007 14:45:57 +0200 Subject: Combinatorial of elements in Python? In-Reply-To: <9e2f512b0708142203m782b0e10s817fb4d061ba0e46@mail.gmail.com> References: <9e2f512b0708142203m782b0e10s817fb4d061ba0e46@mail.gmail.com> Message-ID: <46C2F585.2010407@isy.liu.se> Sebastian Bassi wrote: > I have 2 (or more) groups of elements, and I want to get all possible > unique combinations from all of them. Is there a build-in method to do > it? > > ADictionary={"one":["A","B","C","D"],"two":["H","I"]} > > I want to have all possible combinations from "one" and "two", that is: > [snip] Not at all complicated. My solution: >>> A={'one':['A','B','C','D'],'two':['H','I']} >>> [x+y for x in A['one'] for y in A['two']] ['AH', 'AI', 'BH', 'BI', 'CH', 'CI', 'DH', 'DI'] HTH /MiO -- /Mikael Olofsson Universitetslektor (Senior Lecturer [BrE], Associate Professor [AmE]) Link?pings universitet ----------------------------------------------------------------------- E-Mail: mikael at isy.liu.se WWW: http://www.dtr.isy.liu.se/en/staff/mikael Phone: +46 - (0)13 - 28 1343 Telefax: +46 - (0)13 - 28 1339 ----------------------------------------------------------------------- Link?pings kammark?r: www.kammarkoren.com Vi s?ker tenorer och basar! From grflanagan at yahoo.co.uk Thu Aug 16 12:37:47 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: Thu, 16 Aug 2007 09:37:47 -0700 Subject: ploting issues in program In-Reply-To: <1187250500.571837.196940@19g2000hsx.googlegroups.com> References: <1187250500.571837.196940@19g2000hsx.googlegroups.com> Message-ID: <1187282267.317304.237010@57g2000hsv.googlegroups.com> On Aug 16, 9:48 am, yadin <conra2... at yahoo.com> wrote: > hi every one! > > can you please help me to fix these polar plot in db's > so that the center is at the minimun negative number in voltagedb > about [-50] > and the maximun is at zero and how can i see values on the axis like > showing that the axes start at -50 -40 -30 .....and end at zero > than you Just guessing, does plotting the following rectangular coords give you any insight? Seems to be a rough figure of eight. theta = [ 4.36332313e-003, 3.18522588e-001, 6.32681854e-001, 9.46841119e-001, 1.26100038e+000, 1.57515965e+000, 1.88931892e+000, 2.20347818e+000, 2.51763745e+000, 2.83179671e+000, 3.14595598e+000, 3.46011524e+000, 3.77427451e+000, 4.08843377e+000, 4.40259304e+000, 4.71675230e+000, 5.03091157e+000, 5.34507083e+000, 5.65923010e+000, 5.97338936e+000,] voltage = [ 0.00363471, 0.26569155, 0.52562334, 0.76330428, 0.93673361, 1. , 0.93321713, 0.75733232, 0.5185449 , 0.25840091, 0.00363471, 0.26569155, 0.52562334, 0.76330428, 0.93673361, 1. , 0.93321713, 0.75733232, 0.5185449 , 0.25840091,] from math import * #dbvoltage = [20*log10(1/v) for v in voltage] dbvoltage = [-20*log10(v) for v in voltage] def mkpoint(m, arg): return m*sin(arg), m*cos(arg) graph = [mkpoint(m,arg) for m, arg in zip(dbvoltage, theta)] for point in graph: print point (0.21288849842373814, 48.790140231909419) (3.6052811402858937, 10.933359102749559) (3.303355590073223, 4.505208562238618) (1.9039899333399253, 1.3706766199218816) (0.54065408491628131, 0.17306473975245495) (0.0, 0.0) (0.57014803194263397, -0.18800662846533356) (1.9469751572632745, -1.427581247329087) (3.3327193729963271, -4.6294392863200207) (3.5834113333756323, -11.194573773272479) (-0.21288865846549074, -48.790140231211105) (-3.6052811229041124, -10.933359108481211) (-3.3033556009317082, -4.5052085542768472) (-1.9039899297901561, -1.3706766248528219) (-0.54065408602566212, -0.17306473628675043) (0.0, 0.0) (-0.57014803261753888, 0.18800662641861987) (-1.9469751623879956, 1.4275812403398493) (-3.3327193896150562, 4.6294392743562476) (-3.5834113735618405, 11.194573760408771) Gerard From chris.hamons at gmail.com Sun Aug 26 17:31:01 2007 From: chris.hamons at gmail.com (chris.hamons at gmail.com) Date: Sun, 26 Aug 2007 21:31:01 -0000 Subject: Debugging a curses application in python In-Reply-To: <1188061484.516090.231200@q5g2000prf.googlegroups.com> References: <1188061484.516090.231200@q5g2000prf.googlegroups.com> Message-ID: <1188163861.942093.184120@57g2000hsv.googlegroups.com> Just to let anyone know who runs across this post, winpdb from (http:// www.digitalpeers.com/pythondebugger/) solved my issue. --Chris From grante at visi.com Wed Aug 15 18:23:20 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 15 Aug 2007 22:23:20 -0000 Subject: Colored text References: <1186970751.435970.189900@q3g2000prf.googlegroups.com> Message-ID: <13c6v6opp3mdcd8@corp.supernews.com> On 2007-08-13, Rohan <vodela.sai at gmail.com> wrote: > Hello, > Can some one tell me how do I get colored text. Say when I want to > write something in a text file , how do I get it colored. The PyRTF module supports colored text, and RTF is portable (mostly). -- Grant Edwards grante Yow! What I want to find at out is -- do parrots know visi.com much about Astro-Turf? From kyosohma at gmail.com Thu Aug 23 13:03:14 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 23 Aug 2007 10:03:14 -0700 Subject: comparing two lists In-Reply-To: <mailman.180.1187886381.32294.python-list@python.org> References: <mailman.180.1187886381.32294.python-list@python.org> Message-ID: <1187888594.076531.163410@l22g2000prc.googlegroups.com> On Aug 23, 11:27 am, Ladislav Andel <lad... at iptel.org> wrote: > Hi, > what would be the most efficient way to do following? > > I have a list of dictionaries taken from DB e.g. > dblist = [{'id:1, 'host':'google.com','ip_address':'1.2.3.4'}, > {'id:3, 'host':'yahoo.com','ip_address':'5.6.7.8'}, > {'id:9, 'host':'msn.com','ip_address':'11.3.2.3'}] > > and list of object instances in memory(it's just for example) > which are looping within itself and testing particular hosts > > memlist = [<instance 1>,<instance 2>] > memlist[0].id is 1 and memlist[0].host is google.com etc. > memlist[1].id is 9 and memlist[1].host is msn.com etc. > > Now I want to add a new instance to memlist since id=3(in dblist) is not > in memlist. > How would you iterate through it and insert a new instance? > > The result should be: > memlist = [<instance 1>,<instance 2>, <instance 3>] > memlist[0].id is 1 and memlist[0].host is google.com etc. > memlist[1].id is 3 and memlist[1].host is yahoo.com etc. > memlist[2].id is 9 and memlist[2].host is msn.com etc. > > Furthermore, I can have the opposite situation. > This time I need to remove from memlist a host which is not in dblist. > How would you do this? > > The way how it works is that DBlist is loaded every 10 minutes and > compares with memlist. > The memlist should be the same as dblist. > > Could you help me, please? > I'm working on my version of this but somebody might be quicker than me. > In case I have it done I will post it. > > Thanks, > Lada > > There is > > and wt On lists that change in memory, I use the following looping structure: for i in range(len(in_memory_list)-1,-1,-1) This loops over the list backwards. I found this method here: http://mail.python.org/pipermail/python-list/1999-September/012451.html Hopefully this will fulfill your needs. I've used it to great effect! Mike From ricaraoz at gmail.com Wed Aug 29 07:51:38 2007 From: ricaraoz at gmail.com (=?UTF-8?B?UmljYXJkbyBBcsOhb3o=?=) Date: Wed, 29 Aug 2007 08:51:38 -0300 Subject: encoding problems In-Reply-To: <fb3au1$v9m$1@lust.ihug.co.nz> References: <46d5215b$0$411$426a74cc@news.free.fr> <fb3au1$v9m$1@lust.ihug.co.nz> Message-ID: <46D55DCA.5040601@bigfoot.com> Lawrence D'Oliveiro wrote: > In message <46d5215b$0$411$426a74cc at news.free.fr>, tool69 wrote: > >> p2.content = """Ce poste poss?de des accents : ? ? ? ?""" > > My guess is this is being encoded as a Latin-1 string, but when you try to > output it it goes through the ASCII encoder, which doesn't understand the > accents. Try this: > > p2.content = u"""Ce poste poss?de des accents : ? ? ? ?""".encode("utf8") > is there a way to sort this string properly (sorted()?) I mean first 'a' then '?' then 'e' etc. (sorted puts accented letters at the end). Or should I have to provide a comparison function to sorted? From hyugaricdeau at gmail.com Mon Aug 20 17:56:22 2007 From: hyugaricdeau at gmail.com (Hyuga) Date: Mon, 20 Aug 2007 21:56:22 -0000 Subject: Symbolic Link In-Reply-To: <1187555373.202634.163160@57g2000hsv.googlegroups.com> References: <1187475296.173269.263080@k79g2000hse.googlegroups.com> <iwWxi.28394$RX.20505@newssvr11.news.prodigy.net> <1187555373.202634.163160@57g2000hsv.googlegroups.com> Message-ID: <1187646982.760523.195750@i38g2000prf.googlegroups.com> On Aug 19, 4:29 pm, mosscliffe <mcl.off... at googlemail.com> wrote: > The source file is in an area which python can see, but not the > browser. I am trying to make a link in a browser friendly area so I > can use it to display an image file. You might want to try using an .htaccess file. Place a file called .htaccess in the "browser friendly area" and place in it the line: Options +FollowSymLinks Assuming your hosting service will allow that, then it should work. If not, then why not just copy the image files? Storage is cheap these days. Hyuga From gagsl-py2 at yahoo.com.ar Tue Aug 28 19:18:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 28 Aug 2007 16:18:48 -0700 Subject: Chaining programs with pipe In-Reply-To: <13d84mghdg7990f@corp.supernews.com> References: <1187734166.384152.178040@o80g2000hse.googlegroups.com> <13cnbi87neru8c3@corp.supernews.com> <mailman.97.1187757319.32294.python-list@python.org> <13cogr3n6no937b@corp.supernews.com> <1187795716.083417.299540@q4g2000prc.googlegroups.com> <fau28j$gle$3@lust.ihug.co.nz> <mailman.51.1188274035.28954.python-list@python.org> <fb0alf$hgr$3@lust.ihug.co.nz> <1188290735.746264.280650@y42g2000hsy.googlegroups.com> <13d84mghdg7990f@corp.supernews.com> Message-ID: <1188343128.599432.174880@19g2000hsx.googlegroups.com> On 28 ago, 09:19, Grant Edwards <gra... at visi.com> wrote: > On 2007-08-28, Gabriel Genellina <gagsl-... at yahoo.com.ar> wrote: > > > On Windows, windowed applications (as opposed to console > > applications) start with no stdin/stdout/stderr by default. > > The application developer can modify that if desired, of > > course - I've menctioned some ways to do that. This fact > > simply means that those OS's *are* different - most of the > > time one can ignore the differences, but not always. Neither > > of them is doing the absolute "Right Thing". > > We're never going have any good flames with that sort of > attitude. ;) Does this help with the right attitude? "How serious can be a system where you can't say 'Open this file using my preferred application for it'"? "A 'stream of bytes' was not a good file metaphor even in the 70's - why still insist on that? How old-fashioned...! Ever read about ADS?" "Gay-Lussac's Law is not true in chemistry anymore - why insist on using small integers for all things? I got a PID from a process. I can see a running process with that same PID. Are they the same? Go figure!" - I got this file name from here. Could you please tell me which character encoding is it using? - Character encoding? What's that? - This name has some characters that aren't ASCII obviously, and I want to know how to interpret them. - Sorry, I can't help you. The only thing I can see here are byte sequences. - But how should I display them? The user is concerned with characters, not bytes! - I'm really sorry, there's nothing I can do. - Could you please forward my request to the file system then?!?! - FS has no answer either. - Fu"$&=)==)("$@2@! :-) -- Gabriel Genellina From llasram at gmail.com Thu Aug 16 02:30:45 2007 From: llasram at gmail.com (Marshall T. Vandegrift) Date: Thu, 16 Aug 2007 02:30:45 -0400 Subject: Coroutines and argument tupling References: <mailman.2032.1187207899.22759.python-list@python.org> <5ih63mF3pvnt7U1@mid.individual.net> <87k5rwo24e.fsf@seneca.iss.local> <1187224267.067743.52150@i13g2000prf.googlegroups.com> Message-ID: <87fy2kng8a.fsf@seneca.iss.local> "attn.steven.kuo at gmail.com" <attn.steven.kuo at gmail.com> writes: > Do you really need a generator or co-routine to do this? Maybe > you can just use a closure: For my trivial example, sure -- there are lots of ways to do it. Here's a slightly better example: the `read' method of a file-like object which sequentially joins the contents of a sequence of other file-like objects: @coroutine def read(self, size=-1): data = '' for file in self.files: this = file.read(size - len(data)) data = ''.join([data, this]) while this: if len(data) == size: _, size = (yield data) data = '' this = file.read(size - len(data)) data = ''.join([data, this]) yield data while True: yield '' -Marshall From arkanes at gmail.com Fri Aug 31 12:28:11 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 31 Aug 2007 11:28:11 -0500 Subject: strings (dollar.cents) into floats In-Reply-To: <fb9eas$tnc$1@sea.gmane.org> References: <mailman.140.1188483282.28954.python-list@python.org> <877incd20i.fsf@benfinney.id.au> <46d75cf3$0$7698$9b4e6d93@newsspool2.arcor-online.net> <1188575044.874256.42960@50g2000hsm.googlegroups.com> <fb9eas$tnc$1@sea.gmane.org> Message-ID: <4866bea60708310928nf54e60dqdd207ccafa8b8a6e@mail.gmail.com> On 8/31/07, Steve Holden <steve at holdenweb.com> wrote: > sturlamolden wrote: > > On 31 Aug, 02:12, Wildemar Wildenburger > > <lasses_w... at klapptsowieso.net> wrote: > > > >> I've heard (ok, read) that several times now and I understand the > >> argument. But what use is there for floats, then? When is it OK to use them? > > > > There are fractions that can be exactly represented by floats that > > cannot be exactly represented by decimals. > > Would you care to give an example? > > > There are fractions that > > can be exactly represented by decimals that cannot be exactly > > represented by floats. > > > > Which one is better? Which do we prefer? > > > > What a float cannot do is to represent a decimal fractional number > > (e.g. 1.1) exactly. If we need that, we cannot use floats. A notable > > example is monetary computations, it covers 99% of the use for decimal > > numbers in computers. For this reason, we should never use floats to > > add 10 cents to a dollar. The use of decimals for monetary > > calculations is mandatory. > > > That last sentence is patent nonsense, and completely untrue. Many > satisfactory financial applications have been written using only > floating-point arithmetic. Indeed I believe the accountant's Swiss army > knife, the Excel spreadsheet, uses floating-point numbers exclusively. > This is true, although Excel munges it's FP to provide "expected" results. It depends on what you consider a "financial" application though. Excel, while in extremely broad use, is not used to implement any of the systems which actually "define" money, like the back end financial systems at banks and credit unions. In my experience, by far the most common method of calculating financial numbers is actually using integer amounts, and then applying well-defined rounding rules which I can't be bothered to look up the name for. For what it's worth, the work that I do with money (which is middleware doing data transport, not calculations or billing) uses either string representations or fixed point. > What you say about floating-point have speed advantages is true, but you > go too far in claiming that decimal arithmetic is mandatory for monetary > calculations. That's about as sensible as saying that base 12 and base > 20 arithmetic units were required to calculate in pounds, shillings and > pence. > I believe that to the degree that "real" accounting was done in those currencies it did in fact use non-decimal bases. Just as people don't use decimal time values (except us crazy computer folk), you're write 1 pound 4 shillings, not 1.333... pounds. From kib2 at free.fr Wed Aug 29 04:53:08 2007 From: kib2 at free.fr (tool69) Date: Wed, 29 Aug 2007 10:53:08 +0200 Subject: encoding problems In-Reply-To: <5jkq6pF27cfU1@mid.uni-berlin.de> References: <46d5215b$0$411$426a74cc@news.free.fr> <5jkq6pF27cfU1@mid.uni-berlin.de> Message-ID: <46d534f4$0$5661$426a74cc@news.free.fr> Diez B. Roggisch a ?crit : > tool69 wrote: > >> Hi, >> >> I would like to transform reST contents to HTML, but got problems >> with accented chars. >> >> Here's a rather simplified version using SVN Docutils 0.5: >> >> %------------------------------------------------------------- >> >> #!/usr/bin/env python >> # -*- coding: utf-8 -*- > > > This declaration only affects unicode-literals. > >> from docutils.core import publish_parts >> >> class Post(object): >> def __init__(self, title='', content=''): >> self.title = title >> self.content = content >> >> def _get_html_content(self): >> return publish_parts(self.content, >> writer_name="html")["html_body"] >> html_content = property(_get_html_content) > > Did you know that you can do this like this: > > @property > def html_content(self): > ... > > ? > I only took some part of code from someone else (an old TurboGears tutorial if I remember). But you're right : decorators are better. >> # Instanciate 2 Post objects >> p1 = Post() >> p1.title = "First post without accented chars" >> p1.content = """This is the first. >> ...blabla >> ... end of post...""" >> >> p2 = Post() >> p2.title = "Second post with accented chars" >> p2.content = """Ce poste poss?de des accents : ? ? ? ?""" > > > This needs to be a unicode-literal: > > p2.content = u"""Ce poste poss?de des accents : ? ? ? ?""" > > Note the u in front. > > > You need to encode a unicode-string into the encoding you want it. > Otherwise, the default (ascii) is taken. > > So > > print post.html_content.encodec("utf-8") > > should work. > That solved it : thank you so much. > Diez From ninja.krmenadl at nes.com Mon Aug 20 15:14:54 2007 From: ninja.krmenadl at nes.com (Boris Ozegovic) Date: Mon, 20 Aug 2007 21:14:54 +0200 Subject: I Need help from all the group participants References: <fac7nj$ci9$1@localhost.localdomain> <mailman.0.1187630213.32294.python-list@python.org> <fack3a$7kk$1@ss408.t-com.hr> <1187636668.436474.289220@o80g2000hse.googlegroups.com> Message-ID: <facp6k$e0k$1@localhost.localdomain> dogatemycomputer at gmail.com wrote: > I would be happy to help but I don't have a clear understand of what > the poster needs. Suppose you want to find out what is someone's pulse/heart rate, you can ask question in many ways, syntaxically, but with same semantic. One way to find out someone's pulse is to ask: "What is John's pulse", other is "Please, tell me, what is Jonh's pulse", or "Send me John's pulse immediatelly!", etc. So, if you can write some other question to find out someone's pulse, please do, but, it would be great if your question would have different pattern, e.g. "Please, tell me John's pulse immediatelly" and "Tell me John's pulse right now" have the same pattern, because they are syntaxically very alike. -- Ne dajte da nas la?ljivac Bandi? truje: http://cnn.blog.hr/arhiva-2007-06.html#1622776372 From mcl.office at googlemail.com Sat Aug 25 05:57:24 2007 From: mcl.office at googlemail.com (mosscliffe) Date: Sat, 25 Aug 2007 02:57:24 -0700 Subject: Joining Big Files Message-ID: <1188035844.616831.205350@i38g2000prf.googlegroups.com> I have 4 text files each approx 50mb. I need to join these into one large text file. I only need to do this very occasionally, as the problem has occurred because of upload limitations. Bearing in mind filesize and memory useage, would I be better reading every line in every file and writing each line to the output file or is there someway I could execute some shell command. I am working on a hosted website with no direct telnet or similar access. I would appreciate any tips, best code, as I do not want to break anything on the website. Richard From stef.mientki at gmail.com Tue Aug 14 13:39:02 2007 From: stef.mientki at gmail.com (stef mientki) Date: Tue, 14 Aug 2007 19:39:02 +0200 Subject: LEGB rule, totally confused ... In-Reply-To: <3u*sChSr@news.chiark.greenend.org.uk> References: <mailman.1959.1187094797.22759.python-list@python.org> <3u*sChSr@news.chiark.greenend.org.uk> Message-ID: <46C1E8B6.6060402@gmail.com> Sion Arrowsmith wrote: > stef mientki <stef.mientki at gmail.com> wrote: > >> def Run (): >> print X <=== UnboundLocalError: local variable >> 'X' referenced before assignment >> X = X + 1 >> >> Why do I get the error ? >> Printing isn't assigning anything or am I missing something. >> Now if I remove "X = X + 1" I don't get an error ??? >> > > Several people have already explained the scoping rules acting > here, but let's just look at how that error message is telling > you everything you need to know to fix the problem. > > "local variable 'X' referenced before assignment" > > "local variable 'X'" immediately tells you that the 'X' in > question is not your global 'X'. > > "referenced before assignment": well, 'print X' is surely a > reference to 'X', and 'X = X + 1' is an assignment to it, > and 'print X' appears before 'X = X + 1'. That this is the > key you have confirmed experimentally. > > The question to ask here is "Why does Python think 'X' is > local?" Everything else is answered by the error message. > > Thanks guys, I beginning to see the light again, and if X is mutual the story is completely different, I still have to get used to these differences. cheers, Stef Mientki From arkanes at gmail.com Thu Aug 16 14:43:14 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 16 Aug 2007 13:43:14 -0500 Subject: Accessing Windows Network Share? In-Reply-To: <1187287133.737105.169960@19g2000hsx.googlegroups.com> References: <1187287133.737105.169960@19g2000hsx.googlegroups.com> Message-ID: <4866bea60708161143u7bce6c01o97397abfb07aa8ee@mail.gmail.com> On 8/16/07, frikk <frikker at gmail.com> wrote: > I previously posted about accessing SharePoint over the web. Well I > have since given up any easy means of doing this, since something else > has perked my interest. Instead of going to http://sharepoint/site, > why not just access \\sharepoint\site\ directly? > > So my question is this - How do I access that network share? > > If I go to start -> run, and type in "\\SharPointServer\Site\Folder", > windows explorer will pop up with it. I suppose I could have a little > batch script that python runs to map the drive to a local letter, like > J:, but this does not seem necessary. > > Suggestions? > > This does not work, for obvious reasons: > >>> import glob.glob > >>> glob.glob("\\\\server\\folder\\*") > [] > I don't see whats "obvious" about this. Access to windows shares is handled by Windows in a VFS layer, and glob and all other Python file access works fine over them for me. From bignose+hates-spam at benfinney.id.au Fri Aug 10 10:38:39 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 11 Aug 2007 00:38:39 +1000 Subject: The Future of Python Threading References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> Message-ID: <87ir7n4fps.fsf@benfinney.id.au> "Justin T." <jmtulloss at gmail.com> writes: > The truth is that the future (and present reality) of almost every > form of computing is multi-core, and there currently is no effective > way of dealing with concurrency. Your post seems to take threading as the *only* way to write code for multi-core systems, which certainly isn't so. Last I checked, multiple processes can run concurrently on multi-core systems. That's a well-established way of structuring a program. > We still worry about setting up threads, synchronization of message > queues, synchronization of shared memory regions, dealing with > asynchronous behaviors, and most importantly, how threaded an > application should be. All of which is avoided by designing the program to operate as discrete processes communicating via well-defined IPC mechanisms. -- \ "I can picture in my mind a world without war, a world without | `\ hate. And I can picture us attacking that world, because they'd | _o__) never expect it." -- Jack Handey | Ben Finney From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Aug 21 05:47:50 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 21 Aug 2007 11:47:50 +0200 Subject: The folder a script is executed in References: <1187687436.476773.276550@22g2000hsm.googlegroups.com> <1187688437.358293.322460@22g2000hsm.googlegroups.com> Message-ID: <5ivqm3F3rg15jU1@mid.individual.net> Ant wrote: > Do you mean the folder containing the script? Or the current > working directory? > > If the former, then look at os.path.split(sys.argv[0])[0] test.py: | #!/usr/bin/env python | import sys,os | print os.path.split(sys.argv[0])[0] $ cd tmp ~/tmp$ ../test.py .. ~/tmp$ That's rather not what's intended. I'd try os.path.abspath(__file__) instead. Regards, Bj?rn -- BOFH excuse #113: Root nameservers are out of sync From pyth0nc0d3r at gmail.com Thu Aug 23 16:55:09 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Thu, 23 Aug 2007 15:55:09 -0500 Subject: How would I compile a Python file to a exe Message-ID: <eb79828c0708231355o72f9b200g74036aca19f1806c@mail.gmail.com> Been a while and I'm wondering how I would go about doing it. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070823/9acd2641/attachment.html> From grante at visi.com Tue Aug 21 23:32:24 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 22 Aug 2007 03:32:24 -0000 Subject: Chaining programs with pipe References: <1187734166.384152.178040@o80g2000hse.googlegroups.com> Message-ID: <13cnbi87neru8c3@corp.supernews.com> On 2007-08-21, avishay <avishorp at yahoo.com> wrote: > I'm trying to chain two programs with a pipe (the output of > one feeding the input of the other). I managed to capture the > output and feeding the input of each program independently > with popen, but how do I tie them together? On Unix, you do the same thing you would in C. Create a pipe using os.pipe(), then run one program with stdout connected to the "write" end of the pipe and the other program with stdin connected to the "read" end of the pipe. Or you can take a bit of a shortcut by letting the subprocess module create the pipe for you: http://docs.python.org/lib/node536.html > Is there a solution that works equally on all platforms? The doc page for subprocess doesn't say what platforms support it. I've had a lot of problems trying to use the subprocess module on windows. As is typical for Windows, there are all sorts of special cases that either don't work at all or don't work the way they should. You pays your money and you takes your chances. -- Grant Edwards grante Yow! Sorry, wrong ZIP at CODE!! visi.com From deets at nospam.web.de Sun Aug 19 13:14:40 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 19 Aug 2007 19:14:40 +0200 Subject: Hot subject: a good python editor and/or IDE? In-Reply-To: <mailman.2166.1187530711.22759.python-list@python.org> References: <mailman.2162.1187525764.22759.python-list@python.org> <5iqreuF3qanv6U1@mid.individual.net> <mailman.2166.1187530711.22759.python-list@python.org> Message-ID: <5irc4bF3qvd9qU1@mid.uni-berlin.de> Buchoux S?bastien schrieb: > Bjoern Schliessmann wrote: >> S?bastien wrote: >> >>> I am currently using Eclipse+PyDev when developping Python >>> projects but I lack a fast, simple editor for tiny bit of scripts. >>> So here is my question: what is, for you, the current best ( but >>> still kind of light! ) Python editor/IDE ? >>> >> >> vim >> >> BTW, this is an FAQ. Please look through the archives for many >> threads with many, many IDEs. >> >> Regards, >> >> >> Bj?rn >> >> > Yeah, I know this is a FAQ, but, as you mention, there is a whole bunch > of editors, every one of them being updated constantly (+ the new ones > getting out). So I am quite sure that looking through the archives is > THE solution since it will only reflect what people thought when > question was asked. Just type "best Python editor" on Google and you > will see that almost all hits are completely out of date. > Fair enough though! ;) http://groups.google.de/group/comp.lang.python/browse_thread/thread/77285bd20fafbf2b/75bf35b712b1432b?lnk=st&q=python+editor+comp.lang.python&rnum=1#75bf35b712b1432b Six weeks don't strike me as "completely out of date". Diez From pablo.mitchell at gmail.com Sun Aug 5 18:29:00 2007 From: pablo.mitchell at gmail.com (pablo.mitchell at gmail.com) Date: Sun, 05 Aug 2007 15:29:00 -0700 Subject: Efficient Rank Ordering of Nested Lists In-Reply-To: <1i2c5qo.ynsani1aobwaN%aleax@mac.com> References: <1186104049.022836.253470@e9g2000prf.googlegroups.com> <1i29gpw.1vh7eku1iauistN%aleax@mac.com> <1186279182_8217@sp12lax.superfeed.net> <1i2c5qo.ynsani1aobwaN%aleax@mac.com> Message-ID: <1186352940.618342.219710@x40g2000prg.googlegroups.com> On Aug 4, 7:29 pm, al... at mac.com (Alex Martelli) wrote: > Cousin Stanley <cousinstan... at gmail.com> wrote: > > ... > > > for i , item in reversed( enumerate( sorted( single_list ) ) ) : > ... > > TypeError: argument to reversed() must be a sequence > > Oops, right. Well then, > > aux_seq = list(enumerate(sorted(single_list))) > for i, item in reversed(aux_seq): ... > > or the like. > > Alex The particular embedded list I have been tinkering with is 43 x 3884 and the dictionary approach (as you can probably guess) is a big improvement over the linear one. It also has the added benefit of being compatible with Python24. If I'm not mistaken the binary approach suggested by Neil requires Python25. Since in some situations I don't have control over the version available I will go with a variant of the dictionary recipe. From steve at holdenweb.com Thu Aug 2 06:36:45 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 02 Aug 2007 06:36:45 -0400 Subject: DBUtil with modepython In-Reply-To: <1186031736.489064.287430@22g2000hsm.googlegroups.com> References: <1186031736.489064.287430@22g2000hsm.googlegroups.com> Message-ID: <f8sc41$ac9$1@sea.gmane.org> cpmishra wrote: > Hi all > I have used DBUtil in mysql databse. when we run to program in > dos command ,successfully run but when we run in apache server > (locally)with modepython then given error.Pls give me suggation > > error: > No module named DBUtils.PooledDB > It seems likely that the web environment doesn't include the directory containing the DBUtils (DBUtil?) in the PYTHONPATH variable. Try running this script as a CGI: print "Content-Type: text/plain\n" import os for val in os.environ.items(): print "%s=%s" % val and see what PYTHONPATH looks like. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From ehsan.khoddam at gmail.com Sat Aug 4 10:10:10 2007 From: ehsan.khoddam at gmail.com (Ehsan) Date: Sat, 04 Aug 2007 07:10:10 -0700 Subject: regexp problem in Python In-Reply-To: <1186222973.073756.300890@r34g2000hsd.googlegroups.com> References: <1186177312.117581.129910@d55g2000hsg.googlegroups.com> <1186222973.073756.300890@r34g2000hsd.googlegroups.com> Message-ID: <1186236610.438810.230580@22g2000hsm.googlegroups.com> On Aug 4, 1:22 pm, S?nmez Kartal <rainwatch... at gmail.com> wrote: > On 4 A ustos, 00:41, Ehsan <ehsan.khod... at gmail.com> wrote: > > > > > > > I want to find "http://www.2shared.com/download/1716611/e2000f22/ > > Jadeed_Mlak14.wmv?tsid=20070803-164051-9d637d11" or 3gp instead of > > wmv in the text file like this : > > <html> > > ""some code"" > > function reportAbuse() { > > var windowname="abuse"; > > var url="/abuse.jsp?link=" + "http://www.2shared.com/file/1716611/ > > e2000f22/Jadeed_Mlak14.html"; > > OpenWindow = > > window.open(url,windowname,'toolbar=no,scrollbars=no,resizable=no,width=500?,height=500,left=50,top=50'); > > OpenWindow.focus(); > > } > > function startDownload(){ > > window.location = "http://www.2shared.com/download/1716611/ > > e2000f22/Jadeed_Mlak14.wmv?tsid=20070803-164051-9d637d11"; > > //document.downloadForm.submit(); > > } > > </script> > > </head> > > </html>http://www.2shared.com/download/1716611/e2000f22/ > > Jadeed_Mlak14.3gp?tsid=20070803-164051-9d637d11"sfgsfgsfgv > > > I use this pattern : > > "http.*?\.(wmv|3gp).*"" > > > but it returns only 'wmv' and '3gp' instead of "http://www.2shared.com/ > > download/1716611/e2000f22/Jadeed_Mlak14.wmv? > > tsid=20070803-164051-9d637d11" > > > what can I do? what's wrong whit this pattern? thanx for your comments > > You could use r'window.location = "(.*?\.(wmv|3gp)";' as your regex > string, I guess..- Hide quoted text - > > - Show quoted text - I didn't get what do you mean? i think i must just change the pattern but I don't know how to find bestfit pattern From ratchetgrid at googlemail.com Thu Aug 16 03:09:39 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Thu, 16 Aug 2007 08:09:39 +0100 Subject: Problem using Optional pyparsing Message-ID: <676224240708160009i3561f8dcid3c62f4f60b850d5@mail.gmail.com> Hi, I know this isnt the pyparsing list, but it doesnt seem like there is one. I m trying to use pyparsing to parse a file however I cant get the Optional keyword to work. My file generally looks like this: ALIGNMENT 1020 YS2-10a02.q1k chr09 1295 42 141045 142297 C 1254 95.06 1295 reject_bad_break 0 or this: ALIGNMENT 36 YS2-10a08.q1k chrm 208 165 10745 10788 C 44 95.45 593 reject_low 10,14 and my grammar work well for these lines, however somethings the row looks like: ALIGNMENT 53 YS2-10b03.p1k chr12 180 125 1067465 1067520 C 56 98.21 532|5,2 reject_low 25 So I try to parse the 532 using from pyparsing import * integer = Word( nums ) float = Word( nums+".") identifier = Word( alphanums+"-_." ) alignment = Literal("ALIGNMENT ").suppress() row_1 = integer.setResultsName("row_1")#.setParseAction(make_int) src_id = identifier.setResultsName("src_id") dest_id = identifier.setResultsName("dest_id") src_start = integer.setResultsName("src_start")#.setParseAction(make_int) src_stop = integer.setResultsName("src_stop")#.setParseAction(make_int) dest_start = integer.setResultsName("dest_start")#.setParseAction(make_int) dest_stop = integer.setResultsName("dest_stop")#.setParseAction(make_int) row_8 = oneOf("F C").setResultsName("row_8") length = integer.setResultsName("length")#.setParseAction(make_int) percent_id = float.setResultsName("percent_id")#.setParseAction(make_float) row_11 = integer + Optional(Literal("|") + commaSeparatedList ) )#.setResultsName("row_11")#.setParseAction(make_int) result = Word(alphas+"_").setResultsName("result") row_13 = commaSeparatedList.setResultsName("row_13") def make_alilines_status_parser(): return alignment + row_1 + src_id + dest_id + src_start + src_stop + dest_start + dest_stop + row_8 + length + percent_id + row_11 + result + row_13 def parse_alilines_status(ifile): alilines = make_alilines_status_parser() for l in ifile: yield alilines.parseString( l ) However my parser always fails on lines of type 3. Does anyone know why the Optional part is not working. Many Thanks in advance Nathan From alanmk at hotmail.com Tue Aug 14 13:54:58 2007 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 14 Aug 2007 10:54:58 -0700 Subject: JPype - passing to Java main In-Reply-To: <1187097639.176267.33050@d55g2000hsg.googlegroups.com> References: <1187040070.806416.75090@r34g2000hsd.googlegroups.com> <mailman.1941.1187047345.22759.python-list@python.org> <1187095969.789811.63960@j4g2000prf.googlegroups.com> <f9s972$hd2$1@news2.u-psud.fr> <1187097639.176267.33050@d55g2000hsg.googlegroups.com> Message-ID: <1187114098.399251.62790@22g2000hsm.googlegroups.com> > -------------ERROR_------------- > File "tester.py", line 10, in <module> > com.JPypeTest.main("arg") > RuntimeError: No matching overloads found. at src/native/common/ > jp_method.cpp:121 > ----------END ERROR------------- I haven't used jpype, but the signature for java main functions is public static void main (String [] args) So try com.JPypeTest.main(["arg"]) Note the addition of square brackets to create a *list* of arguments, which presumably jpype will transform into a java String[]. Alan. From kyosohma at gmail.com Fri Aug 24 11:49:12 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 24 Aug 2007 08:49:12 -0700 Subject: creating a tar file with python In-Reply-To: <mailman.256.1187969609.32294.python-list@python.org> References: <93066C069973ED448DC2BCEA9C44A7383BE2EB@efmailx> <faktv8$8fs$1@sea.gmane.org> <93066C069973ED448DC2BCEA9C44A7383BE2ED@efmailx> <46CE4D3D.7020106@holdenweb.com> <93066C069973ED448DC2BCEA9C44A7383BE2EE@efmailx> <1187969070.3385.20.camel@dot.uniqsys.com> <mailman.256.1187969609.32294.python-list@python.org> Message-ID: <1187970552.537218.202160@x35g2000prf.googlegroups.com> On Aug 24, 10:33 am, Ed Leafe <e... at leafe.com> wrote: > On Aug 24, 2007, at 11:24 AM, Carsten Haese wrote: > > > You clearly have no idea who you're talking to. I suggest you > > Google for > > '"Steve Holden" Python' to get a clue. Good luck finding any more help > > here. > > Even if it were Joe Nobody to whom he was directing those comments, > it was *way* out of line. The fact that it was Steve only reinforces > the cluelessness of the writer. > > -- Ed Leafe > --http://leafe.com > --http://dabodev.com Where is this guy posting his code? I see a lot of responses from Steve and Gabriel to posts that never seem to begin anywhere. Are these posts originating from the noob python list and somehow getting cross-posted here? I like Steve, but he seems pretty crabby/rude much of the time. Mike From deets at nospam.web.de Wed Aug 8 09:21:59 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 08 Aug 2007 15:21:59 +0200 Subject: How to avoid reverse code engineering of a python executable References: <1186573228.419760.272240@k79g2000hse.googlegroups.com> <5htp32F3md0abU2@mid.uni-berlin.de> Message-ID: <5htubnF3lttkaU1@mid.uni-berlin.de> Marc 'BlackJack' Rintsch wrote: > On Wed, 08 Aug 2007 11:40:28 +0000, NicolasG wrote: > >> Couple of day's ago I asked for your help on how to create a single >> file of a python executable. Now I want to proceed a little bit >> further asking how can I avoid (or at least make it difficult) for >> some one to extract my code by using reverse code engineer techniques? >> I came on pyobfuscate but I would like more suggestions and guide to >> achieve the most possible security in this matter. > > Just don't deliver the code at all but provide a webservice. > > Everything else can be reverse engineered and possibly will be if it is > worth the trouble. Most things aren't. Even if one thinks so. The efforts put into reverse engineering software usually don't stem from the desire to rip code one couldn't write self, but to e.g. circumvene registration keys or otherwise locked software. Diez From steven.bethard at gmail.com Mon Aug 13 12:26:22 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 13 Aug 2007 10:26:22 -0600 Subject: is there anybody using __del__ correctly?? In-Reply-To: <1186984722.604498.39490@q75g2000hsh.googlegroups.com> References: <1186731369.073644.158490@z24g2000prh.googlegroups.com> <1186762908.121319.35900@x35g2000prf.googlegroups.com> <SradnX_-hI91BiHbnZ2dnUVZ_r6rnZ2d@comcast.com> <1186895084.388293.295330@57g2000hsv.googlegroups.com> <0M2dnWsFO7-zwSLbnZ2dnUVZ_ryqnZ2d@comcast.com> <1186984722.604498.39490@q75g2000hsh.googlegroups.com> Message-ID: <gdSdnYEt6sysG13bnZ2dnUVZ_hynnZ2d@comcast.com> Michele Simionato wrote: > SPECIALMETHODS = ['__%s__' % name for name in > ''' > abs add and call concat contains delitem delslice div eq floordiv ge > getitem > getslice gt iadd iand iconcat idiv ifloordiv ilshift imod imul index > inv invert > ior ipow irepeat irshift isub iter itruediv ixor le len lshift lt mod > mul ne neg > not or pos pow repeat repr rshift setitem setslice str sub truediv > xor > '''.split()] > > def add_special_method(cls, name): > def meth(self, *args): > return getattr(self, name)(*args) > meth.__name__ = name > setattr(cls, name, meth) > for name in SPECIALMETHODS: > add_special_method(Impostor, name) > > In this way the Impostor can emulate even the special methods. Here is > an example: > >>>> class C(object): > ... > pass > ... >>>> c=Impostor(C()) >>>> print c > <__main__.C object at 0x102a390> > > Notice that the impostor is calling the __str__ method of C, so it > really looks like a C object. Moreover > >>>> c.__class__ > <class '__main__.C'> > > and > >>>> isinstance(c, C) > True > > so the Impostor is doing a damn pretty good job of imposture for C > objects. Of course it does what it can, and it cannot impersonate C > objects completely: > >>>> type(c) > <class '__main__.Impostor'> > > so code using checks like ``type(c) is C`` would break and the > approach here cannot be considered more than a hack. That's fun. =) I don't really think it's too much of a hack either. ``type(c) is C`` is expected to fail for proxy classes, which is why everyone keeps getting told to use ``isinstance(c, C)`` instead. In Py3K, when ``isinstance`` becomes overloadable, it's going to be even more of a mistake to write ``type(c) is C``. That said, I doubt I'd want to slow down all attribute access on my class just to do some cleanup, when it's probably better to just tell everyone to use a ``with`` block. ;-) STeVe From sbellon at sbellon.de Thu Aug 2 15:15:38 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Thu, 2 Aug 2007 21:15:38 +0200 Subject: Catching SystemExit in C API code when embedding Python? References: <20070802141906.2581c099@cube.tz.axivion.com> Message-ID: <20070802211538.142fc74b@cube.tz.axivion.com> First of all, I'm sorry to followup my own posting, but I can add a few things ... On Thu, 02 Aug, Stefan Bellon wrote: > As in Python itself you can catch SystemExit, I think this should be > the way to go. But how do I catch this exception from within the C > API? I now installed an exception hook in sys.excepthook on the C side. And indeed, it gets called whenever an exception is raised ... but not when SystemExit is raised. And indeed, in PyErr_PrintEx in pythonrun.c I found the following: hook = PySys_GetObject("excepthook"); if (hook) { PyObject *args = PyTuple_Pack(3, exception, v ? v : Py_None, tb ? tb : Py_None); PyObject *result = PyEval_CallObject(hook, args); if (result == NULL) { PyObject *exception2, *v2, *tb2; if (PyErr_ExceptionMatches(PyExc_SystemExit)) { handle_system_exit(); } But ... then my original question becomes even stronger: How do I "catch" a SystemExit when embedding Python and not wanting that a script with sys.exit just terminates the whole application? -- Stefan Bellon From steve at holdenweb.com Mon Aug 6 14:18:00 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 06 Aug 2007 14:18:00 -0400 Subject: Tkinter or wxpython? In-Reply-To: <4866bea60708061043x34fb94edg8b675eb1608af9b1@mail.gmail.com> References: <op.tv98rva4wepdt4@ericb.pragmadev> <mailman.1550.1186099225.22759.python-list@python.org> <1186410331.905174.21370@q3g2000prf.googlegroups.com> <7xps204tin.fsf@ruckus.brouhaha.com> <mailman.1677.1186412323.22759.python-list@python.org> <7xlkcopu4r.fsf@ruckus.brouhaha.com> <mailman.1680.1186416061.22759.python-list@python.org> <7x3aywr4tc.fsf@ruckus.brouhaha.com> <4866bea60708061043x34fb94edg8b675eb1608af9b1@mail.gmail.com> Message-ID: <f97okn$qve$1@sea.gmane.org> Chris Mellon wrote: > On 06 Aug 2007 09:44:15 -0700, Paul Rubin > <"http://phr.cx"@nospam.invalid> wrote: >> "Chris Mellon" <arkanes at gmail.com> writes: [...] >> Again, it all depends on what you're trying to do. For data entry >> stuff you probably want the data on a remote server anyway, and you >> can do basic CRUD validation with fairly simple javascript. Maybe >> that departs from pure HTML but it's nothing like the ajax/dhtml >> madness that causes the problems you've described. >> -- > > CRUD with javascript is something I actually have a lot of experience > with. Deficiencies in the data entry UI have real consequences because > you get invalid data and slow data entry speeds. The auto-completing > combo-box, for example, is simply impossible in a browser without > quite complicated (and slow) DHTML and is a huge boon for data entry. > It's not even that easy in wxPython is you choose the wrong widget - I tried to make a combo box accept text and select the drop-down elements from a database and it turned out to be way too tricky to manage easily. Having said that, I quickly discovered superior alternatives once I got rid of my "it has to be a combo box" mentality. While great GUIs have been created as web front-ends it is substantially more difficult to create them than it is with a simple-ish GUI toolkit like wxPython, particularly with a GUI designer like wxDesigner behind it. > I'm not trying to claim that there are no benefits to web > applications. But I often see people touting the web as a *superior > application platform*, which is simply false, and as innately simpler > to develop for, which is also false. I would agree. The inherent state-maintenance and interaction problems have caused the ASP.NET model to be somewhat counterintuitive, to say the least, though it *has* made it easier to build complex interfaces that it is on the "raw web". As with all such things, though, once you run into the limits of the model, the promise of "point-and-click programming" rapidly becomes a dim memory. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From horpner at yahoo.com Tue Aug 7 14:31:46 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 07 Aug 2007 18:31:46 GMT Subject: Dealing with multiple excel sheets References: <1186509914.117596.249330@j4g2000prf.googlegroups.com> Message-ID: <slrnfbhe9b.so.horpner@FIAD06.norwich.edu> On 2007-08-07, Rohan <vodela.sai at gmail.com> wrote: > I would like to write a script which does the following job. > Take column1 and 7 from 10 different excel sheets and pasthe > them into a new excel worksheet. Any ideas on how to do it Get the xlrd Python module. It'll come in handy. -- Neil Cerutti From tjreedy at udel.edu Fri Aug 3 15:18:43 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 3 Aug 2007 15:18:43 -0400 Subject: Trying to find zip codes/rest example References: <f8vhct$3g6$1@sea.gmane.org> Message-ID: <f8vv2k$i1f$1@sea.gmane.org> "VanL" <van.lindberg at gmail.com> wrote in message news:f8vhct$3g6$1 at sea.gmane.org... | | I now cannot find this demo and the associated discussion. Does anybody | remember this demo and where I might be able to find it? No, but does the localflavor entry on http://code.djangoproject.com/browser/django/trunk/docs/add_ons.txt?rev=5118 help? (found with Google) From ldo at geek-central.gen.new_zealand Sat Aug 25 08:55:35 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 26 Aug 2007 00:55:35 +1200 Subject: Threading problem when many sockets open References: <mailman.1865.1186871554.22759.python-list@python.org> Message-ID: <fap8nk$ue4$2@lust.ihug.co.nz> In message <mailman.1865.1186871554.22759.python-list at python.org>, Philip Zigoris wrote: > ... and the server > would go into a state where the master thread repeatedly polled the > socket and printed an error. Is that because it cannot create a new socket to accept the connection on? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Aug 24 11:05:12 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 24 Aug 2007 17:05:12 +0200 Subject: Server-side scripting in python In-Reply-To: <1187954190.571860.85920@m37g2000prh.googlegroups.com> References: <1187614732.519547.296020@j4g2000prf.googlegroups.com> <gi6rp4-mes.ln1@lairds.us> <1187755436.972359.293360@i13g2000prf.googlegroups.com> <0k2up4-lla.ln1@lairds.us> <1187843960.922925.127990@i13g2000prf.googlegroups.com> <46ceb673$0$415$426a74cc@news.free.fr> <1187954190.571860.85920@m37g2000prh.googlegroups.com> Message-ID: <46cef36a$0$431$426a34cc@news.free.fr> olive a ?crit : >> Yes : have a look at Pylons too. It's actually quite less 'polished' >> than Django, but it's IMHO going in the right direction (as a matter of >> fact, Turbogears 2.0 - another well-known Python MVC framework - will >> be based on Pylons...). Django is clearly more oriented toward >> content-management, which might not be what you want for this project. > > this opinion about Django is a little bit dated Possibly. I worked with pre 1.0 versions, then switched to other solutions (there were things I didn't like that much in Django... personal taste, not a criticism). > > Django is really multi-purpose and is rarely use as a CMS, (snip) > I would use Plone instead as a general CMS. I meant it was more oriented toward *building* CMS - not that it was a CMS by itself. And as far as I'm concerned, I would not use Plone without *really* needing such a heavyweight thingie (and yes, I do have recent working experience with Plone...). From wolf_tracks at invalid.com Thu Aug 23 10:38:56 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 23 Aug 2007 14:38:56 GMT Subject: Baby Steps, optionDB In-Reply-To: <mailman.169.1187874026.32294.python-list@python.org> References: <Uk7zi.1531$vU4.979@nlpi068.nbdc.sbc.com> <1187862216.183609.89810@r23g2000prd.googlegroups.com> <Pcezi.6450$924.6108@newssvr23.news.prodigy.net> <mailman.169.1187874026.32294.python-list@python.org> Message-ID: <4_gzi.30161$RX.21287@newssvr11.news.prodigy.net> VBasic is the same. Longish. The ultimate in conciseness was APL. Carsten Haese wrote: > On Thu, 2007-08-23 at 04:30 -0700, W. Watson wrote: >> I used to program in C++, and there's one thing I've never liked about >> OOP. Too much typing! > > Blame C++, not OOP. In time, you will find that Python's approach to OOP > in particular and to programming in general allows you to express your > ideas more concisely than you could in other programming languages. > -- Wayne Watson (Nevada City, CA) Web Page: <speckledwithStars.net> From arkanes at gmail.com Fri Aug 10 15:46:26 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 10 Aug 2007 14:46:26 -0500 Subject: wxPython before MainLoop In-Reply-To: <6a6dnfbbFJNzcCbbnZ2dnUVZ_oudnZ2d@comcast.com> References: <13bl9a75laqcm70@corp.supernews.com> <6a6dnfbbFJNzcCbbnZ2dnUVZ_oudnZ2d@comcast.com> Message-ID: <4866bea60708101246w3026d6f4k53cf66745fe813cc@mail.gmail.com> On 8/9/07, Heikki Toivonen <heikki at osafoundation.org> wrote: > [david] wrote: > > I'd like to refresh the display before I start the main loop. > > We have this kind of situation in Chandler, where we display and update > the splash screen before we enter MainLoop. > > 1. Create app object > http://lxr.osafoundation.org/source/chandler/Chandler.py#080 > > 2. During app object creation, in OnInit, put up splash screen and update it > > http://lxr.osafoundation.org/source/chandler/application/Application.py#433 > > 3. The splash screen refresh is basically: draw new stuff, > self.Layout(), self.Update(), wx.Yield() > http://lxr.osafoundation.org/source/chandler/application/Application.py#1421 > > 3. Start MainLoop > http://lxr.osafoundation.org/source/chandler/Chandler.py#086 > wxYield spins the event loop in place. This can have some serious consequences if you aren't very careful with your usage, like recursively entering event handlers. I generally consider it an experts only interface, and avoid it. Thankfully, in Python 2.5 you can do some very nice things with Pythons generators. Basically, replace your wxYielding code with a python generator that just yields where you used to wxYield, and then call your generator repeatedly with wx.CallAfter. Here's an (unpolished) example of a progress dialog that is updated via generator: import wx def startupTask(): for ii in xrange(1001): cont, skip = yield ii, "step %s"%str(ii) if not cont: raise StopIteration class GeneratorProgress(wx.ProgressDialog): """ Progress dialog fed via generator. Task let should be a python generator that yields (value, message) tuples and is sent (continue, skip) tuples, as per the arguments to and return values from the wx.ProgressDialog.Update method. """ def __init__(self, title, message, tasklet, *args, **kwargs): super(GeneratorProgress, self).__init__(title, message, *args, **kwargs) self.tasklet = tasklet wx.CallAfter(self.iterate) def iterate(self, cont=None, skip=None): try: if cont is None and skip is None: value, msg = self.tasklet.next() else: value, msg = self.tasklet.send((cont, skip)) cont, skip = self.Update(value, msg) wx.CallAfter(self.iterate, cont, skip) except StopIteration: self.Destroy() def main(): app = wx.App(False) f = wx.Frame(None) pg = GeneratorProgress("Startup", "running task...", startupTask(), parent=f, maximum=1000) pg.Show() f.Show() app.MainLoop() if __name__ == '__main__': main() From bronger at physik.rwth-aachen.de Fri Aug 24 11:59:22 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 24 Aug 2007 17:59:22 +0200 Subject: Co-developers wanted: document markup language References: <87odgyyx9u.fsf@wilson.homeunix.com> <87tzqpew22.fsf@wilson.homeunix.com> <fal3cv$bi2$1@panix3.panix.com> <87tzqp77my.fsf@wilson.homeunix.com> <famljb$1d9$1@panix3.panix.com> Message-ID: <87y7g0udnp.fsf@wilson.homeunix.com> Hall?chen! Aahz writes: > Torsten Bronger <bronger at physik.rwth-aachen.de> wrote: > >> [...] >> >> reStructuredText, AsciiDoc, and some others focus on source code >> documentation, or on software documentation. In contrast to >> that, our markup should be suitable for PhD theses, papers and >> the like. Thus, it has weaker means for code snippets, RFC >> citation etc, but rich syntax for bibliographic entries, index >> entries, math, and floating figures. > > Enh. reST is intended to be a general-purpose system. It's > certainly extensible, and I've added code for index entries > myself. I like reST very much, and it is used for all documentation in the "Gummi" source files. I could probably use it as a starting point for the features that I want but the same is true for AsciiDoc or MediaWiki. I doubt, however, that the resulting syntax is what I want (see below). > There has been some recent activity on improving bibliographic > support, and I believe some people are working on integrating > MathML. But I hope only for the backend side? >> Additionally, input methods simplify using characters like ??, >> ???, or ???. > > "Everyone" says to just use a Unicode editor. Long-term, I think > that's what's going to happen -- you're starting your project too > late for this to make much sense. Well, your newsreader failed to specify UTF-8, and my newsreader failed to do a proper auto-detect. So, Unicode has not arrived yet. ;-) Seriously: Most people can't enter those characters. In LaTeX, you can use many Unicode characters directy for years, however, only few documents make use of this. To most people, it's probably simpler to write \alpha than to find and use the Unicode-insertion tool of their editor. > [...] > > Then you're really caught between a rock and a hard place. LaTeX > is extremely well-entrenched; But only in a small group (compared to Word for example). The main motivation of our group was to see that many people stay away from LaTeX because it is too complicated. The basic assertion of our project is that this complexity is not necessary while still maintaining important features of LaTeX (plain text file format, semantic markup). It is a tradeoff, though: You give up a lot of flexibility. However, I think that this particular type of flexibility (namely, local layout tweaking) is of minor importance. Probably one important thing that didn't get through yet is that we try to get people to semantic markup who don't come from engineering or science. These are heavily under-represented in the LaTeX community. "Gummi" (or however we'll call it) is not supposed to be another Geek language. On the contrary, our goal is that even a typical linguistics student loves to write their seminar paper with "Gummi". Reading only forums and newsgroups, one may think that this is impossible but in real life, I've seen more people using LaTeX exactly once and never again than people who keep using it. If I look at typical modern LaTeX preambles, I know what went wrong, so I see a lot of potential. However, then a very defensively constructed syntax is crucial, and everything must just work -- without having to use a tool chain or declaring things before you can use them. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From countblabula at yahoo.com Mon Aug 6 13:51:20 2007 From: countblabula at yahoo.com (Lee Fleming) Date: Mon, 06 Aug 2007 10:51:20 -0700 Subject: Something in the function tutorial confused me. In-Reply-To: <mailman.1683.1186421435.22759.python-list@python.org> References: <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <mailman.1683.1186421435.22759.python-list@python.org> Message-ID: <1186422680.103021.105230@l70g2000hse.googlegroups.com> On Aug 6, 12:30 pm, "Hamilton, William " <wham... at entergy.com> wrote: > When you call f(23), the variable y within it gets created and points at > None. When f(23) exits, the y that it created gets destroyed. (Well, > goes out of scope, but even if it's not garbage collected it won't ever > come back into scope.) When you then call f(24), a new y is created > that also points to None, and disappears forever when f(24) exits. > > The values in a def statement are created when the def is executed, but > the variables are only created when the function is actually called, and > new ones are created every time the function is called. > > -- > -Bill Hamilton- Hide quoted text - > > - Show quoted text - why isn't the y in def f (x, y = []): something garbage-collected? From wolf_tracks at invalid.com Thu Aug 23 00:32:20 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 23 Aug 2007 04:32:20 GMT Subject: Baby Steps, optionDB In-Reply-To: <1187843018.391276.303410@z24g2000prh.googlegroups.com> References: <Uk7zi.1531$vU4.979@nlpi068.nbdc.sbc.com> <1187843018.391276.303410@z24g2000prh.googlegroups.com> Message-ID: <o58zi.29778$RX.9996@newssvr11.news.prodigy.net> Don't even know what the file is. I figured the book would have included it in the example. I see no mention of it in the index. Does it go by another name? BartlebyScrivener wrote: > On Aug 22, 10:41 pm, "W. Watson" <wolf_tra... at invalid.com> wrote: > >> clError: couldn't open "optionDB": no such file or directory > > Because the file doesn't exist? > > Did you make an optionDB file? > > http://tinyurl.com/283o98 > > -- Wayne Watson (Nevada City, CA) Web Page: <speckledwithStars.net> From aboudouvas at panafonet.gr Mon Aug 13 09:20:51 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Mon, 13 Aug 2007 06:20:51 -0700 Subject: Eclipse/PyDev question In-Reply-To: <1187006912.494455.86830@w3g2000hsg.googlegroups.com> References: <1186998539.030727.279330@g4g2000hsf.googlegroups.com> <1187005485.137101.43130@l70g2000hse.googlegroups.com> <1187006912.494455.86830@w3g2000hsg.googlegroups.com> Message-ID: <1187011251.632213.249450@g4g2000hsf.googlegroups.com> Ah, i forgot another one: as any project evolves, you need to organize it in directories. So, i have a project named "Dev" and Eclipse has provided me (in Navigator) with "Dev" and "Src". Inside Src i put my .py files. Let's say that i want to create a directory there (will i make it in "Src" or in "Dev") to put other .py files. I tried adding a "Folder", i also tried to add a "Pydev Source Folder", either way i cannot refer to these files from a .py located in Src directory with the usual "from folderA import"...It does not understand the folder structure and i am pretty sure i am missing something obvious here... From steve at holdenweb.com Fri Aug 10 06:57:20 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 10 Aug 2007 06:57:20 -0400 Subject: The Future of Python Threading In-Reply-To: <1186740111.918048.77920@d30g2000prg.googlegroups.com> References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> Message-ID: <f9hgaf$oon$1@sea.gmane.org> Justin T. wrote: > Hello, > > While I don't pretend to be an authority on the subject, a few days of > research has lead me to believe that a discussion needs to be started > (or continued) on the state and direction of multi-threading python. [...] > What these seemingly unrelated thoughts come down to is a perfect > opportunity to become THE next generation language. It is already far > more advanced than almost every other language out there. By > integrating stackless into an architecture where tasklets can be > divided over several parallelizable threads, it will be able to > capitalize on performance gains that will have people using python > just for its performance, rather than that being the excuse not to use > it. > Aah, the path to world domination. You know you don't *have* to use Python for *everything*. > The nice thing is that this requires a fairly doable amount of work. > First, stackless should be integrated into the core. Then there should > be an effort to remove the reliance on the GIL for python threading. > After that, advanced features like moving tasklets amongst threads > should be explored. I can imagine a world where a single python web > application is able to redistribute its millions of requests amongst > thousands of threads without the developer ever being aware that the > application would eventually scale. An efficient and natively multi- > threaded implementation of python will be invaluable as cores continue > to multiply like rabbits. > Be my guest, if it's so simple. > There has been much discussion on this in the past [2]. Those > discussions, I feel, were premature. Now that stackless is mature (and > continuation free!), Py3k is in full swing, and parallel programming > has been fully realized as THE next big problem for computer science, > the time is ripe for discussing how we will approach multi-threading > in the future. > I doubt that a thread on c.l.py is going to change much. It's the python-dev and py3k lists where you'll need to take up the cudgels, because I can almost guarantee nobody is going to take the GIL out of 2.6 or 2.7. > > [1] I haven't actually looked at the GIL code. It's possible that it > creates a bunch of wait queues for each nice level that a python > thread is running at and just wakes up the higher priority threads > first, thus maintaining the nice values determined by the scheduler, > or something. I highly doubt it. I bet every python thread gets an > equal chance of getting that lock despite whatever patterns the > scheduler may have noticed. > It's possible that a little imp tosses a coin and decides which thread gets to run next. The point of open source is that it's easy to dispel ignorance and make your own changes if you are competent to do so. Talk is cheap, code is costly. Your bet is worth nothing. Is it even possible to run threads of the same process at different priority levels on all platforms? > [2] > http://groups.google.com/group/comp.lang.python/browse_thread/thread/7d16083cf34a706f/858e64a2a6a5d976?q=stackless%2C+thread+paradigm&lnk=ol& > http://www.stackless.com/pipermail/stackless/2003-June/000742.html > ... More that I lost, just search this group. > Anyone who's been around Python for a while is familiar with the issues. Have you actually asked Chris Tismer whether he's happy to see Stackless go into the core? He was far from certain that would be a good idea at PyCon earlier this year. He probably has his reasons ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From sturlamolden at yahoo.no Sun Aug 19 09:29:22 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 19 Aug 2007 06:29:22 -0700 Subject: best GUI library for vector drawing program In-Reply-To: <1187357244.883516.79840@j4g2000prf.googlegroups.com> References: <1187357244.883516.79840@j4g2000prf.googlegroups.com> Message-ID: <1187530162.698816.280140@50g2000hsm.googlegroups.com> On Aug 17, 3:27 pm, chewie54 <dfabrizi... at gmail.com> wrote: > What would be the best cross-platform GUI library to use for a vector > based CAD program I suggest you use different toolkits for windowing (GUI widgets) and drawing the vector graphics. It does not really matter which toolkit you use for windowing. wxPython looks good on many platforms and are free. So it PyGTK. For vector graphics part I suggest PyCairo, AggDraw or OpenGL, depending on your need. PIL and NumPy are also essential if you will be working with images From pavlovevidence at gmail.com Wed Aug 29 19:26:05 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 29 Aug 2007 19:26:05 -0400 Subject: Haskell like (c:cs) syntax References: <fb25uh$gl9$1@online.de> <4866bea60708281512q31635803x1b025274c94caf7e@mail.gmail.com> <mailman.86.1188340264.28954.python-list@python.org> Message-ID: <46d60c96$0$16452$4c368faf@roadrunner.com> On Tue, 28 Aug 2007 17:30:47 -0500, Erik Jones wrote: > On Aug 28, 2007, at 5:12 PM, Chris Mellon wrote: >> When working with lists, Python has a slice syntax (which is rather >> more powerful than Haskells limited head->tail linked list syntax) that >> you can use to chop a sequence up into various parts. > > That is extremely arguable (in fact, Haskell's list semantics are > extremely powerful as they are not limited to just head/tail). Apples and oranges, really. Pattern matching can do an awful lot of cool things, but arbitrary slicing isn't one of the more pleasant ones. (At least not without a good set of slice-matching patterns handy, which I don't know if Haskell has.) Carl Banks From jzgoda at o2.usun.pl Fri Aug 24 16:37:22 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 24 Aug 2007 22:37:22 +0200 Subject: GUI and distrubution In-Reply-To: <fanec2$nr$1@daisy.noc.ucla.edu> References: <1187974418.175783.50860@i38g2000prf.googlegroups.com> <92ab7$46cf1f51$4275d90a$11544@FUSE.NET> <fanec2$nr$1@daisy.noc.ucla.edu> Message-ID: <fanfrn$lb3$1@nemesis.news.tpi.pl> James Stroud napisa?(a): >> These are two of the most-often-asked questions on this list (along >> with "What's the best Python IDE?"). Search the list archives via >> Google, or do a general Google search. Some helpful terms to get you >> started include pyinstaller, py2exe, py2app, Tkinter, wxPython, PyQt, >> and pyGTK. > > One of these days, someone needs to write a tutorial on distributing for > the Big 3 (Linux, OSX, and Amiga--or was that last one supposed to be > M$?). That would make 12 howto's (4 GUI platforms x 3 operating systems). Tedious. -- Jarek Zgoda http://jpa.berlios.de/ From ptmcg at austin.rr.com Thu Aug 16 22:25:03 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 16 Aug 2007 19:25:03 -0700 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: <1187311999.880853.135780@j4g2000prf.googlegroups.com> References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> <fa2m4s$k1g$1@daisy.noc.ucla.edu> <1187311999.880853.135780@j4g2000prf.googlegroups.com> Message-ID: <1187317503.988255.194840@57g2000hsv.googlegroups.com> On Aug 16, 7:53 pm, beginner <zyzhu2... at gmail.com> wrote: > On Aug 16, 6:21 pm, James Stroud <jstr... at mbi.ucla.edu> wrote: > > > > > > > beginner wrote: > > > Hi All. > > > > I'd like to do the following in more succint code: > > > > if k in b: > > > a=b[k] > > > else: > > > a={} > > > b[k]=a > > > > a['A']=1 > > > > In perl it is just one line: $a=$b->{"A"} ||={}. > > > I'm afraid you've asked a non sequiter: > > > euler 40% cat test.pl > > > $a=$b->{"A"} ||={} ; > > print "$a\n" ; > > > $b->{"B"} = 0 ; > > $a=$b->{"B"} ||={} ; > > print "$a\n" ; > > > $b->{"X"} = 15 ; > > $a=$b->{"X"} ||={} ; > > print "$a\n" ; > > > euler 41% perl test.pl > > HASH(0x92662a0) > > HASH(0x926609c) > > 15 > > > James > > > -- > > James Stroud > > UCLA-DOE Institute for Genomics and Proteomics > > Box 951570 > > Los Angeles, CA 90095 > > >http://www.jamesstroud.com/ > > It is not supposed to be used this way. > $b is supposed to be a hash-table of hash-table. If a key exists in > $b, it points to another hash table. The $a=$b->{"A"} ||={} pattern is > useful when you want to add records to the double hash table. > > For example, if you have a series of records in the format of (K1, K2, > V), and you want to add them to the double hash-table, you can do > $a=$b->{K1} || ={} > $a->{K2}=V- Hide quoted text - > > - Show quoted text - I think this demonstrates the Python version of what you describe. -- Paul from collections import defaultdict data = [ ('A','B',1), ('A','C',2), ('A','D',3), ('B','A',4), ('B','B',5), ('B','C',6), ('B','D',7), ] def defaultdictFactory(): return defaultdict(dict) table = defaultdict(defaultdictFactory) for k1,k2,v in data: table[k1][k2] = v for kk in sorted(table.keys()): print "-",kk for jj in sorted(table[kk].keys()): print " -",jj,table[kk][jj] prints: - A - B 1 - C 2 - D 3 - B - A 4 - B 5 - C 6 - D 7 From byte8bits at gmail.com Tue Aug 14 14:57:32 2007 From: byte8bits at gmail.com (brad) Date: Tue, 14 Aug 2007 14:57:32 -0400 Subject: post xml payload with urllib Message-ID: <f9su1q$4e6$1@solaris.cc.vt.edu> Has anyone sent an xml payload via post using urllib? I'd like to do something like this: logon_request = """<LoginRequest> <password>"the_password"</password> <user>"the_user"</user> </LoginRequest>""" logon = urllib.urlopen("https://127.0.0.1/api/version/xml", logon_request) print logon.read() logon.close() 127.0.0.1 expects xml via a https connection post. From aahz at pythoncraft.com Sat Aug 4 10:07:09 2007 From: aahz at pythoncraft.com (Aahz) Date: 4 Aug 2007 07:07:09 -0700 Subject: the one python book References: <mailman.1611.1186233912.22759.python-list@python.org> Message-ID: <f9216d$ffu$1@panix3.panix.com> In article <mailman.1611.1186233912.22759.python-list at python.org>, dhr <dima.hristov at gmail.com> wrote: > >newbie question: > >Is there a 'K&R" type of Python book? The book that you'd better have on >your shelf if you are going into Python? There really aren't any, assuming you're comfortable reading web-based material. If it's important to you to have a reference book, probably _Python in a Nutshell_ would be best. If you're looking for a tutorial, I'll plug my own _Python for Dummies_. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. From irmen.NOSPAM at xs4all.nl Sun Aug 12 12:00:26 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 12 Aug 2007 18:00:26 +0200 Subject: ANN: Compyler 0.1 In-Reply-To: <mailman.1859.1186862018.22759.python-list@python.org> References: <mailman.1859.1186862018.22759.python-list@python.org> Message-ID: <46bf2ea3$0$240$e4fe514c@news.xs4all.nl> Grant Olson wrote: > Compyler is a pre-alpha x86 native code compiler. In what ways is this similar or different to Shed Skin? http://mark.dufour.googlepages.com/ --Irmen From victor.lebrun at gmail.com Thu Aug 2 16:53:34 2007 From: victor.lebrun at gmail.com (vml) Date: Thu, 02 Aug 2007 20:53:34 -0000 Subject: python 3.0, pywin32 and scipy In-Reply-To: <1186086609.231563.224090@x35g2000prf.googlegroups.com> References: <1186070475.659511.24130@q3g2000prf.googlegroups.com> <1186086609.231563.224090@x35g2000prf.googlegroups.com> Message-ID: <1186088014.008755.318660@e9g2000prf.googlegroups.com> On 2 ao?t, 22:30, sturlamolden <sturlamol... at yahoo.no> wrote: > On Aug 2, 6:01 pm, vml <victor.leb... at gmail.com> wrote: > > > - my script using pywin32 for the COM layer and scipy for the maths > > won't work under 3.0 > > Why not? > > > - will we have the equivalent of pywin32 and scipy in python ? > > Say what? I've always thought pywin32 and scipy were Python packages. The problem is quite complex in my case. My company has a some softwares to do some test measurement which can be automated with vb 6 via OLE automation. One could use matlab and vb 6 or vb.net or even C# but I succeed to show the advantages of python due to its simplicity and its efficiency but I am a newbee and not a computer scientist at all. Now they want to use Python as the swissknife of the engineer. So it is going from vb 6 to Python which is not really straight forward ... If we want to do simple things like matlab script it is possible in python, but it is also possible to do some OO programming and even more. So with python I need absolutly a COM level and also scipy and matplotlib, I am confident that both will be ported to python 3.x. I try still to convince people to switch for, vb 6 to python by writting a python module which will handle the come layer of our software. I thank you very much for your answers. I hope it will be possible to switch easily to python 3. But I need to produce something as cheap as possible and I have no means ... And I try to argue to give up vb 6 and use python. C# is for our developpers the best solution to do this except the mathematic stuff... python is so easy to use and easy to read I believe it can be our best solution ... Any ideas to convience people (except my scripts ;) )? From davbrow at gmail.com Fri Aug 24 01:41:08 2007 From: davbrow at gmail.com (Davo) Date: Thu, 23 Aug 2007 22:41:08 -0700 Subject: List Comprehension Question: One to Many Mapping? In-Reply-To: <1187929443.636690.287450@i13g2000prf.googlegroups.com> References: <1187929443.636690.287450@i13g2000prf.googlegroups.com> Message-ID: <1187934068.998593.201240@x40g2000prg.googlegroups.com> On Aug 23, 9:24 pm, beginner <zyzhu2... at gmail.com> wrote: > Hi All, > > How do I map a list to two lists with list comprehension? > > For example, if I have x=[ [1,2], [3,4] ] > > What I want is a new list of list that has four sub-lists: > > [[1,2], [f(1), f(2)], [3,4], [f(3), f(4)]] > > [1,2] is mapped to [1,2] and [f(1), f(2)] and [3,4] is mapped to > [3,4], [f(3), f(4)]. > > I just can't find any way to do that with list comprension. I ended up > using a loop (untested code based on real code): > > l=[] > for y in x: > l.append(y) > l.append([f(z) for z in y]) > > Thanks, > Geoffrey This may be what you want: l = [[y, [f(z) for z in y]] for y in x] But It's a bit dense. How about: l=[] for y in x: Fy = [f(z) for z in y] l.extend([y, Fy]) -- David From kyosohma at gmail.com Mon Aug 6 15:15:34 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 06 Aug 2007 19:15:34 -0000 Subject: Any Good Book To Start ? In-Reply-To: <1186426924.388898.224310@l70g2000hse.googlegroups.com> References: <1186426924.388898.224310@l70g2000hse.googlegroups.com> Message-ID: <1186427734.352753.183520@z24g2000prh.googlegroups.com> On Aug 6, 2:02 pm, Katie Tam <katie... at gmail.com> wrote: > Please let me know any good book to start ? Thank You > > Katie Tam > CCNP, CCDP > LinkWaves Corporation > **Leading Provider of Cisco Equipment**http://www.linkwaves.com To start learning Python or what? "Python Programming 3rd Ed." by Lutz is good for learning deeper concepts in Python, but is probably better suited for experienced programmers. I still recommend it though, as it has lots of case studies and cool examples. "Python for Dummies" gives a good overview of Python for a complete n00b. There are many other beginner Python books, most of which are pretty nice, but not equal in quality. Mike From chernevik at gmail.com Sat Aug 4 18:03:32 2007 From: chernevik at gmail.com (chernevik at gmail.com) Date: Sat, 04 Aug 2007 22:03:32 -0000 Subject: Question -- Running Programming Python Examples In-Reply-To: <mailman.1627.1186264086.22759.python-list@python.org> References: <1186263007.587499.305340@57g2000hsv.googlegroups.com> <mailman.1627.1186264086.22759.python-list@python.org> Message-ID: <1186265012.342976.139150@q75g2000hsh.googlegroups.com> That fixed it, and Gary's item on pointing my browser to the proper port answered the next question percolating in my mind. It now runs as advertised. Thanks to you both! From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Aug 8 08:02:56 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 08 Aug 2007 14:02:56 +0200 Subject: Seek the one billionth line in a file containing 3 billion lines. In-Reply-To: <1186571432.901348.138990@g4g2000hsf.googlegroups.com> References: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> <7xzm12o7o7.fsf@ruckus.brouhaha.com> <mailman.1729.1186557385.22759.python-list@python.org> <46b996b1$0$12384$426a74cc@news.free.fr> <1186571432.901348.138990@g4g2000hsf.googlegroups.com> Message-ID: <46b9b0f0$0$15951$426a74cc@news.free.fr> Ant a ?crit : > On Aug 8, 11:10 am, Bruno Desthuilliers <bruno. > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> Jay Loden a ?crit : >> (snip) >> >>> If we just want to iterate through the file one line at a time, why not just: >>> count = 0 >>> handle = open('hugelogfile.txt') >>> for line in handle.xreadlines(): >>> count = count + 1 >>> if count == '1000000000': >>> #do something >> for count, line in enumerate(handle): >> if count == '1000000000': >> #do something > > You'd get better results if the test were: > > if count == 1000000000: > > Or probably even: > > if count == 999999999: > > Since the 1 billionth line will have index 999999999. > Doh :( Thanks for the correction. From aleax at mac.com Wed Aug 29 10:44:57 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 29 Aug 2007 07:44:57 -0700 Subject: What's the difference ? References: <1188394767.333396.129020@r29g2000hsg.googlegroups.com> <1188396199.136398.321900@r34g2000hsd.googlegroups.com> Message-ID: <1i3ljx0.et1tyg1lxph4nN%aleax@mac.com> <kyosohma at gmail.com> wrote: ... > Weird. Hetland's book, "Beginning Python" states that it's a matter of > taste. If your taste is for more verbose AND slower notation without any compensating advantage, sure. > Martelli's "Python Cookbook 2nd Ed." says to use the get() > method instead as you never know if a key is in the dict. However, I > can't seem to find any reference to has_key in his book. .get is not a direct alternative to ``in'' (it's an alternative to an idiom where you key into the dict if the key is present and otherwise supply a default value, and it's MUCH better in that case). has_key is probably not even mentioned in the Cookbook (2nd edition) since there is never a good need for it in the Python versions it covers (2.2 and up), but you can probably find traces in the 1st edition (which also covered Python back to 1.5.2, where has_key *was* needed); the Nutshell (2nd ed) mentions it briefly in a table on p. 60. > According to Chun in "Core Python Programming", has_key will be > obsoleted in future versions of Python, so he recommends using "in" or > "not in". Yes, we're removing has_key in Python 3.0 (whose first alpha will be out reasonably soon, but is not going to be ready for production use for quite a bit longer), among other redundant things that exist in 2.* only for legacy and backwards compatibility reasons. This makes 3.0 simpler (a little closer to the "only one obvious way" ideal). But you should use ``in'' and ``not in'' anyway, even if you don't care about 3.* at all, because they only have advantages wrt has_key, without any compensating disadvantage. Alex From rdm at rcblue.com Wed Aug 22 03:15:26 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 22 Aug 2007 00:15:26 -0700 Subject: 'REPL' style IDE In-Reply-To: <1187632249.748945.158910@i13g2000prf.googlegroups.com> References: <1187632249.748945.158910@i13g2000prf.googlegroups.com> Message-ID: <20070822071536.8D8ED1E4014@bag.python.org> At 10:50 AM 8/20/2007, beginner wrote: >Hi Everyone, > >I am using the Wing IDE. It works great when developing applications, >but the workflow is like Visual Studio -- after you execute it or >debug it, the python script ends. > >What I want is an interactive interpreting environment. I want the IDE >to execute a boot script to initialize my environment and create some >basic data objects. And then I want to be able to type in command on >the command line using these objects. The IDLE that comes with Python >does this, but compared with Wing, it does not have a lot of the >convenient features. > >I am wondering if there is anything more powerful than IDLE that can >do this. Are you sure you can't do this with Wing? Have you asked support, <support at wingware.com>? Dick Moores ====================================== Bagdad Weather <http://weather.yahoo.com/forecast/IZXX0008_f.html> From joel.granados at gmail.com Tue Aug 21 16:33:07 2007 From: joel.granados at gmail.com (Joel Granados) Date: Tue, 21 Aug 2007 15:33:07 -0500 Subject: IDE for Python In-Reply-To: <1187709711.175483.86780@x35g2000prf.googlegroups.com> References: <mailman.55.1187690455.32294.python-list@python.org> <1187709711.175483.86780@x35g2000prf.googlegroups.com> Message-ID: <7ad76b520708211333h3247eba6m9166cf2566801281@mail.gmail.com> Thanks to all for the valuable suggestions. On 8/21/07, Benjamin <musiccomposition at gmail.com> wrote: > > On Aug 21, 5:00 am, Joel Andres Granados <joel.grana... at gmail.com> > wrote: > > Hello list: > > > > I have tried various times to use an IDE for python put have always been > > disapointed. > > I haven't revisited the idea in about a year and was wondering what the > > python people > > use. > > I have also foundhttp://pida.co.uk/mainas a possible solution. Anyone > > tried it yet? > > > > suggestions. > I like PyDev + Eclipse mostly because I develop Java, PHP, and C/C++, > so I like having a consistent interface between the languages. > Besides, the Eclipse updater makes updating and installing new > features really easy. > > Regards > > Joel Andres Granados > > > > joel.granados.vcf > > 1KDownload > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Joel Andr?s Granados Medell?n Colombia -- jgranad1 at eafit.edu.co joel.granados at ieee.org -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070821/9a7c85a7/attachment.html> From steve at holdenweb.com Sat Aug 11 10:04:04 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 11 Aug 2007 10:04:04 -0400 Subject: Finding gurus (was Re: Something in the function tutorial confused me.) In-Reply-To: <f9kd93$lg8$1@panix3.panix.com> References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <mailman.1737.1186577596.22759.python-list@python.org> <5hv705F3mk67nU1@mid.individual.net> <1i2nhnv.2y00l5173lfbbN%aleax@mac.com> <f9kd93$lg8$1@panix3.panix.com> Message-ID: <f9kfkk$scq$1@sea.gmane.org> Aahz wrote: > In article <1i2nhnv.2y00l5173lfbbN%aleax at mac.com>, > Alex Martelli <aleax at mac.com> wrote: >> Because of this, a Google search for >> >> "<name> <surname>" python >> >> may sometimes help; when you get 116,000 hits, as for "Steve Holden" >> python, that may be a reasonable indication that the poster is one of >> the world's Python Gurus (in fact, the winner of the 2007 Frank WIllison >> Award -- congratulations, Steve!!!). > > Sometimes that precise search pattern isn't appropriate, of course. ;-) Of course, Alex didn't mention that there are actually 117,000 hits, and the last thousand have nothing to do with programming ;-) Alex, thanks for your congratulations, as no public announcement has yet been made (apart from at OSCON) I haven't mentioned the Frank Willison Award until now. The certificate arrived this week, and I am humbled by the honor. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From jeremy+complangpython at jeremysanders.net Fri Aug 24 12:01:00 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Fri, 24 Aug 2007 17:01:00 +0100 Subject: Co-developers wanted: document markup language References: <87odgyyx9u.fsf@wilson.homeunix.com> Message-ID: <famvbs$2fm$1@gemini.csx.cam.ac.uk> Torsten Bronger wrote: > Some LaTeX users in Aachen thought about a general-use markup > language this spring. I wrote some code and a rough project > description, however, we could need some help. > > If you are interested, visit the provisional project page at > http://latex-bronger.sourceforge.net/gummi/ Sounds a good idea - LaTeX has so many historical hangovers. How many people on earth can actually write a LaTeX style file? I'm not sure about writing LaTeX output, however, due to the crude nasty ways it handles fonts and so on. How are you going to get enough controls for users over what they always complain about: fonts, page breaking, and positioning of figures? Maybe it's an okay first step however. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From Dominic at PLEASEASK.co.uk Thu Aug 9 04:22:04 2007 From: Dominic at PLEASEASK.co.uk (special_dragonfly) Date: Thu, 9 Aug 2007 09:22:04 +0100 Subject: Help with Dictionaries and Classes requested please. Message-ID: <46bacae3$0$89254$7b0f0fd3@mistral.news.newnet.co.uk> Hello, I'm new to this group, I've read through the subject of a lot of the group but can't find anything relevant. Perhaps my question is too basic but I'm still stuck. Classes and Dictionaries. If I have a dictionary, how do I instantiate many instances of a class per dictionary key? Either at run-time or dynamically. Can anyone help me please? Thank you Dominic From danb_83 at yahoo.com Sat Aug 25 09:48:33 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Sat, 25 Aug 2007 06:48:33 -0700 Subject: Does shuffle() produce uniform result ? In-Reply-To: <tooru_honda-1F800B.15385124082007@wvnews01.netvigator.com> References: <tooru_honda-1F800B.15385124082007@wvnews01.netvigator.com> Message-ID: <1188049713.024407.265900@e9g2000prf.googlegroups.com> On Aug 24, 2:38 am, tooru honda <tooru_ho... at fast-mail.org> wrote: > Hi, > > I have read the source code of the built-in random module, random.py. > After also reading Wiki article on Knuth Shuffle algorithm, I wonder if > the shuffle method implemented in random.py produces results with modulo > bias. > > The reasoning is as follows: Because the method random() only produces > finitely many possible results, we get modulo bias when the number of > possible results is not divisible by the size of the shuffled list. > > 1. Does shuffle() produce uniform result ? Experimental evidence with a 5-card decks and 1,200,000 simulation gives me [9782, 9784, 9784, 9786, 9817, 9822, 9825, 9841, 9859, 9864, 9866, 9872, 9886, 9888, 9893, 9893, 9893, 9893, 9896, 9896, 9901, 9905, 9909, 9909, 9912, 9917, 9919, 9920, 9920, 9925, 9932, 9933, 9934, 9938, 9938, 9943, 9944, 9946, 9947, 9951, 9952, 9955, 9956, 9959, 9960, 9961, 9962, 9963, 9964, 9966, 9968, 9968, 9968, 9969, 9969, 9975, 9977, 9978, 9978, 9979, 9985, 9987, 9990, 9996, 9998, 9998, 10002, 10009, 10012, 10015, 10017, 10018, 10020, 10026, 10027, 10028, 10032, 10035, 10042, 10047, 10048, 10049, 10049, 10055, 10056, 10060, 10062, 10064, 10066, 10069, 10070, 10076, 10087, 10089, 10092, 10095, 10097, 10098, 10100, 10101, 10116, 10117, 10128, 10129, 10131, 10137, 10138, 10140, 10146, 10155, 10158, 10162, 10162, 10163, 10177, 10190, 10190, 10232, 10260, 10292] frequencies of each of the 120 possible orderings. The chi-squared test statistic (for H0: all 120 orderings are equally likely) is 132.9472 with 119 degrees of freedom. The p-value is 0.1804, which is greater than typically-used significance levels, so there is insufficient evidence to reject H0. From zzbbaadd at aol.com Fri Aug 31 00:33:43 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Thu, 30 Aug 2007 21:33:43 -0700 Subject: list index() In-Reply-To: <mailman.183.1188533232.28954.python-list@python.org> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <mailman.135.1188474634.28954.python-list@python.org> <1188495863.242815.236900@o80g2000hse.googlegroups.com> <87bqcod2gq.fsf@benfinney.id.au> <1188517370.998114.119940@q4g2000prc.googlegroups.com> <mailman.179.1188521931.28954.python-list@python.org> <1188530220.815429.281380@i38g2000prf.googlegroups.com> <mailman.183.1188533232.28954.python-list@python.org> Message-ID: <1188534823.558722.212480@l22g2000prc.googlegroups.com> On Aug 30, 9:06 pm, "Carsten Haese" <cars... at uniqsys.com> wrote: > On Thu, 30 Aug 2007 20:17:00 -0700, zzbbaadd wrote > > > Well IN was what I was looking for and would have saved this thread. > > However I don't believe IN showed up on the doc web page that has > > list methods, where I found index(). > > They're not on the exact same page, but index() is in section 3.6.4 of the > library reference (http://docs.python.org/lib/typesseq-mutable.html), whereas > "in" is in section 3.6 of the library reference > (http://docs.python.org/lib/typesseq.html). I'm wondering how you managed to > find subsection 3.6.4 without finding section 3.6. www.google.com search "python list methods" first search find: 5. Data Structures The list methods make it very easy to use a list as a stack, where the last element added .... Another useful data type built into Python is the dictionary. ... http://docs.python.org/tut/node7.html "The list data type has some more methods. Here are all of the methods of list objects:" From seb.buchoux at gmail.com Sun Aug 19 05:47:03 2007 From: seb.buchoux at gmail.com (=?ISO-8859-1?Q?S=E9bastien?=) Date: Sun, 19 Aug 2007 11:47:03 +0200 Subject: Hot subject: a good python editor and/or IDE? Message-ID: <46C81197.6030700@gmail.com> Hi folks, I am currently using Eclipse+PyDev when developping Python projects but I lack a fast, simple editor for tiny bit of scripts. So here is my question: what is, for you, the current best ( but still kind of light! ) Python editor/IDE ? A tiny precision, I am on Ubuntu so I am looking for a linux compatible editor. Cheers, S?bastien From junkeun.park at gmail.com Mon Aug 27 17:43:00 2007 From: junkeun.park at gmail.com (Jun-geun Park) Date: Mon, 27 Aug 2007 17:43:00 -0400 Subject: Biased random? In-Reply-To: <favd0c$fcu$1@ss408.t-com.hr> References: <favd0c$fcu$1@ss408.t-com.hr> Message-ID: <favgh4$1gm3$1@grapevine.csail.mit.edu> Ivan Voras wrote: > Hi, > > I have a list of items, and need to choose several elements from it, > "almost random". The catch is that the elements from the beginning > should have more chance of being selected than those at the end (how > much more? I don't care how the "envelope" of probability looks like at > this point - can be linear). I see that there are several functions in > Python standard libraries for various distribution, but is there an easy > pythonic way to make them do what I need? > > That's weird. random.randint(a,b) will be enough for most cases. Test your system to see the distribution is uniform with something like: ---- import random dist = {} for z in xrange(100000): u = random.randint(1,10) try: dist[u] = dist[u] + 1 except KeyError: dist[u] = 1 print dist ---- From lew at lewscanon.com Mon Aug 20 08:05:36 2007 From: lew at lewscanon.com (Lew) Date: Mon, 20 Aug 2007 08:05:36 -0400 Subject: Latest models of Gibson guitars In-Reply-To: <1187579396.285862.186860@e9g2000prf.googlegroups.com> References: <1187544898.289948.322160@22g2000hsm.googlegroups.com> <1187548916.909340.37420@k79g2000hse.googlegroups.com> <1187579396.285862.186860@e9g2000prf.googlegroups.com> Message-ID: <9K6dnY8HnIUNHlTbnZ2dnUVZ_gGdnZ2d@comcast.com> Twisted wrote: > On Aug 19, 2:41 pm, vedrandeko... at v-programs.com wrote: >> This is a newsgroup of programming language Python, stop with this! > > Python?! Python is as off-topic here as guitars, unlike, say, Java... When referring to "this" newsgroup or "here", one must remember that this is a cross-posted thread, so those concepts have multiple referents. Take another look at the address field ("Newsgroups:") of the message, then redefine "this newsgroup" accordingly - there are more than one due to the spammish cross-posting of the original message. So let's all stop being so parochial, hmm? -- Lew From bj_666 at gmx.net Thu Aug 30 03:27:12 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Aug 2007 07:27:12 GMT Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <87hcmhebwv.fsf@benfinney.id.au> Message-ID: <5jn9qgFdmbcU3@mid.uni-berlin.de> On Thu, 30 Aug 2007 17:09:36 +1000, Ben Finney wrote: > zzbbaadd at aol.com writes: > >> What's with the index() function of lists throwing an exception on not >> found? > > It's letting you know that the item isn't in the list. There's no > sensible return value from an "index" function in that condition. What about -1? C programmers do this all the time. :-) Ciao, Marc 'BlackJack' Rintsch From simon at brunningonline.net Mon Aug 27 12:34:51 2007 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 27 Aug 2007 17:34:51 +0100 Subject: Image.open( "C:\test.jpg") is this wrong ? In-Reply-To: <CEFAE560FE3E3C458A2335A1AA37A82D06763937@MAIL2W2K3.WarrenNT.SaintFrancis.Loc> References: <CEFAE560FE3E3C458A2335A1AA37A82D06763937@MAIL2W2K3.WarrenNT.SaintFrancis.Loc> Message-ID: <8c7f10c60708270934h69cad046ic7b4ac68119da069@mail.gmail.com> On 8/27/07, Carnell, James E <jecarnell at saintfrancis.com> wrote: > Image.open("C:\test.jpg") Try: Image.open(r"C:\test.jpg") See http://docs.python.org/ref/strings.html -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From steve at holdenweb.com Sun Aug 26 22:16:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 26 Aug 2007 22:16:11 -0400 Subject: make images with python In-Reply-To: <fap87e$ue4$1@lust.ihug.co.nz> References: <1187147338.400947.181010@x40g2000prg.googlegroups.com> <1i2vg8p.1d8t42r1jzvm9iN%raims@dot.com> <mailman.2012.1187186603.22759.python-list@python.org> <fap87e$ue4$1@lust.ihug.co.nz> Message-ID: <fatc5b$5i0$1@sea.gmane.org> Lawrence D'Oliveiro wrote: > In message <mailman.2012.1187186603.22759.python-list at python.org>, Boris > Borcic wrote: > >> Lawrence Oluyede wrote: >> >>> stefano <ssalvatori at gmail.com> wrote: >>>> I need make some images using python but i'm lost :P >>> <http://www.pythonware.com/products/pil/> >>> >> If you want to do antialiased drawings into images, >> you might rather want to look for pil at >> >> http://effbot.org/downloads/ >> >> and grab PIL together with the aggdraw extension >> (while "core" PIL includes some drawing primitives, >> last time I tried they weren't antialiased). > > I see that PIL supports image resizing > <http://www.pythonware.com/library/pil/handbook/image.htm> with filters > that can be used for antialiasing. So just do all your drawing at, say, > 200% scale, then downsample with Image.resize to antialias. That certainly worked very well for rendering text. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From robert.kern at gmail.com Fri Aug 31 14:40:59 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 31 Aug 2007 13:40:59 -0500 Subject: Biased random? In-Reply-To: <fb9bg9$ibi$1@sea.gmane.org> References: <favd0c$fcu$1@ss408.t-com.hr> <mailman.80.1188332647.28954.python-list@python.org> <fb77bq$jtk$1@ss408.t-com.hr> <fb7a3d$phj$1@sea.gmane.org> <fb9bg9$ibi$1@sea.gmane.org> Message-ID: <fb9nc1$s6v$1@sea.gmane.org> Jeffrey Barish wrote: > Robert Kern wrote: > >> Ivan Voras wrote: >>> Jeffrey Barish wrote: >>> >>>> If you take the difference between two uniformly distributed random >>>> variables, the probability density function forms an isosceles triangle >>>> centered at 0. Take the absolute value of that variable and the pdf is >>>> a >>>> straight line with maximum value at 0 tapering to 0 at max. Thus, >>>> >>>> z = abs(randint(0, max) - randint(0, max)) >>>> >>>> ought to do the trick. >>> It's elegant :) >>> >>> I've noticed something interesting in my test: the value 0 appears less >>> often than other values (which behave as they should). >> The distribution of the difference (before the abs()) looks like this >> (max=4): >> >> # >> ### >> ##### >> ####### >> ---0+++ >> 321 123 >> >> Taking the absolute value doubles up the non-zero masses, but there's no >> "negative 0" to add to the 0s stack. >> >> # >> # >> ### >> ### >> #### >> #### >> 0123 >> >> The method does not work because of that. >> > The math says that it works, so we must not be implementing it correctly. "The math" says nothing of the kind about the method that was stated. > I > suspect that our mistake is quantizing the random variable first and then > taking the difference and absolute value. What result do you get when you > quantize once? That is, obtain two random values (floats) with uniform > pdf. Take the difference. Abs. Round to int. This way, everything in the > band from (-0.5, +0.5) goes to 0, and that's the highest part of the > triangle. That's a very different "it". The difference is not just implementation. If you change "round" to "truncate", that method should work, though. -- 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 ptmcg at austin.rr.com Wed Aug 15 22:09:01 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 15 Aug 2007 19:09:01 -0700 Subject: replacement for string.printable In-Reply-To: <mailman.2026.1187204186.22759.python-list@python.org> References: <mailman.2026.1187204186.22759.python-list@python.org> Message-ID: <1187230141.510879.229490@b79g2000hse.googlegroups.com> On Aug 15, 1:56 pm, John K Masters <johnmast... at oxtedonline.net> wrote: > >From what I have read the string module is obsolete and should not be > > used but I am working on a project that parses printable files created > in a DOS program and creates a web page for each file. I am using the > string.printable constant to determine which characters should be kept; > the files contain many print control codes. There seems to be nothing > like this in the string methods. isalnum() seems the nearest but gives > false for '+' '!' etc. > > I realise I could define a global string to cover this but wondered if > there was another, better, way > > Regards, John > -- > War is God's way of teaching Americans geography > Ambrose Bierce (1842 - 1914) Well, I was all set with a cocky answer to the effect of "here's half a dozen different ways to test to see if the ordinal of a character is between 33 and 127 inclusive," assuming that the "printable" in string.printable meant "prints something that is not whitespace." Well, I'm glad I checked - string.printable includes a number of whitespace characters, including those with ASCII codes 32 (space), 9 (tab), 10 (linefeed), 13 (CR), 11 (FF), and 12 (VT). So you could hard code such a string (you are working with a legacy DOS app after all), or maybe better, make it a set of chars, since it seems that you are doing massive numbers of membership tests using "if c in string:" - create the set once, and then use "if c in setMadeFromString:". -- Paul From steve at holdenweb.com Thu Aug 9 12:24:09 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 09 Aug 2007 12:24:09 -0400 Subject: Stackless Integration In-Reply-To: <f9fd8h$q2t$1@sea.gmane.org> References: <mailman.1786.1186660119.22759.python-list@python.org> <46bb1df0$0$403$426a74cc@news.free.fr> <f9fd8h$q2t$1@sea.gmane.org> Message-ID: <f9ff36$f1$1@sea.gmane.org> Steve Holden wrote: > Bruno Desthuilliers wrote: >> Jean-Paul Calderone a ?crit : >>> On Thu, 09 Aug 2007 09:00:27 -0000, "Justin T." <jmtulloss at gmail.com> >>> wrote: >>>> Hi, >>>> >>>> I've been looking at stackless python a little bit, and it's awesome. >>>> My question is, why hasn't it been integrated into the upstream python >>>> tree? Does it cause problems with the current C-extensions? It seems >>>> like if something is fully compatible and better, then it would be >>>> adopted. However, it hasn't been in what appears to be 7 years of >>>> existence, so I assume there's a reason. >>> It's not Pythonic. >> Hum... Yes ? Really ? Care to argument ? > > Unfortunately such arguments quickly descend to the "yes it is", "no it > isn't" level, as there is no objective measure of Pythonicity. > > Twisted [...] > Oops, did I say Twisted? When I last heard Chris Tismer talking about Stackless someone in the audience asked him about the prospects of incorporating Stackless into the core and he suggested he didn't necessarily think of that as a desirable change. I would like to see it in the core, but integration would not be an easy task, and maintenance might be problematic. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From __peter__ at web.de Fri Aug 17 10:51:48 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 17 Aug 2007 16:51:48 +0200 Subject: how to pass a custom object to re.search? References: <1187359347.755104.118660@r29g2000hsg.googlegroups.com> <1i2zz9z.jb9h6m13ontqgN%raims@dot.com> <1187360512.063710.182450@r29g2000hsg.googlegroups.com> Message-ID: <fa4cm6$uab$00$1@news.t-online.com> brunovianarezende at gmail.com wrote: > I've done that (and added __unicode__ too). I only didn't want to, I > want to do: > > re.search(custom_object) > > so, code that worked before as: > > re.search(parentobj.custom_object) > > don't have to be changed for: > > re.search(str(parentobj.custom_object)) > > and I'm also curious to know if it is possible to do that... :-) Not without monkeypatching the re module: import re _original_compile = re._compile def _wrapped_compile(*key): try: custom_compile = key[0].__compile__ except AttributeError: return _original_compile(*key) else: return custom_compile(*key[1:]) re._compile = _wrapped_compile class Aaa(object): def __compile__(self, *args): return re.compile("[Aa]+") print re.findall(Aaa(), "a yadda so whaaaat") Peter From jmtulloss at gmail.com Thu Aug 9 12:53:39 2007 From: jmtulloss at gmail.com (Justin T.) Date: Thu, 09 Aug 2007 16:53:39 -0000 Subject: Stackless Integration In-Reply-To: <mailman.1786.1186660119.22759.python-list@python.org> References: <1186650027.043779.276520@i38g2000prf.googlegroups.com> <mailman.1786.1186660119.22759.python-list@python.org> Message-ID: <1186678419.594781.149190@g12g2000prg.googlegroups.com> > It's not Pythonic. > > Jean-Paul Ha! I wish there was a way to indicate sarcasm on the net. You almost got people all riled up! From fartknuckle at fartknuckle.com Fri Aug 10 17:01:57 2007 From: fartknuckle at fartknuckle.com (fartknuckle) Date: Fri, 10 Aug 2007 16:01:57 -0500 Subject: Python Dies on "make install" Message-ID: <pan.2007.08.10.21.01.56.706157@fartknuckle.com> When I try to build and install python from source It configures and makes fine but upon 'make install' I always get to this point: Listing /usr/local/lib/python2.5/xml/sax ... Compiling /usr/local/lib/python2.5/xml/sax/__init__.py ... Compiling /usr/local/lib/python2.5/xml/sax/_exceptions.py ... Compiling /usr/local/lib/python2.5/xml/sax/expatreader.py ... Compiling /usr/local/lib/python2.5/xml/sax/handler.py ... Compiling /usr/local/lib/python2.5/xml/sax/saxutils.py ... Compiling /usr/local/lib/python2.5/xml/sax/xmlreader.py ... Compiling /usr/local/lib/python2.5/xmllib.py ... Compiling /usr/local/lib/python2.5/xmlrpclib.py ... Compiling /usr/local/lib/python2.5/zipfile.py ... make: *** [libinstall] Error 1 I am currently trying to install 2.5.1. I get the error no matter what the version is. Does anyone have an idea what may be causing this? I have gone through the config.log and found no errors concerning zipfile.py or zipfile or zip. I am thinking the error is the next command after the zipfile.py installation because I can go into /usr/local/lib/python2.5 and zipfile.py is installed. Any help much appreciated. Thanks -- Take summa dis punk! From joncle at googlemail.com Wed Aug 15 09:46:58 2007 From: joncle at googlemail.com (Jon Clements) Date: Wed, 15 Aug 2007 06:46:58 -0700 Subject: What order does info get returned in by os.listdir() In-Reply-To: <gemini.jmthof006bdd602a4@omba.demon.invalid> References: <gemini.jms7ay00fafcf00k8@jernic.by.invalid> <gemini.jmtc5f0021tj002a4@omba.demon.invalid> <5igd1gF3mc1akU1@mid.uni-berlin.de> <gemini.jmthof006bdd602a4@omba.demon.invalid> Message-ID: <1187185618.672790.305850@w3g2000hsg.googlegroups.com> To emulate the order of XP, you might be able to get away with something like:- sorted( myData, key=lambda L: L.replace('~',chr(0)) ) That just forces all '~'s to be before everything else. hth, Jon. On 15 Aug, 14:33, Jeremy C B Nicoll <jer... at omba.demon.co.uk> wrote: > Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote: > > > > > > > On Wed, 15 Aug 2007 12:34:27 +0100, Jeremy C B Nicoll wrote: > > > > I've some supplementary questions... my original code was looking at > > > each leafname in turn via > > > > for leaf in os.listdir(path): > > > wholefile = os.path.join(path,leaf) > > > if os.path.isfile(wholefile): > > > if leaf.startswith("~"): > > > > etc. But I now realise I might alternatively do something like: > > > > leaflist = os.listdir(path) > > > <then something to sort that list> > > > for leaf in leaflist: > > > But this is doing something different that the above code!? > > I'm not sure if I understand you. I know it's only "equivalent" to the > first line of what's above, ie iterate over a list of names, and obviously > it's got the sorting of that list done, but do you mean there's some other > difference? > > > > How would I sort leaflist in a way that mimics the sort order that XP > > > shows me things under? > > > This depends on what XP is. Which program? Which locale? How does the > > locale influence that programs sorting? > > Well... XP is Windows XP (Pro as I think I said earlier), and I'm in the UK. > I explained earlier how XP shows me stuff in order when I tell it to sort by > name. > > > > > > > > > > Secondly, my code is wasting time looking at subdirectories/files which > > > I already know I'm not interested in. Is there a way to restrict > > > listdir to, say, only return info about subdirectories, or only about > > > dirs/files whose names match a pattern? > > > `os.listdir()` always returns all names. You can or have to filter the > > result if you are only interested in some of the names. Simple pattern > > matching on names can be done with `glob.glob()`. > > > > Thirdly, once I've go a list of leafnames, somehow, is there a way to > > > ask Python if a specific leaf-value is in that list, without explicitly > > > looping through the items in the list? > > > With the ``in`` operator you have an implicit loop over the list. > > > if 'readme.txt' in leafnames: > > print 'Hurray!' > > OK, that looks useful. Thanks. > > -- > Jeremy C B Nicoll - my opinions are my own.- Hide quoted text - > > - Show quoted text -- Hide quoted text - > > - Show quoted text - From alisonken1 at gmail.com Thu Aug 16 12:45:57 2007 From: alisonken1 at gmail.com (alisonken1) Date: Thu, 16 Aug 2007 16:45:57 -0000 Subject: Layer 2 socket connection In-Reply-To: <1187265821.989249.276090@r34g2000hsd.googlegroups.com> References: <1187202110.958564.206770@l22g2000prc.googlegroups.com> <1187265821.989249.276090@r34g2000hsd.googlegroups.com> Message-ID: <1187282757.460386.143180@l22g2000prc.googlegroups.com> On Aug 16, 5:03 am, "richmoor... at gmail.com" <richmoor... at gmail.com> wrote: <snip> > I use impacket for stuff like that, seehttp://oss.coresecurity.com/projects/impacket.html > > Cheers > > Rich. Thanks, Rich - I'll have a look From kbk at shore.net Fri Aug 10 22:08:34 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 10 Aug 2007 22:08:34 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200708110208.l7B28YEW028649@hampton.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 404 open ( +0) / 3855 closed ( +8) / 4259 total ( +8) Bugs : 1065 open ( +6) / 6790 closed ( +6) / 7855 total (+12) RFE : 263 open ( +0) / 295 closed ( +0) / 558 total ( +0) New / Reopened Patches ______________________ MSVC++8 x86 tkinter build patch for trunk (2007-08-05) http://python.org/sf/1767787 opened by brotchie test_asyncore fix (2007-08-05) CLOSED http://python.org/sf/1767834 opened by Hasan Diwan Fix for failing test_scriptpackages in py3k-struni (2007-08-07) CLOSED http://python.org/sf/1768976 opened by Antti Rasinen Fix for failing test_plistlib in py3k-struni (2007-08-07) CLOSED http://python.org/sf/1769016 opened by brotchie struni: test_xml_etree_c (2007-08-08) CLOSED http://python.org/sf/1769767 opened by Joe Gregorio Remove cStringIO usage (2007-08-08) CLOSED http://python.org/sf/1770008 reopened by tiran Remove cStringIO usage (2007-08-08) CLOSED http://python.org/sf/1770008 opened by Christian Heimes ctypes: c_char now uses bytes and not str (unicode) (2007-08-08) CLOSED http://python.org/sf/1770355 opened by STINNER Victor Misc improvements for the io module (2007-08-10) http://python.org/sf/1771364 opened by Christian Heimes Patches Closed ______________ test_asyncore fix (2007-08-05) http://python.org/sf/1767834 closed by gvanrossum test_csv struni fixes + unicode support in _csv (2007-08-03) http://python.org/sf/1767398 closed by gvanrossum urllib2-howto - correction (2007-08-02) http://python.org/sf/1765839 closed by gbrandl Fix for failing test_scriptpackages in py3k-struni (2007-08-06) http://python.org/sf/1768976 closed by nnorwitz Fix for failing test_plistlib in py3k-struni (2007-08-07) http://python.org/sf/1769016 closed by gvanrossum struni: test_xml_etree_c (2007-08-07) http://python.org/sf/1769767 closed by nnorwitz Remove cStringIO usage (2007-08-08) http://python.org/sf/1770008 closed by gvanrossum Remove cStringIO usage (2007-08-08) http://python.org/sf/1770008 closed by gvanrossum ctypes: c_char now uses bytes and not str (unicode) (2007-08-08) http://python.org/sf/1770355 closed by haypo New / Reopened Bugs ___________________ SocketServer.DatagramRequestHandler (2007-08-04) http://python.org/sf/1767511 opened by Alzheimer Badly formed XML using etree and utf-16 (2007-08-05) http://python.org/sf/1767933 opened by BugoK Byte code WITH_CLEANUP missing, MAKE_CLOSURE wrong (2007-08-05) http://python.org/sf/1768121 opened by L. Peter Deutsch tutorial (2007-08-06) CLOSED http://python.org/sf/1768767 opened by Michael R Bax Python - Operation time out problem (2007-08-06) http://python.org/sf/1768858 opened by MASK A paragraph about packages should be updated. (2007-08-07) CLOSED http://python.org/sf/1769002 opened by Noam Raphael decimal.Decimal("trash") produces informationless exception (2007-08-08) http://python.org/sf/1770009 opened by John Machin platform.mac_ver() returning incorrect patch version (2007-08-08) http://python.org/sf/1770190 opened by Gus Tabares Decimal.__int__ overflows for large values (2007-08-08) http://python.org/sf/1770416 opened by Jason G words able to decode but unable to encode in GB18030 (2007-08-09) http://python.org/sf/1770551 opened by Z-flagship Errors in site.py not reported properly (2007-08-09) http://python.org/sf/1771260 opened by Adam Olsen bsddb can't use unicode keys (2007-08-10) http://python.org/sf/1771381 opened by Erol Aktay another 'nothing to repeat' (2007-08-10) CLOSED http://python.org/sf/1771483 opened by viciousdog minor bug in turtle (2007-08-10) CLOSED http://python.org/sf/1771558 opened by Jeremy Sanders Bugs Closed ___________ String.capwords() does not capitalize first word (2007-08-03) http://python.org/sf/1767363 closed by gbrandl subprocess.Popen.wait fails sporadically with threads (2007-07-16) http://python.org/sf/1754642 closed by gbrandl subprocess raising "No Child Process" OSError (2007-07-14) http://python.org/sf/1753891 closed by gbrandl tutorial (2007-08-06) http://python.org/sf/1768767 deleted by mrbax A paragraph about packages should be updated. (2007-08-07) http://python.org/sf/1769002 closed by gbrandl cStringIO no longer accepts array.array objects (2007-06-03) http://python.org/sf/1730114 closed by gbrandl another 'nothing to repeat' (2007-08-10) http://python.org/sf/1771483 deleted by viciousdog minor bug in turtle (2007-08-10) http://python.org/sf/1771558 closed by gbrandl From Brian.McCann at viziant.net Mon Aug 20 14:52:16 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Mon, 20 Aug 2007 14:52:16 -0400 Subject: reading a line in file References: <93066C069973ED448DC2BCEA9C44A7383BE2B2@efmailx> <2dc0c81b0708201029k5909d919vcf0deebae74a79c7@mail.gmail.com> Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE2B4@efmailx> Hi, I can read in the whole file build.number which has the following lines how do I just capture the value of build.number and assign it to a variable Thanks, Brian contents of file build.number: #Build Number for ANT. Do not edit! #Mon Aug 20 04:04:51 EDT 2007 build.number=1 buildinfo.py ################################## #!/usr/bin/python import string import os import sys import time import errno import shutil buildinfo = "build.number" input = open(buildinfo, 'r') for line in input: print line ######################################### command line when script is run $ buildinfo.py #Build Number for ANT. Do not edit! #Mon Aug 20 04:04:51 EDT 2007 build.number=1 ________________________________ From: python-list-bounces+brian.mccann=viziant.net at python.org on behalf of Shawn Milochik Sent: Mon 8/20/2007 1:29 PM To: python-list at python.org Subject: Re: reading a line in file Write some code, even if it doesn't quite work, and post it. We'll help you fix it. You can open a file with: input = open("file.txt", "r") You can read a line with: someText = input.readline() You can loop through an open file like this: for line in input: #do something with line That should get you started. -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070820/2d76dc81/attachment.html> From bdesth.quelquechose at free.quelquepart.fr Wed Aug 29 09:34:05 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 29 Aug 2007 15:34:05 +0200 Subject: Creating a multi-tier client/server application In-Reply-To: <1188408670.480447.42470@k79g2000hse.googlegroups.com> References: <1188360460.838635.186930@w3g2000hsg.googlegroups.com> <7xbqcqhqbw.fsf@ruckus.brouhaha.com> <46d54ed8$0$429$426a34cc@news.free.fr> <1188393925.007952.313110@r29g2000hsg.googlegroups.com> <46d57888$0$295$426a74cc@news.free.fr> <1188398008.538820.21960@d55g2000hsg.googlegroups.com> <46d59fa8$0$278$426a74cc@news.free.fr> <1188408670.480447.42470@k79g2000hse.googlegroups.com> Message-ID: <46d5bee0$0$291$426a74cc@news.free.fr> Jeff a ?crit : > Goldfish--thanks, I'll check it out. > > >>>That, or something similar, may be what I do. It would mean, however, >>>developing my own method for transferring objects across the network, >> >>Why transfering "objects" ? You only need to transfer data. > > I suppose I don't need to transfer objects, it just seems like it > would make it far easier (certainly less repetition of code) Why so ??? > to > program the client-side app. From kyosohma at gmail.com Wed Aug 15 11:32:30 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 15 Aug 2007 08:32:30 -0700 Subject: Opinions about this new Python book? In-Reply-To: <1187117012.088495.247890@q4g2000prc.googlegroups.com> References: <mailman.1957.1187093157.22759.python-list@python.org> <1187096231.194685.86030@m37g2000prh.googlegroups.com> <20070814154913.D8C3C1E400A@bag.python.org> <8a6b8e350708141020q495b22der4c362ee3df618d82@mail.gmail.com> <mailman.1979.1187113641.22759.python-list@python.org> <1187117012.088495.247890@q4g2000prc.googlegroups.com> Message-ID: <1187191950.037749.8050@z24g2000prh.googlegroups.com> On Aug 14, 1:43 pm, kyoso... at gmail.com wrote: > On Aug 14, 12:46 pm, "Shawn Milochik" <Sh... at Milochik.com> wrote: > > > > > Yes, please post back to the list. I saw this book on Amazon, but > > there's no table of contents listed, nor is there one on the > > publisher's site. > > > Thanks, > > Shawn > > > On 8/14/07, James Matthews <nytrok... at gmail.com> wrote: > > > > i got to say that the best python book i bought was Core Python Programming > > > (2nd) by Wesly Chun! Aside for all the spelling mistakes and syntax errors > > > that there are i feel that the book really explained the language well for > > > someone coming from another programming language! > > > > On 8/14/07, Dick Moores <r... at rcblue.com> wrote: > > > > At 05:57 AM 8/14/2007, kyoso... at gmail.com wrote: > > > > >On Aug 14, 7:05 am, Dick Moores <r... at rcblue.com> wrote: > > > > > > I'd appreciate opinions about this new Python book. > > > > > > > Title: Python Power!: The Comprehensive Guide > > > > > > Author: Matt Telles > > > > > > Publisher: Course Technology > > > > > > Pub. Date: Jul 27, 2007 > > > > > > Edition: 1st edition > > > > > > Binding: Paperback > > > > > > Pages: 508 > > > > > > ISBN: 1598631586 > > > > > > List Price: 34.99 USD > > > > > > > The book on the publisher's website: <http://tinyurl.com/2dkhzg> > > > > > > > And at BestBookDeal.com: > > > > > > <http://www.bestbookdeal.com/book/compare/1598631586> > > > > > > > Thanks, > > > > > > > Dick Moores > > > > > >I just got this book over the weekend. I'll start reading/skimming > > > > >through it this week and hopefully remember to get back to you. > > > > > Thanks! > > > > > > By the > > > > >way, why do you want to know? > > > > > If the experts like it, I'll buy it. > > > > > Dick > > > > > -- > > > >http://mail.python.org/mailman/listinfo/python-list > > > > -- > > >http://www.goldwatches.com/ > > >http://www.jewelerslounge.com > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > -- > > Please read:http://milocast.com/2007/07/31/this-i-believe/ > > Here's an abbreviated Table of Contents...just chapter titles. The > book's table of contents also lists section headers. > > Chapter 1: About Python > Chapter 2: Python Language Overview > Chapter 3: Tools > Chapter 4: Data Types > Chapter 5: Control Flow > Chapter 6: Input & Output > Chapter 7: Functions & Modules > Chapter 8: Exception Handling > Chapter 9: Object-Oriented Programming > Chapter 10: Classes and Objects in Python > Chapter 11: The Python Library > Chapter 12: The GUI - Tkinter > Chapter 13: The Web Server - Apache > Chapter 14: Working with Databases > Chapter 15: Putting It All Together > Chapter 16: Python and Graphics > > Mike More on the subject...the writer is very conversational in tone and it makes for a light read in the first 1 1/2 chapters that I've completed. I've noticed a couple of sentence errors, but nothing in the code. He disses lambdas, which I haven't used for anything either. But I have seen good uses for them (particularly in Tkinter callbacks), although they don't seem to be as readable or usable as the rest of Python. For some reason, the author makes the claim that the term "Predicate" is "bandied about quite a bit in the literature" of Python. I have 17 or so Python books and I don't think I've ever seen this used in conjunction with Python...or in any of the docs I've skimmed. What the!? I'll keep you'all posted. Mike From deets at nospam.web.de Fri Aug 24 10:09:33 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 24 Aug 2007 16:09:33 +0200 Subject: Unequal Length Maze In-Reply-To: <1187963693.724859.116810@m37g2000prh.googlegroups.com> References: <1187941996.333191.323540@z24g2000prh.googlegroups.com> <5j85h5F3t20idU1@mid.uni-berlin.de> <1187963693.724859.116810@m37g2000prh.googlegroups.com> Message-ID: <5j874vF3rvp2nU1@mid.uni-berlin.de> tomtim20 at gmail.com schrieb: > On Aug 24, 4:41 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote: >> tomti... at gmail.com schrieb: >> >>> Hi All, >>> what's the best algorithm to solve such problem ? >>> http://www.stetson.edu/~efriedma/unequal/ >>> I will really appreciate some pieces of code (python). >> If you pay me 100$ (really a bargain), you get a solution in python. >> >> Diez > > What about Barack Obama Autographed Photo ? I'm living in germany, couldn't care less about USA presedential candidates. If you want others to make your homework, you gotta pay. Diez From kw at codebykevin.com Wed Aug 8 11:17:15 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 08 Aug 2007 11:17:15 -0400 Subject: Tkinter or wxpython? In-Reply-To: <hgamo4-p2m.ln1@lairds.us> References: <op.tv98rva4wepdt4@ericb.pragmadev> <mailman.1677.1186412323.22759.python-list@python.org> <7xlkcopu4r.fsf@ruckus.brouhaha.com> <7x7io8r6na.fsf@ruckus.brouhaha.com> <hgamo4-p2m.ln1@lairds.us> Message-ID: <46B9DE7B.3050909@codebykevin.com> Cameron Laird wrote: > > While those with an artistic eye > assure me the simplest Tkinter programs look worse > that corresponding ones built with any other toolkit, > they behave the most coherently in regards to resizing > and so on. > "Look worse" can be addressed through extensive means: through theming (via Tile, which can now be easily used in Tkinter; see http://tkinter.unpy.net/wiki/TileWrapper); and through other aspects of UI design, such as color, fonts, and even use of icons. A pyGtk or wxPython application that uses old-school Gnome icons, for instance, will look ugly. It's quite possible to make an attractive Tkinter application using modern, stylish icons that even blends in reasonably well on a specific platform (I've done it). -- Kevin Walzer Code by Kevin http://www.codebykevin.com From dennis.benzinger at gmx.net Wed Aug 8 07:25:33 2007 From: dennis.benzinger at gmx.net (Dennis.Benzinger@gmx.net) Date: Wed, 08 Aug 2007 04:25:33 -0700 Subject: RTF 2 Tiff In-Reply-To: <1186495747.958628.198070@g12g2000prg.googlegroups.com> References: <1186427712.284976.207560@d30g2000prg.googlegroups.com> <tLOdnWiKvpsq4yrbnZ2dnUVZ_qOknZ2d@comcast.com> <1186495747.958628.198070@g12g2000prg.googlegroups.com> Message-ID: <1186572333.184049.42540@19g2000hsx.googlegroups.com> On Aug 7, 4:09 pm, cjankow... at hbr-inc.com wrote: > [...] > We are running Windows Operating Systems. I was not able to find > anything that actually would convert the images via command line or > interface. > [...] You could instruct OpenOffice to export the RTF files as PDF files by using the Python-UNO bridge and then convert the PDF files to TIFF. Google finds a lot of PDF to TIFF converters. Dennis Benzinger From wolf_tracks at invalid.com Thu Aug 23 07:33:14 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 23 Aug 2007 04:33:14 -0700 Subject: Baby Steps, optionDB In-Reply-To: <13cq7bjl2l03366@corp.supernews.com> References: <Uk7zi.1531$vU4.979@nlpi068.nbdc.sbc.com> <13cq7bjl2l03366@corp.supernews.com> Message-ID: <rfezi.6451$924.3721@newssvr23.news.prodigy.net> Thanks. I think I agree about the book comment. I used to dabble with Tcl/Tk many years ago. About a year ago, I sold my only book on it. I thought I'd never need it again! I wonder if Grayson's (e-book on his site) has improved. After spending about 90 minutes with IDLE, I'm not real impressed. Is there something better? Dennis Lee Bieber wrote: > On Wed, 22 Aug 2007 20:41:11 -0700, "W. Watson" > <wolf_tracks at invalid.com> declaimed the following in comp.lang.python: > >> I'm just playing with Python. It's my first outing. The program is below. I >> thought I'd fuss with numbers, and then get bold and try some Tkinter stuff. >> I copied the root stuff from a book (Grayson), and get stopped at the >> optionDB statement. What's wrong? I get >> clError: couldn't open "optionDB": no such file or directory >> from Idle. Does the Tk code need to be up higher? The book is dated 2000, so >> maybe that item no longer exists. >> > More likely, you need to create a file with standard Tk > configuration options in the directory you are running from... > > A google search on "tk optiondb" brings up a page full of RUBY > stuff... > > > {That wasn't the easiest book to understand either... It seems to have > been written on the basis that one already knew tcl/tk, and how it > linked together} -- Wayne Watson (Nevada City, CA) Web Page: <speckledwithStars.net> From bronger at physik.rwth-aachen.de Mon Aug 27 05:36:14 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 27 Aug 2007 11:36:14 +0200 Subject: my parser.py isn't imported References: <874pimqpei.fsf@wilson.homeunix.com> <1188166462.066732.123620@i13g2000prf.googlegroups.com> Message-ID: <87ir715ng1.fsf@wilson.homeunix.com> Hall?chen! John Machin writes: > Torsten Bronger wrote: > >> I have a module parser.py in the same directory as the main >> module. In the main module, I import "parser". On Linux, this >> works as expected, however on Windows, it imports the stdlib >> parser module. sys.path[0] points to the directory of my >> parser.py in both cases. What went wrong here? > > [...] > > 2. Failure to RTFabulousM: > """ > Details of the module searching and loading process are implementation > and platform specific. It generally involves searching for a ``built- > in'' module with the given name and then searching a list of locations > given as sys.path. > """ Okay, I did the following to avoid this: import sys, os.path modulepath = os.path.abspath(os.path.dirname(sys.argv[0])) def import_local_module(name): """Load a module from the local modules directory. Loading e.g. a local "parser" module is difficult because on Windows, the stdlib parser module is a built-in and thus loaded with higher priority. With http://www.python.org/dev/peps/pep-0328/ it may become simpler. :Parameters: - `name`: name of the module, as it would be given to ``import``. :Return: the module object or ``None`` if none was found :rtype: module """ import imp try: return sys.modules[name] except KeyError: pass fp, pathname, description = imp.find_module(name, [modulepath]) try: return imp.load_module(name, fp, pathname, description) finally: # Since we may exit via an exception, close fp explicitly. if fp: fp.close() Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From drewlist at gmail.com Fri Aug 3 23:38:40 2007 From: drewlist at gmail.com (drewlist at gmail.com) Date: Fri, 03 Aug 2007 20:38:40 -0700 Subject: bias in random.normalvariate?? Message-ID: <1186198720.800007.38800@k79g2000hse.googlegroups.com> I'm a Python newbie and certainly no expert on statistics, but my wife was taking a statistics course this summer and to illustrate that sampling random numbers from a distribution and taking an average of the samples gives you a random number as the result (bigger sample -> smaller variance in the calculated random number, converging in on the mean of the original distribution), I threw together this program: #! /usr/bin/python import random; i=1 samplen=100 mean=130 lo=mean hi=mean sd=10 sum=0 while(i<=samplen): x=random.normalvariate(mean,sd) #print x if x<lo: lo=x if x>hi: high=x sum+=x i+=1 print 'sample mean=', sum/samplen, '\n' print 'low value =', lo print 'high value=', high --------------------------------------------------------- But the more I run the darn thing, the stranger the results look to me. random.normalvariate is defined on page 89 of http://www-acc.kek.jp/WWW-ACC-exp/KEKB/Control/Python%20Documents/lib.pdf as generating points from a normal distribution with mean and standard deviation given by the arguments. But my test program consistently comes up with sample means that are less than the mean of the distribution. The lo value is consistently much lower relative to the mean than the high value is higher than the mean. That is, it looks to me like the normalvariate function is biased. Part of my being a Python newbie is I'm not really sure where to go to discuss this problem. If this group isn't the right place, do feel free to point me to where I ought to go. I'm running Ubuntu Dapper and "python -V" says I've got Python 2.4.3. I tried looking in random.py down under /usr/lib but find no clues there as to the version of the random module on my machine. Am I missing something? /usr/lib/python2.4$ ls -l random.py -rw-r--r-- 1 root root 30508 2006-10-06 04:34 random.py I added the lo and high stuff to my test program out of fear that I was running into something funky in adding up 100 floating point numbers. That would be more of a worry if the sample size was much bigger, but lo and high showed apparent bias quite aside from the calculation of the mean. Am I committing some other obvious statistical or Python blunder? e.g. Am I mis-understanding what random.normalvariate is supposed to do? From carsten at uniqsys.com Fri Aug 17 20:42:53 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 17 Aug 2007 20:42:53 -0400 Subject: Question about 'for' loop In-Reply-To: <496954360708171545m6a0eff61la5fe270145246eab@mail.gmail.com> References: <496954360708171545m6a0eff61la5fe270145246eab@mail.gmail.com> Message-ID: <1187397773.3327.12.camel@localhost.localdomain> On Fri, 2007-08-17 at 17:45 -0500, Robert Dailey wrote: > [...] > Secondly, I'm wondering how I can use this method of a for loop to > append strings to strings in a list. For example: > > mylist = [ > "Hello ", > "Hello again " > ] > > I should be able to do this: > > print [ i + "World" for i in mylist ] > > Which should yield the output: > > ["Hello World", "Hello again world"] > > However, instead I get an error message saying "TypeError: cannot > concatenate 'str' and 'list' objects" > > How can I achieve the above? Thanks for reading. You must have done something different than what you're describing above to get that error message. The code you posted works as expected: >>> mylist = [ ... "Hello ", ... "Hello again " ... ] >>> print [ i + "World" for i in mylist ] ['Hello World', 'Hello again World'] -- Carsten Haese http://informixdb.sourceforge.net From steve at holdenweb.com Wed Aug 1 08:30:15 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 01 Aug 2007 08:30:15 -0400 Subject: access the name of my method inside it In-Reply-To: <5hb80tF3inuf2U7@mid.uni-berlin.de> References: <1185959202.302467.276080@x35g2000prf.googlegroups.com> <5hb1ebF3inuf2U6@mid.uni-berlin.de> <mailman.1427.1185966164.22759.python-list@python.org> <5hb80tF3inuf2U7@mid.uni-berlin.de> Message-ID: <f8pucp$ubd$1@sea.gmane.org> Marc 'BlackJack' Rintsch wrote: > On Wed, 01 Aug 2007 07:01:42 -0400, Steve Holden wrote: > >> Marc 'BlackJack' Rintsch wrote: >>> On Wed, 01 Aug 2007 09:06:42 +0000, james_027 wrote: >>> >>>> for example I have this method >>>> >>>> def my_method(): >>>> # do something >>>> >>>> # how do I get the name of this method which is my_method here? >>> Why do you need this? There are ways but those are not really good for >>> production code. >>> >> Maybe he wants to write a recursive method? >> >> Once way is to call self.__calss__.mymethod(self). Ugly, isn't it? > > Ugly yes, unnecessary convoluted yes, solution no. You typed `my_method` > in the source. The OP wants to know how to avoid that. > >> >>> class p: >> ... def mymethod(self, n): >> ... if n <= 1: >> ... return 1 >> ... else: >> ... return n * self.__class__.mymethod(self, n-1) > > Why not simply ``self.mymethod(n - 1)`` instead!? > Well, absolutely no reason if you want to go making things simple ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From tjreedy at udel.edu Sat Aug 25 14:17:42 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 25 Aug 2007 14:17:42 -0400 Subject: How to find parent function/class of generators? References: <b410cefd0708250119p7b4080e0v186967c0ef60f720@mail.gmail.com> Message-ID: <fapro5$706$1@sea.gmane.org> "J. A. Aczel" <seventhhs at gmail.com> wrote in message news:b410cefd0708250119p7b4080e0v186967c0ef60f720 at mail.gmail.com... | Hello all. I think I should explain my problem in detail, so everyone | understands what I'm trying to do and why. There may be a better | approach to the whole problem then I am using. | | I am working on a game, with most of my AI code & such divided up into | generator functions (really coroutines that don't take any input) | stored in a dictionary called Director.tasks, and handled by a simple | cooperative multitasking engine. The dictionary key is the generator | object to be advanced, and the value is the frame number at which it | should next be executed. The generator objects yield the delay before | their next execution. | | def realtick(self): | Director.frame += 1 | for task in Director.tasks.items(): | if task[1] <= Director.frame: | try: | result = task[0].next() | if result == -1: | Director.tasks.pop(task[0]) | else: | Director.tasks[task[0]] = Director.frame + result | except: | Director.tasks.pop(task[0]) | | Why did I use a dictionary? Originally I had a list of lists, but I | thought converting it to a dictionary would make removing tasks from | the queue easier, the main difficulty I'm having. But it didn't, | because I can't identify the The standard way of storing multiple tasks for future execution at a varietyu of times is a priority queue. Python's heap class (module) is one way to implement such. | Due to the framework I'm using, I think (or possibly just the Python | language?) in-game objects aren't actually destroyed when they're | removed from the game world. Thus, when an enemy or something with | associated tasks 'dies', the tasks merrily continue executing... and | the game will have a bunch of enemies who no longer have sprites, | movement abilities or collision checks, but otherwise are none the | worse for wear for having been destroyed. It's a big mess. So I need a | way to remove all tasks associated with a game object from the queue, | upon the object's 'destruction'. I suspect you need to keep a list of tasks associated with a creature with each creature. When creature dies, remove them from the queue or keep a set of dead tasks that tasks removed from the queue are checked against before being executed. Good luck. tjr From mbeachy at gmail.com Fri Aug 17 10:12:01 2007 From: mbeachy at gmail.com (mbeachy at gmail.com) Date: Fri, 17 Aug 2007 14:12:01 -0000 Subject: unexpected optparse set_default/set_defaults behavior Message-ID: <1187359921.637383.268380@22g2000hsm.googlegroups.com> Some rather unexpected behavior in the set_default/set_defaults methods for OptionParser that I noticed recently: >>> import optparse >>> parser = optparse.OptionParser() >>> parser.add_option("-r", "--restart", dest="restart", action="store_true") <Option at 0x-483b3414: -r/--restart> >>> parser.defaults {'restart': None} >>> parser.set_default("retart", False) >>> parser.defaults {'retart': False, 'restart': None} Why does set_default not raise an exception when passed a key that it doesn't recognize? Bad typysts bewaer. The only reason I can think not to raise an exception is so that defaults can be defined before the options are added. Is there some use case that I'm not thinking of here? I realize that changing this could break some existing scripts, but I'm still tempted to file this as a bug. Mike From carsten at uniqsys.com Fri Aug 31 00:10:17 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 31 Aug 2007 00:10:17 -0400 Subject: list index() In-Reply-To: <1188529598.134837.157530@x35g2000prf.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <mailman.135.1188474634.28954.python-list@python.org> <1188495863.242815.236900@o80g2000hse.googlegroups.com> <87bqcod2gq.fsf@benfinney.id.au> <1188517370.998114.119940@q4g2000prc.googlegroups.com> <mailman.174.1188517712.28954.python-list@python.org> <1188529598.134837.157530@x35g2000prf.googlegroups.com> Message-ID: <20070831040746.M7133@uniqsys.com> On Thu, 30 Aug 2007 20:06:38 -0700, zzbbaadd wrote > On Aug 30, 4:48 pm, "Chris Mellon" <arka... at gmail.com> wrote: > > > It suddenly dawned on me that what would be best would be a contains() > > > (or IN syntax for those who can't afford to wait) for lists. > > > > > if mylist.contains("hello): > > > > Genius. Why didn't anyone think of that before? > > With an attitude like that Chris, don't expect to be getting an > invite to beta test my Python 3 fork. Welcome to comp.lang.python, where laziness is punished with brutal sarcasm. -- Carsten Haese http://informixdb.sourceforge.net From steve at holdenweb.com Wed Aug 29 18:20:19 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 29 Aug 2007 18:20:19 -0400 Subject: re compiled object result caching? In-Reply-To: <pan.2007.08.29.21.54.50.317879@datallegro.com> References: <1188417101.936530.182480@50g2000hsm.googlegroups.com> <mailman.122.1188423947.28954.python-list@python.org> <pan.2007.08.29.21.54.50.317879@datallegro.com> Message-ID: <fb4rf4$9m1$1@sea.gmane.org> Dan Stromberg - Datallegro wrote: > On Wed, 29 Aug 2007 17:45:36 -0400, Steve Holden wrote: > >> Dan wrote: >>> foo_re = re.compile(r"foo(bar)") >>> # . . . >>> if foo_re.search(line): >>> foo_re.last_result().group(1) >>> >> If you wanted to implement this I don't really see why a method call is >> necessary. It would surely only need to be a simple attribute? >> >> Of course you then introduce the possibility that someone will reference >> if before using the RE in a search, plus it still requires separate >> storage if you want the ability to use the same RE for two different >> matches and compare the match results. > > I've long felt that publicly accessible attributes probably should be > syntactic sugared to look like accessor methods, a bit like how __add__ > ends up being + - so that if your attribute ever needs to become methods > (say, it started out life as a unidimensional thing, but later needs to > be a flattening of 3 dimensions or something), you won't necessarily need > to change depenent code. > > But are methods a lot more expensive in python than referencing other > kinds of attributes? > Well, given that they are procedure calls, yes. There's also other magic over and above that. The property() function is a way of making what appear to be attribute accesses become method calls. Your intuition is taking you the wrong way: if you need an accessor method then just turn the normal attribute into a property. Given that mechanism, your wish to use accessor methods is definitely anti-pythonic. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From zentraders at gmail.com Fri Aug 10 14:37:06 2007 From: zentraders at gmail.com (Zentrader) Date: Fri, 10 Aug 2007 11:37:06 -0700 Subject: float to string with different precision In-Reply-To: <f9h6kj$sj6$00$1@news.t-online.com> References: <1186731617.128913.279360@m37g2000prh.googlegroups.com> <f9h6kj$sj6$00$1@news.t-online.com> Message-ID: <1186771026.472118.137090@d30g2000prg.googlegroups.com> On Aug 10, 1:12 am, Peter Otten <__pete... at web.de> wrote: > zunbe... at gmail.com wrote: > > I have to print float numbers to a file. Each float should be 5 > > characters in width (4 numbers and the decimal point). > > My problem is that I do not now how to specify float to have different > > numbers of decimals. For example > > > 5.32 -> 5.320 > > 10.356634 -> 10.357 > > 289.234 -> 289.2 > > > In the string formating operations only fixed number of decimal digits > > is allow. > >>> ["%#.4g" % f for f in [5.32, 10.356634, 289.234, 123456789.]] > > ['5.320', '10.36', '289.2', '1.235e+08'] > > Found by playing around with format strings, so no guarantees. > > Peter If the above does not work [/code]test_list = [ 5.32, 10.35634, 289.234 ] for num in test_list : str_num = "%11.5f" % (num) ## expand to at least 5 print str_num, "-->", str_num.strip()[:5][/code] From bbrown at speakeasy.net Fri Aug 31 00:31:21 2007 From: bbrown at speakeasy.net (Robert Brown) Date: Fri, 31 Aug 2007 00:31:21 -0400 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> Message-ID: <m2wsvc1g12.fsf@manolo-blahnik.bibliotech.com> aleax at mac.com (Alex Martelli) writes: > DbC and allegedly rigorous compile-time typechecking (regularly too weak > due to Eiffel's covariant vs countervariant approach, btw...), based on > those empirical results, appear to be way overhyped. My experience with writing Eiffel code was a bit different. Integrating code from multiple sources happened much faster than I expected, and the code ran reliably. There were a couple of instances where previously uncombined code was linked together and worked on the first run. Perhaps more important, however, is that method contracts provide important documentation about how each method is supposed to work -- what it assumes and what must be true when it returns. Using Eiffel changed my coding process. Often I'd write the pre- and postconditions first, then write the method body, just as programmers today often write unit tests first. Thinking carefully about the contracts and writing them down, so they could be verified, makes the code more reliable and maintainable. The contracts are part of the source code, not a fuzzy concept in each programmer's head. The contracts are also useful when discussing the code with domain experts who are not programmers. They can read and understand the "flat short" view of a class, which includes all the method names, method comments, and contracts, but leaves out the method implementations. Here's an example, Eiffel's String class: http://www.nenie.org/eiffel/flatshort/string.html In any case, I'm still not sure whether it would be useful to integrate DbC into Python. A library that implements DbC for Common Lisp has not gotten much traction in that community, which has a similar style of software development. Perhaps it's just too much to ask that programmers write both unit tests and method contracts. bob From 5502109103600001 at t-online.de Sat Aug 25 06:10:29 2007 From: 5502109103600001 at t-online.de (Josef Moellers) Date: Sat, 25 Aug 2007 12:10:29 +0200 Subject: Regular expression use In-Reply-To: <famdl6$p9j$1@gemini.csx.cam.ac.uk> References: <famdl6$p9j$1@gemini.csx.cam.ac.uk> Message-ID: <faov6l$s7k$01$2@news.t-online.com> Nick Maclaren wrote: > For reasons that I won't explain, as they are too complicated > and not terribly relevant, I am interested in discovering what > people actually use regular expressions for. Not the subject > domain, but the construction of the regular expressions. > > I know about computer scientists and parsing, and I know about > the use of relatively simple ones for things like extracting > HTML links from Web pages. But I don't have much feel for the > (probably rare but difficult) uses of more complex ones for > other purposes. I have heard of several such uses, but don't > have an overall idea of what is going on. > > Any pointers appreciated, to more-or-less anything. I just don't get what you're after! Lots of data is available in text form, so sifting though it requires regular expressions. A better question would be: what do you use Perl for, as I'd say most Perl programs utilize REs at some point or the other. But IIRC we've had that thread already. -- Mails please to josef dot moellers and I'm on gmx dot de. From uymqlp502 at sneakemail.com Thu Aug 30 02:08:43 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Wed, 29 Aug 2007 23:08:43 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188441554.884249.50110@22g2000hsm.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <pan.2007.08.29.23.17.34.304019@datallegro.com> <1188441554.884249.50110@22g2000hsm.googlegroups.com> Message-ID: <1188454123.777083.57480@x35g2000prf.googlegroups.com> > I disagree. IMO automatic testing is thousands of times better than > design by contract and Python has already all the support you need > (unittest, doctest, py.test, nose, ...) In theory, anything you can verify with "design by contract" you can also verify with unittest and the rest. However, "design by contract" has a major practical advantage: if you have real (or simulated) inputs available, you don't need to write a test driver or generate test inputs for each class or function. All you need to do is to run your program with the real (or simulated) inputs, all the internal data that gets passed around between classes and functions gets generated as usual, and everything gets tested automatically. In other words, you are spared the potentially considerable effort of generating and storing samples of all the internal data that gets passed around internally. You may want to do unit tests also, of course. Separate unit tests will give you more control and allow you to test individual classes and functions using a wider variety of inputs. But if your design by contract is comprehensive (i.e., passing it guarantees correct functioning of your code), then your unit tests can simply make use of the tests already available in the design by contract. So you've done no extra work in setting up the design by contract anyway. Another significant advantage of "design by contract" is that the tests are all right there in your source code, where they are much less likely to get lost or ignored by subsequent programmers who need to maintain the code. Relying on separate units tests is a bit like relying on extended "comments" or design documents that are separate from the code. Yes, those are certainly useful, but they do not eliminate the need for comments in the code. From michele.simionato at gmail.com Wed Aug 29 01:58:28 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 29 Aug 2007 05:58:28 -0000 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188364909.397692.209170@q4g2000prc.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> Message-ID: <1188367108.393207.241970@g4g2000hsf.googlegroups.com> On Aug 29, 7:21 am, Russ <uymqlp... at sneakemail.com> wrote: > > Thanks for that information. That's too bad, because it seems like a > strong positive capability to add to Python. I wonder why the cold > reception. Were there problems with the idea itself or just the > implementation? Or is it just a low priority? Why do you think that would ad a strong positive capability? To me at least it seems a big fat lot of over-engineering, not needed in 99% of programs. In the remaining 1%, it would still not be needed since Python provides out of the box very powerful metaprogramming capabilities so that you can implement yourself the checks you need, if you really need them. > In any case, I guess it is still perfectly usable even if it isn't > part of the core Python. Has anyone used it? If so, how well did it > work? Thanks. Dunno, I would be curious myself to know if there are users of these frameworks (including AOP frameworks in Python) or if they are just exercises. Michele Simionato From khamenya at gmail.com Thu Aug 30 11:10:19 2007 From: khamenya at gmail.com (Valery) Date: Thu, 30 Aug 2007 15:10:19 -0000 Subject: SOCKS5 + python = pain in you-know-where ? Message-ID: <1188486619.763947.47500@r34g2000hsd.googlegroups.com> Hi all just googled both the web and groups. Who could believe in that: nothing simple, helpful and working concerning SOCKS5 support in python. Anyone got success here? Regards, Valery. From nick at craig-wood.com Tue Aug 28 16:30:06 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 28 Aug 2007 15:30:06 -0500 Subject: tempfile.mkstemp and os.fdopen References: <1188323759.955043.317630@19g2000hsx.googlegroups.com> Message-ID: <slrnfd90i1.rol.nick@irishsea.home.craig-wood.com> billiejoex <gnewsg at gmail.com> wrote: > I'm trying to generate a brand new file with a unique name by using > tempfile.mkstemp(). > > Moreover, I'd like to know if I'm doing fine. Does this approach avoid > race conditions This is a reasonably secure way of doing things. It can't race under unix at least (dunno about windows) unless your dir is on NFS. If you want more security then make sure dir isn't publically writeable. -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From iclark at mail.ewu.edu Thu Aug 9 18:36:09 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Thu, 09 Aug 2007 15:36:09 -0700 Subject: programmatically define a new variable on the fly In-Reply-To: <1186697500.024593.303820@x35g2000prf.googlegroups.com> References: <1186697500.024593.303820@x35g2000prf.googlegroups.com> Message-ID: <f9g4sp$dc2$1@sea.gmane.org> Lee Sander wrote: > Hi, > > I would like to define a new variable which is not predefined by me. > For example, > I want to create an array called "X%s" where "%s" is to be determined > based on the data I am processing. So, for example, if I the file > I'm reading has > g 99 > on the first line, I want to create a new variable called "Xg" whose > length > is 99. > I tried eval("Xg=[0]*99") but that did not work. > > any help would be greatly appreciated > Lee > >>> Xg Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'Xg' is not defined >>> namespace = globals() >>> var_name = 'Xg' >>> var_value = [0] * 9 >>> namespace[var_name] = var_value >>> Xg [0, 0, 0, 0, 0, 0, 0, 0, 0] Ian From http Sat Aug 4 18:05:23 2007 From: http (Paul Rubin) Date: 04 Aug 2007 15:05:23 -0700 Subject: Submit web form only client-side with Python? COM? References: <1186257525.483524.5570@j4g2000prf.googlegroups.com> Message-ID: <7xmyx7ot0c.fsf@ruckus.brouhaha.com> goldtech <goldtech at worldpost.com> writes: > So I can present the user with an HTML form in it - but how can I > write the form data to a local file on my work station? The simplest way is with the cgi and CGIHTTPServer modules. You'd write your form in an html file, with the target set to a Python script that you'd write as a cgi. Then you'd write a trivial CGI HTTP server (look at the example code in the comments) with CGIHTTPServer. The user would point their browser at your server (you could make a desktop shortcut for that), the browser shows the html file, and the submit button sends the form contents to your cgi. This is very basic, old-school web programming, not as flexible or high-performance as using the fancy frameworks, but a lot simpler for limited applications like what you're describing. From yinglcs at gmail.com Sun Aug 26 02:05:11 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: Sun, 26 Aug 2007 06:05:11 -0000 Subject: How can I use python for file processing Message-ID: <1188108311.154118.229610@50g2000hsm.googlegroups.com> Hi, I am trying to use python for file processing. Suppose I have a file like this: I want to build a Hashmap between the line "begin_QOS_statistics" and "end_QOS_statistics" and for each line I want to put the first text as the key of the hash table and the second text as the value. Received RTCP "BYE" on "audio/MPA" subsession (after 89 seconds) Received RTCP "BYE" on "video/MP4V-ES" subsession (after 89 seconds) begin_QOS_statistics server_availability 100 stream_availability 100 subsession video/MP4V-ES num_packets_received 3529 num_packets_lost 0 elapsed_measurement_time 82.302305 kBytes_received_total 3756.422000 measurement_sampling_interval_ms 100 kbits_per_second_min 0.000000 kbits_per_second_ave 365.134075 kbits_per_second_max 2634.760139 packet_loss_percentage_min 0.000000 packet_loss_percentage_ave 0.000000 packet_loss_percentage_max 0.000000 inter_packet_gap_ms_min 2147483.647000 inter_packet_gap_ms_ave 0.000000 inter_packet_gap_ms_max 0.000000 subsession audio/MPA num_packets_received 1414 num_packets_lost 0 elapsed_measurement_time 82.302305 kBytes_received_total 1187.644000 measurement_sampling_interval_ms 100 kbits_per_second_min 0.000000 kbits_per_second_ave 115.442113 kbits_per_second_max 1132.007640 packet_loss_percentage_min 0.000000 packet_loss_percentage_ave 0.000000 packet_loss_percentage_max 0.000000 inter_packet_gap_ms_min 0.022000 inter_packet_gap_ms_ave 52.214517 inter_packet_gap_ms_max 140.955000 end_QOS_statistics From ricaraoz at gmail.com Thu Aug 23 11:05:38 2007 From: ricaraoz at gmail.com (=?UTF-8?B?UmljYXJkbyBBcsOhb3o=?=) Date: Thu, 23 Aug 2007 12:05:38 -0300 Subject: IDE for Python In-Reply-To: <hTPyi.4052$Oo.2475@newssvr17.news.prodigy.net> References: <mailman.55.1187690455.32294.python-list@python.org> <1187698999.545439.322600@k79g2000hse.googlegroups.com> <mailman.91.1187742207.32294.python-list@python.org> <hTPyi.4052$Oo.2475@newssvr17.news.prodigy.net> Message-ID: <46CDA242.3010108@bigfoot.com> I V wrote: > On Tue, 21 Aug 2007 21:23:25 -0300, Ricardo Ar?oz wrote: >> Do you know if for in-house development a GPL license applies? (Qt4 >> and/or Eric4). > > (I'm not sure if I've understood your question right) > > If you distribute an app that _uses_ PyQT, you have to comply with the GPL > (or buy a license from Trolltech), but note that this doesn't really have > anything to do with Eric4. Running Eric4 doesn't require a license (either > the GPL or Trolltech), and code you write using Eric4 doesn't have to be > licensed according to the GPL either. I think they key word would be 'distribute'. I don't plan to distribute the software. It will be used in-house for a commercial company which pays for my time, they'll keep the source code but they won't be distributing or selling it. Am I ok with QT4 ? (this is Windows). TIA From erfc at caballista.org Mon Aug 20 21:19:33 2007 From: erfc at caballista.org (Art Deco) Date: Mon, 20 Aug 2007 19:19:33 -0600 Subject: What does this thread have to do with classical music, References: <7nnh7350b5h25ghocra72b23mmsnnkj8bh@4ax.com> <469445b3$0$4819$8f2e0ebb@news.shared-secrets.com> <4694e124$0$97214$892e7fe2@authen.yellow.readfreenews.net> <46957ef1$0$10227$8f2e0ebb@news.shared-secrets.com> <46963170$0$97261$892e7fe2@authen.yellow.readfreenews.net> <46981df7$0$12095$8f2e0ebb@news.shared-secrets.com> <46990784$0$97223$892e7fe2@authen.yellow.readfreenews.net> <4699297c$0$4706$4c368faf@roadrunner.com> <140720071431044860%erfc@caballista.org> <46a3a1a7$0$15115$8f2e0ebb@news.shared-secrets.com> <220720072148091069%erfc@caballista.org> <46a5385d$0$4832$8f2e0ebb@news.shared-secrets.com> <250720071834457296%erfc@caballista.org> <46aceaa5$0$13281$8f2e0ebb@news.shared-secrets.com> <290720071853200863%erfc@caballista.org> <46b12539$0$4807$8f2e0ebb@news.shared-secrets.com> <010820072033374341%erfc@caballista.org> <46c63474$0$4844$8f2e0ebb@news.shared-secrets.com> <180820070841431634%erfc@caballista.org> <46c90727$0$14433$8f2e0ebb@news.shared-secrets.com> Message-ID: <200820071919337538%erfc@caballista.org> ah <splifingate at gmail.com> wrote: >Art Deco wrote: >> ah <splifingate at gmail.com> wrote: >>>Art Deco wrote: >>>> ah <splifingate at gmail.com> wrote: >>>>>Art Deco wrote: >>>>>> ah <splifingate at gmail.com> wrote: >>>>>>>Art Deco wrote: >>>>>>>> ah <splifingate at gmail.com> wrote: >>>>>>>>>Art Deco wrote: >>>>>>>>>> ah <splifingate at gmail.com> wrote: >>>>>>>>>>>Art Deco wrote: >>>>>>>>>>>> Who wrote? >>>>>>>>>>>> >>>>>>>>>>>> >>>>>>>>>>>>>What does that have to do with classical music, snuhwolf? >>>>>>>>>>>> >>>>>>>>>>>>>What does that have to do with classical music, snuhwolf? >>>>>>>>>>>> >>>>>>>>>>>> How many more times will you be asking the same tired, lame >>>>>>>>>>>> questions, >>>>>>>>>>>> Tholen? >>>>>>>>>>> >>>>>>>>>>>Till 2056? >>>>>>>>>> >>>>>>>>>> At that point, he will have made the Thirty Years Pset War look like >>>>>>>>>> 1967 in the Sinai. >>>>>>>>> >>>>>>>>>It must have been Hell to keep a garden during those times. >>>>>>>>> >>>>>>>>>Did they all eat jerky, or what? >>>>>>>> >>>>>>>> Worse -- worm-laden hardtack. >>>>>>> >>>>>>>Luxury! >>>>>>> >>>>>>>Why, I remember when I was a lad . . . we used to watch the local churls >>>>>>>across the fences eating that well. >>>>>>> >>>>>>>We only had millings (and (occasionally) water) on Tuesdays and Fridays. >>>>>> >>>>>> Grog and hardtack, life is good! >>>>> >>>>>?Viva la basura! >>>> >>>> Vivat les ordures! >>> >>>Vivara los trunctiato! >> >> das Leben ist gut! > >de Handel esta disgustipado! la vita ? buona! -- Official Overseer of Kooks and Saucerheads for alt.astronomy Wee Davie Tholen is a grade-school lamer Trainer and leash holder of: Honest "Clockbrain" John nightbat "fro0tbat" of alt.astronomy Tom "TommY Crackpotter" Potter <http://www.caballista.org/auk/kookle.php?search=deco> "You really are one of the litsiest people I know, Mr. Deco." --Kali, quoted endlessly by David Tholen as evidence of "something" "I am claiming that you believe ah's family name is "ah", Deco, and I substantiated that claim." --David Tholen "Quite a kook-out, Deco. You've been frothing even more ever since I demonstrated how you believe that ah's family name is "ah"." --David Tholen From paddy3118 at googlemail.com Sun Aug 19 11:55:22 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 19 Aug 2007 15:55:22 -0000 Subject: yet another indentation proposal In-Reply-To: <fEZxi.8855$9W6.6492@fe103.usenetserver.com> References: <fEZxi.8855$9W6.6492@fe103.usenetserver.com> Message-ID: <1187538922.849174.94870@19g2000hsx.googlegroups.com> On Aug 18, 7:22 pm, "Aaron" <cajnnjo... at fjireanjtjprodjuctijons.com> wrote: > Hello all. > > I realize that proposals dealing with alternatives to indentation have been > brought up (and shot down) before, but I would like to take another stab at > it, because it is rather important to me. > > I am totally blind, and somewhat new to Python. I put off learning Python > for a long time, simply because of the indentation issue. There is no easy > way for a screenreader user, such as my self, to figure out how much a > particular line of code is indented. A sited person simply looks down the > column to make sure that everything lines up. I, on the other hand, > generally find my self counting a lot of spaces. > > Naturally, there are many other special circumstances in which depending on > whitespace is impractical, but they have already been mentioned in previous > threads on the topic, so I won't bother rehashing them. > > Borrowing from another proposal, I would submit that the opening block and > closing block markers could be _{ and }_ respectively. If it seems that > there is even a modicum of support, I'll write up a more complete proposal. > But in short, an _{ will signify to the interpreter that one level of > indentation is to be added to the current level, that all the statements > that follow (until the closing _}) are to be understood to be at that level, > and that all whitespace at the beginning of lines, or lack there of, is to > be ignored. > > I realize that this would result in some esthetically ugly code, and so > naturally a simple tool to convert this type of block indication back to > "normal indented format" should also be developed. > > Any thoughts or suggestions? > > I sincerely hope that this proposal can be given some serious consideration, > and not simply dismissed as sacrilege. There are many blind programmers, > and I would hate to see them opt to learn other languages simply because of > this one issue. > > Thanks. > > Aaron > > -- > To reply directly, remove j's from email address. Oh wow. it never crossed my mind... Can screen reaaderss be customized? Maybe their is a way to get the screen reader to say indent and dedent at thee appropriate places? Or maybe a filter to put those wordds into the source? - Paddy. From kyosohma at gmail.com Wed Aug 1 09:54:21 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 01 Aug 2007 13:54:21 -0000 Subject: Equivalent to gzinflate() function in PHP. In-Reply-To: <pan.2007.08.01.13.44.47.273887@artcom.pl> References: <pan.2007.08.01.13.44.47.273887@artcom.pl> Message-ID: <1185976461.491418.20230@i38g2000prf.googlegroups.com> On Aug 1, 8:44 am, Adam Kubica <coyot... at artcom.pl> wrote: > Hellou. > > Anybody know about code that work equivalent to gzinflate() > function used in PHP? > > I search via google but I don't found anything sensible :-( I'm not sure what gzinflate does, but it looks like it's some kind of compression/decompression method. Python can do that. Check out the following links: http://www.python.org/doc/lib/module-gzip.html http://www.python.org/doc/lib/module-zlib.html http://python.active-venture.com/lib/module-bz2.html Hopefully this is the type of thing you were looking for. Mike From aine_canby at yahoo.com Tue Aug 21 15:13:38 2007 From: aine_canby at yahoo.com (aine_canby at yahoo.com) Date: Tue, 21 Aug 2007 12:13:38 -0700 Subject: Python Path Dictionary In-Reply-To: <mailman.66.1187710972.32294.python-list@python.org> References: <1187706985.476483.292820@g4g2000hsf.googlegroups.com> <mailman.66.1187710972.32294.python-list@python.org> Message-ID: <1187723618.729114.19020@19g2000hsx.googlegroups.com> On 21 Aug, 17:42, Gary Herron <gher... at islandtraining.com> wrote: > aine_ca... at yahoo.com wrote: > > Hi, > > > Do the Python Paths come in the form of a dictionary where I can > > access a particular path my its key in the registry? > > > For example, in PythonWin Tools>>Edit Python Paths shows the name as > > well of the address of each path > > > Thanks, > > > Aine > > If by "Python Paths" you mean the list of directories searched when > doing an import, then it is a list (not a dictionary and you can access > it as sys.path. > > Here it is on both my Linux and Windows systems: > > >>> import sys > >>> sys.path > > ['', '/usr/lib/portage/pym', '/usr/lib/python25.zip', > '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', > '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', > '/usr/lib/python2.5/site-packages', > '/usr/lib/python2.5/site-packages/Numeric', > '/usr/lib/python2.5/site-packages/PIL', > '/usr/lib/python2.5/site-packages/gtk-2.0'] > > >>> import sys > >>> sys.path > > ['', 'C:\\WINDOWS\\system32\\python24.zip', 'C:\\cygwin\\home\\Gary', > 'c:\\python24\\DLLs', 'c:\\python24\\lib', > 'c:\\python24\\lib\\plat-win', 'c:\\python24\\lib\\lib-tk', > 'c:\\python24', 'c:\\python24\\lib\\site-packages', > 'c:\\python24\\lib\\site-packages\\Numeric', > 'c:\\python24\\lib\\site-packages\\PIL', > 'c:\\python24\\lib\\site-packages\\gtk-2.0', > 'c:\\python24\\lib\\site-packages\\win32', > 'c:\\python24\\lib\\site-packages\\win32\\lib', > 'c:\\python24\\lib\\site-packages\\Pythonwin'] Thanks. Yeah, that's exactly what I'm talking about, but I don't want the list, I want to access a certain path by name. I'm guessing I'm going to have to write a function to do this that reads the value from the registry. From sadfub at gmx.net Tue Aug 21 04:21:47 2007 From: sadfub at gmx.net (sadfub at gmx.net) Date: Tue, 21 Aug 2007 10:21:47 +0200 Subject: setproctitle Message-ID: <46CAA09B.5000208@gmx.net> Hi, is there still no possibility to easly set the process title? I found a third party addon here: http://mail.python.org/pipermail/python-list/2004-August/273115.html. Shouldn't "import posix" do the thing? I am using python 2.5. Since I write a python daemon here, I need to set the correct name, which is needed by the start_daemon tool to write the pid file. From python at jayloden.com Thu Aug 9 12:20:07 2007 From: python at jayloden.com (Jay Loden) Date: Thu, 09 Aug 2007 12:20:07 -0400 Subject: tests In-Reply-To: <f9fdd5$pqv$1@sea.gmane.org> References: <mailman.1792.1186665714.22759.python-list@python.org> <1186666919.456036.120270@d30g2000prg.googlegroups.com> <f9f70t$dpm$1@solaris.cc.vt.edu> <1186670584.148181.180040@r34g2000hsd.googlegroups.com> <46bb2511$0$10103$7b0f0fd3@mistral.news.newnet.co.uk> <1186671660.912133.225810@l70g2000hse.googlegroups.com> <f9fdd5$pqv$1@sea.gmane.org> Message-ID: <46BB3EB7.8030903@jayloden.com> Steve Holden wrote: > This discussion seems to assume that Excel spreadsheets are stored in > some canonical form so that two spreads with the same functionality are > always identical on disk to the last bit. I very much doubt this is true > (consider as an example the file properties that can be set). > > So really you need to define "equality". So far the tests discussed have > concentrated on identifying identical files. > > regards > Steve I was wondering myself if the OP was actually interested in binary identical files, or just duplicated content. If just duplicated content, perhaps this could be used as a starting point: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440661 and the actual data can be compared -Jay From martin at v.loewis.de Thu Aug 16 12:54:50 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 16 Aug 2007 18:54:50 +0200 Subject: threads, mutual exclusion, and lists In-Reply-To: <9e95df10708160945h2bcaf978s50a4b390af7e4f5f@mail.gmail.com> References: <1187206583.255588.57920@e9g2000prf.googlegroups.com> <mailman.2039.1187219345.22759.python-list@python.org> <46C3F78B.9080305@v.loewis.de> <9e95df10708160945h2bcaf978s50a4b390af7e4f5f@mail.gmail.com> Message-ID: <46C4815A.4050403@v.loewis.de> >> Why do you think they are not? > > Because they aren't. You even mentioned that a few operations that > aren't atomic. OTOH, the OP specifically asked for .append() and .pop(), which are atomic. Regards, Martin From evan at yelp.com Wed Aug 8 02:38:28 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 7 Aug 2007 23:38:28 -0700 Subject: Seek the one billionth line in a file containing 3 billion lines. In-Reply-To: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> References: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> Message-ID: <cfb58d850708072338g7d837b0nae71856e156f5a78@mail.gmail.com> On 8/7/07, Sullivan WxPyQtKinter <sullivanz.pku at gmail.com> wrote: > I have a huge log file which contains 3,453,299,000 lines with > different lengths. It is not possible to calculate the absolute > position of the beginning of the one billionth line. Are there > efficient way to seek to the beginning of that line in python? > > This program: > for i in range(1000000000): > f.readline() > is absolutely every slow.... > > Thank you so much for help. There is no fast way to do this, unless the lines are of fixed length (in which case you can use f.seek() to move to the correct spot). The reason is that there is no way to find the position of the billionth line without scanning the whole file. You should split your logs into smaller files in the future. You might be able to do this a very tiny bit faster by using the split utility and have it split the log file into smaller chunks (split can split by line amounts), but since that still has to scan the file it will will be IO bound. -- Evan Klitzke <evan at yelp.com> From jorgen.maillist at gmail.com Wed Aug 15 09:35:17 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Wed, 15 Aug 2007 15:35:17 +0200 Subject: Using python for dynamic behavior from C++ Message-ID: <11e49df10708150635y60ba1f72w573185b9e4bcbac0@mail.gmail.com> Hi all, I am looking into using Python to introduce dynamic behavior in my C++, e.g. something like a simulation where objects can interact with eachother. I know Python can be called from C++, but is it possible to call a binary compiled Python file / array from C++ ? The reason I ask is that if my objects call a script every tick to do something, I would not like to let the python interpreter recompile the same code over and over again. Any pointers to how I can do that? Regards, - Jorgen From google at mrabarnett.plus.com Wed Aug 8 18:44:04 2007 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 08 Aug 2007 15:44:04 -0700 Subject: Destruction of generator objects In-Reply-To: <20070808002852.6228ae91@cube.tz.axivion.com> References: <20070808002852.6228ae91@cube.tz.axivion.com> Message-ID: <1186613044.494852.306970@q75g2000hsh.googlegroups.com> On Aug 7, 11:28 pm, Stefan Bellon <sbel... at sbellon.de> wrote: > Hi all, > > I'm generating a binding from Python to C using SWIG. On the C side I > have iterators over some data structures. On the Python side I > currently use code like the following: > > def get_data(obj): > result = [] > iter = make_iter(obj) > while more(iter): > item = next(iter) > result.append(item) > destroy(iter) > return result > > Now I'd like to transform it to a generator function like the following > in order to make it more memory and time efficient: > > def get_data(obj): > iter = make_iter(obj) > while more(iter): > yield next(iter) > destroy(iter) > > But in the generator case, I have a problem if the generator object is > not iterated till the StopIteration occurs, but if iteration is stopped > earlier. In that case, the C iterator's destroy is not called, thus the > resource is not freed. > > Is there a way around this? Can I add some sort of __del__() to the > generator object so that in case of an early destruction of the > generator object, the external resource is freed as well? > > I'm looking forward to hearing your hints! > > -- > Stefan Bellon Simple! :-) def get_data(obj): iter = make_iter(obj) try: while more(iter): yield next(iter) finally: destroy(iter) From dogatemycomputer at gmail.com Mon Aug 20 15:04:28 2007 From: dogatemycomputer at gmail.com (dogatemycomputer at gmail.com) Date: Mon, 20 Aug 2007 19:04:28 -0000 Subject: I Need help from all the group participants In-Reply-To: <fack3a$7kk$1@ss408.t-com.hr> References: <fac7nj$ci9$1@localhost.localdomain> <mailman.0.1187630213.32294.python-list@python.org> <fack3a$7kk$1@ss408.t-com.hr> Message-ID: <1187636668.436474.289220@o80g2000hse.googlegroups.com> I would be happy to help but I don't have a clear understand of what the poster needs. From http Fri Aug 24 02:31:28 2007 From: http (Paul Rubin) Date: 23 Aug 2007 23:31:28 -0700 Subject: List Comprehension Question: One to Many Mapping? References: <1187929443.636690.287450@i13g2000prf.googlegroups.com> Message-ID: <7x8x81l9z3.fsf@ruckus.brouhaha.com> beginner <zyzhu2000 at gmail.com> writes: > For example, if I have x=[ [1,2], [3,4] ] > > What I want is a new list of list that has four sub-lists: > > [[1,2], [f(1), f(2)], [3,4], [f(3), f(4)]] [[a, map(f,a)] for a in x] From tooru_honda at fast-mail.org Tue Aug 28 04:27:12 2007 From: tooru_honda at fast-mail.org (tooru honda) Date: Tue, 28 Aug 2007 16:27:12 +0800 Subject: Does shuffle() produce uniform result ? References: <tooru_honda-1F800B.15385124082007@wvnews01.netvigator.com> <mailman.243.1187955760.32294.python-list@python.org> <tooru_honda-7C82D1.10432725082007@wvnews01.netvigator.com> <tooru_honda-58C552.20355225082007@wvnews01.netvigator.com> <tooru_honda-978B9E.11304526082007@wvnews01.netvigator.com> Message-ID: <tooru_honda-DA1E5F.16271128082007@wvnews01.netvigator.com> Thanks to everyone who replied, (and special thanks to Alex Martelli,) I was able to accomplish what I originally asked for: a shuffle() which is both fast and without bias. It is the first time I try to optimize python code, and it is definitely a very rewarding experience. To bring closure to this thread, I will provide below some statistics obtained from cProfile: 1. using random.SystemRandom ncalls tottime percall cumtime percall filename:lineno(function) 4182879 35.154 0.000 211.006 0.000 os.py:724(urandom) 4182879 31.981 0.000 248.291 0.000 random.py:767(random) 40578 17.977 0.000 266.300 0.007 random.py:250(shuffle) 4182879 29.487 0.000 29.487 0.000 {posix.close} 4182879 99.460 0.000 99.460 0.000 {posix.open} 4182879 41.794 0.000 41.794 0.000 {posix.read} 2. my original optimization 8268 0.133 0.000 2.577 0.000 os.py:724(urandom) 4134322 15.094 0.000 21.606 0.000 baccarat.py:70(get2bytes) 4131441 17.221 0.000 41.722 0.000 baccarat.py:85(randrange) 40590 7.059 0.000 48.795 0.001 baccarat.py:112(shuffle) 3. using Alex's generator with string 4117 0.058 0.000 2.048 0.000 os.py:724(urandom) 4214795 10.186 0.000 14.880 0.000 baccarat.py:93(rand2) 4211790 8.883 0.000 23.763 0.000 baccarat.py:106(randrange) 40739 6.101 0.000 29.878 0.001 baccarat.py:131(shuffle) 4. using Alex's generator with array 2081 0.029 0.000 1.736 0.001 os.py:724(urandom) 4161569 1.724 0.000 3.473 0.000 baccarat.py:100(rand2new) 4158474 8.315 0.000 11.788 0.000 baccarat.py:113(randrange) 40514 5.726 0.000 17.528 0.000 baccarat.py:138(shuffle) From steve at holdenweb.com Thu Aug 23 23:54:56 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 23 Aug 2007 23:54:56 -0400 Subject: Making a file-like object for manipulating a large file In-Reply-To: <1187920825.457886.7880@q4g2000prc.googlegroups.com> References: <1187920825.457886.7880@q4g2000prc.googlegroups.com> Message-ID: <falkr3$27f$1@sea.gmane.org> Sean Davis wrote: > This should be a relatively simple problem, but I haven't quite got > the idea of how to go about it. I have a VERY large file that I would > like to load a line at a time, do some manipulations on it, and then > make it available to as a file-like object for use as input to a > database module (psycopg2) that wants a file-like object (with read > and readlines methods). I could write the manipulated file out to > disk and then read it back in, but that seems wasteful. So, it seems > like I need a buffer, a way to fill the buffer and a way to have read > and readlines use the buffer. What I can't do is to load the ENTIRE > file into a stringio object, as the file is much too large. Any > suggestions? > The general approach would be (something like the following untested code): def filter_lines(f): for line in f: if to_be_included(line): yield line fil = open("somefile.big.txt", "r")\ filegen = filter_lines(fil) You can then iterate over the filegen generator, or write your own class that makes it file-like. At least the generator manages to throw away the unwanted content without buffering the whole file in memory. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From wildemar at freakmail.de Fri Aug 24 13:14:46 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 24 Aug 2007 19:14:46 +0200 Subject: Regular expression use In-Reply-To: <8c7f10c60708240954h5af2e55bq823ec167e4247e2e@mail.gmail.com> References: <famdl6$p9j$1@gemini.csx.cam.ac.uk> <8c7f10c60708240954h5af2e55bq823ec167e4247e2e@mail.gmail.com> Message-ID: <46CF1206.5030204@freakmail.de> Simon Brunning wrote: > On 24 Aug 2007 10:58:46 GMT, Nick Maclaren <nmm1 at cus.cam.ac.uk> wrote: > >> For reasons that I won't explain, as they are too complicated >> and not terribly relevant, I am interested in discovering what >> people actually use regular expressions for. >> > > http://xkcd.com/208/ > > That was the one that got me hooked on xkcd. I remember laughing so hard at that. A friend and I still quote that one (and others). /W From info at thegrantinstitute.com Sat Aug 25 01:26:20 2007 From: info at thegrantinstitute.com (Anthony Jones) Date: 24 Aug 2007 22:26:20 -0700 Subject: Professional Grant Proposal Writing Workshop (September 2007: Simon Fraser University) Message-ID: <20070824222620.80437F74DB76B9BF@thegrantinstitute.com> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070824/f9613bf5/attachment.html> From kyosohma at gmail.com Sat Aug 18 13:02:55 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Sat, 18 Aug 2007 17:02:55 -0000 Subject: wxPython with directpython In-Reply-To: <1187448399.382222.177340@22g2000hsm.googlegroups.com> References: <1187442509.620003.316770@r34g2000hsd.googlegroups.com> <1187444103.381907.103240@m37g2000prh.googlegroups.com> <1187448399.382222.177340@22g2000hsm.googlegroups.com> Message-ID: <1187456575.956702.296510@q4g2000prc.googlegroups.com> On Aug 18, 9:46 am, vedrandeko... at v-programs.com wrote: > On 18 kol, 15:35, kyoso... at gmail.com wrote: > > > > > On Aug 18, 8:08 am, vedrandeko... at v-programs.com wrote: > > > > Hello, > > > > I'am using DirectPython 0.8, wxPython 2.8.4.2 (ansi) for Python 2.5 > > > and I'm running it on windows XP SP2. > > > When I run my wx program, and this program run directpython code: > > > > (I run it under wx frame) > > > > example code: > > > > import d3dx > > > fr=d3dx.Frame(unicode("My frame")) > > > fr.mainloop() > > > > .....this code run some d3dx frame, and when I close this d3dx frame > > > it close my whole program ( and wx frame). > > > > Regards, > > > Vedran > > > You need to post some more code, preferably the function that calls > > the directx stuff. And how do you catch the close event? It sounds > > like you've got multiple objects bound to it which causes the entire > > program to close. You might consider running the directx stuff in a > > separate thread. > > > Mike > > Hi, > > no,that's all code I've got,I mean it's all code that I run with my > program for now. > > >You might consider running the directx stuff in a separate thread. > > How? > > Regards, > Vedran Check out this link for more information on running stuff in another thread: http://wiki.wxpython.org/LongRunningTasks?highlight=%28longrunning%29 Mike From Jiandong.Ge at gmail.com Thu Aug 2 12:41:38 2007 From: Jiandong.Ge at gmail.com (JD) Date: Thu, 02 Aug 2007 16:41:38 -0000 Subject: File access Message-ID: <1186072898.405831.105670@e16g2000pri.googlegroups.com> Hi, What I am trying to do is to run a subprocess on another machine using subprocess.Popen, this subprocess contuinue writing something into a file when it is runing. After submit this subprocess, I tried to open the file and readlines() in the loop (with a delay) in the loop) when the subprocess was runing. The problem is I could not get anything untill the subprocess finished. I also tried to run another python programm when the subprocess is runing, I could get what I want. Does anyone know why? Thanks! JD From pippo at pippopippo.pp Fri Aug 17 11:50:15 2007 From: pippo at pippopippo.pp (pierbrun@alice.it) Date: Fri, 17 Aug 2007 17:50:15 +0200 Subject: best GUI library for vector drawing program In-Reply-To: <1187357244.883516.79840@j4g2000prf.googlegroups.com> References: <1187357244.883516.79840@j4g2000prf.googlegroups.com> Message-ID: <46c5c3b9$0$36443$4fafbaef@reader5.news.tin.it> I used wxWidgets for a work like that. I found it quite easy to use and I found simple to create a Gui with wxdev which is quite rad. bye Pier Paolo From steve at holdenweb.com Sun Aug 12 07:08:49 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 12 Aug 2007 07:08:49 -0400 Subject: Web based Reporting tool for Python In-Reply-To: <f9mno6$tgl$1@sea.gmane.org> References: <1186460956.945148.162610@k79g2000hse.googlegroups.com> <mailman.1722.1186522221.22759.python-list@python.org> <1186547726.383996.291360@d55g2000hsg.googlegroups.com> <2007080808575016807-jon@turnthepageorg> <1186891194.582444.222010@r34g2000hsd.googlegroups.com> <f9mno6$tgl$1@sea.gmane.org> Message-ID: <f9mpnt$317$1@sea.gmane.org> Steve Holden wrote: > Madhu Alagu wrote: >> On Aug 8, 4:57 pm, Jon Rosebaugh <j... at turnthepage.org> wrote: >>> On 2007-08-07 23:35:26 -0500, Madhu Alagu <alma... at gmail.com> said: >>> >>>> Thanking so much for all the informations and links.I would like to >>>> use Mako Templates(www.makotemplates.org).Ilike to use simple and >>>> python default module... >>> Mako is an excellent template system, but you'll have a lot of work to >>> do making it into a reporting system. >> >> >> Any reporting template in python ? >> > > Dabo (www.dabodev.com) is certainly heading that way, but I am not sure > how far it's got yet. > Sorry, Dabo isn't web-based. You could look at Kid, Genshi, Cheetah, ... Or you could do a Google search for "python web template" and see what comes up. There are many good contenders. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From steve at holdenweb.com Thu Aug 30 14:00:15 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Aug 2007 14:00:15 -0400 Subject: list index() In-Reply-To: <1188495863.242815.236900@o80g2000hse.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <mailman.135.1188474634.28954.python-list@python.org> <1188495863.242815.236900@o80g2000hse.googlegroups.com> Message-ID: <fb70jj$mdp$1@sea.gmane.org> zzbbaadd at aol.com wrote: >> How could it not be an exception, in the plain English sense of the >> word? Most certainly you're asking for the index because you want to do >> something with the index. If the item is not found, you have no index, >> so that's a special case that must be handled separately. There is no >> logical difference between handling that special case in an except >> clause versus handling it with an if-branch. > > In my case of have done os.listdir() on two directories. I want to see > what files are in directory A that are not in directory B. > I have used exceptions in other languages and only do so on logic that > should never happen. In this case it is known that some of the files > will not be in both lists. I just want to know which ones. > And, as is so often the case, once the *real* problem is stated a more elegant solution become available - in this case, using sets. afiles = set(os.listdir(dira)) bfiles = set(os.listdir(dirb)) for f in (afiles - bfiles): print "Not common:", f You can also generate the files that are in one directory but ot the other with (afiles | bfiles) - (afiles & bfiles) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From vodela.sai at gmail.com Fri Aug 3 12:47:40 2007 From: vodela.sai at gmail.com (Rohan) Date: Fri, 03 Aug 2007 16:47:40 -0000 Subject: Email In-Reply-To: <46b2393f$0$27409$ba4acef3@news.orange.fr> References: <1186076005.729346.327140@z24g2000prh.googlegroups.com> <46b2393f$0$27409$ba4acef3@news.orange.fr> Message-ID: <1186159660.264082.91830@j4g2000prf.googlegroups.com> On Aug 2, 1:06 pm, Laurent Pointal <laurent.poin... at wanadoo.fr> wrote: > Rohan wrote: > > I was wondering if there could be an arrangement where a file could be > > attached and send as an email. > > For ex > > f = open(add.txt,w) > > f.write('python') > > f.close() > > > Now I would like to send an email with add.txt as an attachment, is it > > possible ? > > some one give me a pointer towards this. > > You can use iMailer as an example script to get parts: > > http://nojhan.free.fr/article.php3?id_article=22 > > A+ > > Laurent. Laurent the link you gave me is in a language unknown to me if you have anything that expalains in english, then let me know. thanks From david at nospam.spam Mon Aug 27 00:38:55 2007 From: david at nospam.spam (david) Date: Mon, 27 Aug 2007 14:38:55 +1000 Subject: wxpython thread exception crash In-Reply-To: <13ckp4nj0kt6583@corp.supernews.com> References: <13ckp4nj0kt6583@corp.supernews.com> Message-ID: <13d4lavcsdo6o77@corp.supernews.com> class RedirectText: def __init__(self,aWxTextCtrl): self.out=aWxTextCtrl def write(self,string): wx.CallAfter(self.out.WriteText,string) #CallAfter def flush(self): pass [david] [david] wrote: > What am I doing wrong? > I'm trying to capture stdErr in a multi-threaded program. > > This code crashes wxPython with > /Py Assertion Error: C++ assertion "m_count=-1 || m_count=-2" failed/ > > What I'm trying to do is redirect stderr and stdout to a wxPython text > control. > In an ideal world, when the worker thread crashes, I should get a stderr > message, with no effect on the main thread. > > In an alternate world, I should get an asynchronous exception in the > main thread when there is an unhandled exception in the worker thread. > > In the sample below, the program crashes on the following print statement. > > Oddly enough, I do catch the unhandled worker exception in the main > thread IF THE WORKER THREAD HAS NO INIT PARAMETER. Note: the init > parameter is the only subtle thing in the code. > > Since this is a crash, the exact behaviour will depend on your > environment. You may have difficulty seeing stdErr in some environments. > > Python 2.5, wxPython 2.7.2.0, Windows XP. > (david) > > -------- > import wx > import sys > import threading > > class ExceptionThread(threading.Thread): > def __init__(self,initvar): > threading.Thread.__init__(self); > > def run(self): > raise "ET run" > > > class RedirectText: > def __init__(self,aWxTextCtrl): > self.out=aWxTextCtrl > > def write(self,string): > self.out.WriteText(string) > > def flush(self): > pass > > class Frame(wx.Frame): > def __init__(self, image=None, parent=None): > > wx.Frame.__init__(self, parent) > self.text = wx.TextCtrl(self, style=wx.TE_MULTILINE|wx.TE_RICH2) > > #---- redirection window ---- > redir=RedirectText(self.text) > sys.stdout=redir > sys.stderr=redir > > > class App(wx.App): > def OnInit(self): > self.frame=Frame() > self.frame.Show() > self.Thread=ExceptionThread(1) > self.Thread.start(); > return True > > > app = App() > print 'trigger print failure' > app.MainLoop() > > From steve at holdenweb.com Sun Aug 19 22:52:15 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 19 Aug 2007 22:52:15 -0400 Subject: question In-Reply-To: <1187574897.183659.22140@l22g2000prc.googlegroups.com> References: <1187373737.410546.70930@w3g2000hsg.googlegroups.com> <fa4pn7$5sh$03$1@news.t-online.com> <1187574897.183659.22140@l22g2000prc.googlegroups.com> Message-ID: <faavkn$9tp$1@sea.gmane.org> CarpeSkium at gmail.com wrote: > On Aug 17, 2:34 pm, Peter Otten <__pete... at web.de> wrote: >> CarpeSk... at gmail.com wrote: >>> "I've parsed a webpage into a text file. In doing so, I've kept all >>> the text I'm interested in, and removed all the text I don't want. My >>> result is a text file that iscomma-separated. However, the text file >>> is one, very long, single string. I need to substitute every eighth >>> (8th)commawith a new line ("\n"). I've tried regular expressions, >>> but don't know how to make this happen on only every eighthcomma. I'd >>> post my code, but none of it works. Thanks for the help." >>>>> text = "aaa," * 20 >>>>> from itertools import cycle, groupby >>>>> print "\n".join(",".join(g) for k, g in groupby(text.split(","), >> ... key=lambda key, c=cycle([True]*8+[False]*8): c.next())) >> aaa,aaa,aaa,aaa,aaa,aaa,aaa,aaa >> aaa,aaa,aaa,aaa,aaa,aaa,aaa,aaa >> aaa,aaa,aaa,aaa, >> >> :-) >> >> Peter > > Thanks Peter. I'll try that first thing Monday morning when I'm back > to work. It > is a totally different approach than what I was trying with regex. > > And Shawn, I didn't post any of my work because the network I work on > isn't > connected to the internet. So it didn't seem constructive to re-type > all of my > failed code just to satisfy your "standards" of proving that I've been > trying to > hack this myself for the past few days. All in all, thanks for your, > uhhhh, > constructive comments. > Aah, right, and the USB thumb drive won't be invented for another 20 years. Damn. Sorry, been reading too much bash.org. Damn that Michael Foord ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From max at alcyone.com Sun Aug 12 20:14:19 2007 From: max at alcyone.com (Erik Max Francis) Date: Sun, 12 Aug 2007 17:14:19 -0700 Subject: Fatest standard way to sum bytes (and their squares)? In-Reply-To: <yfs643l84fu.fsf@gmail.com> References: <NPmdnVwqHa74TyPbnZ2dnUVZ_uKpnZ2d@speakeasy.net> <yfs643l84fu.fsf@gmail.com> Message-ID: <ntGdnTiqYbjGPyLbnZ2dnUVZ_gadnZ2d@speakeasy.net> Alexander Schmolck wrote: > Is this any faster? > > ordSum, orsSumSq = (lambda c:c.real,c.imag)(sum(complex(ord(x),ord(x)<<1) > for x in data)) That's pretty clever, but I neglected to mention that I need to accumulate the sums as ints/longs to avoid losing precision, so converting to floating point isn't an optional. (The sums are normalized by the sizes of the files and expanded to 32 bits in order to maximize precision.) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis Experience is the name everyone gives to their mistakes. -- Oscar Wilde From ayaz at dev.null Thu Aug 23 01:48:10 2007 From: ayaz at dev.null (Ayaz Ahmed Khan) Date: Thu, 23 Aug 2007 10:48:10 +0500 Subject: introspection and functions References: <1187819949.515982.15450@r23g2000prd.googlegroups.com> <B33zi.4126$Oo.317@newssvr17.news.prodigy.net> Message-ID: <20070823104810.6054520f.ayaz@dev.null> "James Stroud" typed: > py> def doit(a, b, c, x=14): > ... pass > ... > py> doit.func_code.co_argcount > 4 > py> doit.func_code.co_varnames > ('a', 'b', 'c', 'x') > py> doit.func_defaults > (14,) Neat. -- Ayaz Ahmed Khan I have not yet begun to byte! From martin at v.loewis.de Thu Aug 16 13:21:12 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 16 Aug 2007 19:21:12 +0200 Subject: ctypes and C99 complex numbers In-Reply-To: <mailman.2063.1187278793.22759.python-list@python.org> References: <1187266067.24753.12.camel@wheeler.hlphys.uni-linz.ac.at> <mailman.2063.1187278793.22759.python-list@python.org> Message-ID: <46c48789$0$9301$9b622d9e@news.freenet.de> Thomas Heller schrieb: > Eugen Wintersberger schrieb: >> Hi there >> I want to use ctypes in connection with C functions that use complex >> datatypes defined in the C99 standard. Does someone know a simple way >> how to implement this? Are there any plans to integrate the C99 complex >> data types in the ctypes module? > > I have investigated the complex data types a bit and came to the conclusion > that libffi (which ctypes is based upon) would have to be extended to > support these complex types. I think that depends on what kind of support you want to provide. For passing _Complex values as parameters or receiving them as results, it's certainly necessary to have libffi support. OTOH, if you only want to support _Complex as the field type of a struct or an array, you can do so without libffi support. To write a field at address p with the values r and i, do *(double complex*)p = r * i*I; To fetch the real and imaginary part of a field at address p, do creal(*(double complex*)p) cimag(*(double complex*)p) Likewise for float complex values (and long double complex, if you want to support that). Whether such a limited version would be of any use (e.g. to the OP), I don't know. Regards, Martin From afriere at yahoo.co.uk Tue Aug 21 03:54:53 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 21 Aug 2007 00:54:53 -0700 Subject: Newbee Question In-Reply-To: <1187682705.769160.68850@q3g2000prf.googlegroups.com> References: <mailman.15.1187620149.26576.python-list@python.org> <1187682119.353756.278840@i13g2000prf.googlegroups.com> <1187682705.769160.68850@q3g2000prf.googlegroups.com> Message-ID: <1187682893.684750.118630@e9g2000prf.googlegroups.com> On Aug 21, 5:51 pm, Asun Friere <afri... at yahoo.co.uk> wrote: > On Aug 21, 5:41 pm, Asun Friere <afri... at yahoo.co.uk> wrote:> over = Decimal('1.40) > > oops, that should of course be: > over = Decimal('1.40') oh boy ... and it should also be normal = Decimal('0.40') I really need to test before posting ... From thomas at jollans.com Thu Aug 16 19:20:02 2007 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 17 Aug 2007 01:20:02 +0200 Subject: Pass by reference or by value? In-Reply-To: <496954360708161402x58faba47x7a6eae6e68f81d4@mail.gmail.com> References: <496954360708161402x58faba47x7a6eae6e68f81d4@mail.gmail.com> Message-ID: <200708170120.07645.thomas@jollans.com> On Thursday 16 August 2007, Robert Dailey wrote: > Hi, > > I previously created a topic named "Pass by reference or by value" where I > inquired on how python's function parameters work. I received a lot of nice > responses, however I'm still confused on the topic. Note that I come from a > C++ background to Python, so any comparisons to C++ would be very helpful. Very short answer: Think of normal objects as always-pointers. There are no references. param = 5 sets the local variable "param" (be that of imaginary type int* or int, I don't care) to whatever 5 is. This does not call an operator=, this plain overwrites the variable. If you want to change arguments in that way, you can use a list as an ugly hack: def foo(param): param[0] = 5 print param[0] a = [4] foo(a) yeah, I said ugly. That hack makes sure that a method of the passed object is called instead of of the local namespace dict. (please note that I'm throwing around abstract concepts without caring about an implementation). -- Regards, Thomas Jollans GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu Hacker key <http://hackerkey.com/>: v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part. URL: <http://mail.python.org/pipermail/python-list/attachments/20070817/31d70695/attachment.sig> From steve at holdenweb.com Fri Aug 31 11:02:35 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 31 Aug 2007 11:02:35 -0400 Subject: MySQLdb ImportError In-Reply-To: <1188546939.086855.204670@q5g2000prf.googlegroups.com> References: <1188546939.086855.204670@q5g2000prf.googlegroups.com> Message-ID: <fb9aid$e3l$2@sea.gmane.org> Sjoerd wrote: > Hello! > > When I try to import the MySQLdb lib python generates an error: > > Traceback (most recent call last): > File "<pyshell#0>", line 1, in <module> > import MySQLdb > File "C:\Python25\lib\site-packages\MySQLdb\__init__.py", line 19, > in <module> > import _mysql > ImportError: DLL load failed with error code 193 > > This is on a AMD64 bit machine, when I import it on a 32 bit machine > it works fine. > Is there anyway to fix this? Is there a build for AMD64 bit machines > or is there simply no way > that I can get MySQLdb working on it? > > Thanks in advance, > Sjoerd > I'm not aware of a current build for that architecture (and your assumption that the load fails because of the architecture mismatch is correct). It is possible to build the module yourself if it's important enough. I remember doing this some time ago with the Microsoft free compiler kit, for example. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From aleax at mac.com Sun Aug 19 01:38:56 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 18 Aug 2007 22:38:56 -0700 Subject: Understanding closures References: <1187499818.125192.12930@m37g2000prh.googlegroups.com> Message-ID: <1i32c61.3hu08w15buuxtN%aleax@mac.com> Ramashish Baranwal <ramashish.lists at gmail.com> wrote: > Hi, > > I want to use variables passed to a function in an inner defined > function. Something like- > > def fun1(method=None): > def fun2(): > if not method: method = 'GET' > print '%s: this is fun2' % method > return > fun2() > > fun1() > > However I get this error- > UnboundLocalError: local variable 'method' referenced before > assignment > > This however works fine. > > def fun1(method=None): > if not method: method = 'GET' > def fun2(): > print '%s: this is fun2' % method > return > fun2() > > fun1() > > Is there a simple way I can pass on the variables passed to the outer > function to the inner one without having to use or refer them in the > outer function? Sure, just don't ASSIGN TO those names in the inner function. Any name ASSIGNED TO in a given function is local to that specific function (save for global statements, which bypass variable of containing functions anyway). Alex From Brian.McCann at viziant.net Mon Aug 20 15:02:59 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Mon, 20 Aug 2007 15:02:59 -0400 Subject: reading a line in file References: <93066C069973ED448DC2BCEA9C44A7383BE2B2@efmailx><2dc0c81b0708201029k5909d919vcf0deebae74a79c7@mail.gmail.com><B81734159.43.61526.2@mxextra> <9afea2ac0708201159t4602fe3fpfb738a22f063f37@mail.gmail.com> Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE2B5@efmailx> Hi Tim, The sample data is in file build.number contents of file build.number: #Build Number for ANT. Do not edit! #Mon Aug 20 04:04:51 EDT 2007 build.number=1 Thanks, Brian ________________________________ From: tdwdotnet at gmail.com on behalf of Tim Williams Sent: Mon 8/20/2007 2:59 PM To: Brian McCann Cc: python-list at python.org Subject: Re: reading a line in file On 20/08/07, Brian McCann <Brian.McCann at viziant.net> wrote: > > Hi, > > I can read in the whole file build.number which has the following lines > how do I just capture the value of build.number and assign it to a variable > Thanks, > Brian > > contents of file build.number: > #Build Number for ANT. Do not edit! > #Mon Aug 20 04:04:51 EDT 2007 > build.number=1 > buildinfo.py > ################################## > #!/usr/bin/python > import string > import os > import sys > import time > import errno > import shutil > buildinfo = "build.number" > input = open(buildinfo, 'r') > for line in input: > print line > ######################################### > > command line when script is run > $ buildinfo.py > #Build Number for ANT. Do not edit! > > #Mon Aug 20 04:04:51 EDT 2007 > build.number=1 > > This is preferred nowadays for line in open(buildinfo): print line Without a sample of the data, no-one can help you further. If this is homework, you should say so, people will give you guidance :) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070820/361cb155/attachment.html> From deets at nospam.web.de Wed Aug 22 03:19:13 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 22 Aug 2007 09:19:13 +0200 Subject: redirect or cover .bat log In-Reply-To: <1187764689.836375.212730@z24g2000prh.googlegroups.com> References: <1187764689.836375.212730@z24g2000prh.googlegroups.com> Message-ID: <5j26bvF3s7lbpU2@mid.uni-berlin.de> vedrandekovic at v-programs.com schrieb: > Hello, > > e.g I need run my my_scripts_setup.bat that contain: > > python myscript_setup.py py2exe > > > Can I cover or redirect log of that process into my wx program? > I'am using Windows XP SP2, and Python 2.5. Who's running the bat, and who's running the wx program? Diez From rdm at rcblue.com Sun Aug 12 13:22:51 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 12 Aug 2007 10:22:51 -0700 Subject: Puzzled by "is" In-Reply-To: <f9neac$8aq$1@sea.gmane.org> References: <20070809194105.39BD11E400A@bag.python.org> <f9frbl$dps$1@sea.gmane.org> <mailman.1814.1186692638.22759.python-list@python.org> <87zm1042f0.fsf@benfinney.id.au> <mailman.1839.1186768658.22759.python-list@python.org> <87ir7l5bv4.fsf@benfinney.id.au> <d71c7ed60708120626y6d9a9edcnf007a5273de125cc@mail.gmail.com> <f9n8lb$cg9$1@sea.gmane.org> <20070812163657.2F8F41E400B@bag.python.org> <f9neac$8aq$1@sea.gmane.org> Message-ID: <20070812172301.009F51E401C@bag.python.org> At 09:59 AM 8/12/2007, Steve Holden wrote: >Dick Moores wrote: > > At 08:23 AM 8/12/2007, Steve Holden wrote: > >> Dick Moores wrote: > >>> So would a programmer EVER use "is" in a script? > >> Sure. For example, the canonical test for None uses > >> > >> x is None > >> > >> because there is only ever one instance of type Nonetype, so it's the > >> fastest test. Generally speaking you use "is" to test for identity (do > >> these two expressions reference the same object) rather than equality > >> (do these two expressions evaluate to equivalent objects). > > > > Off the top of your head, could you or others give me as many > > examples as you can think of? > > >Occasionally it's necessary to test for a specific type (though in >Python this is usually bad practice). Since types are also singletons >the best way to do this is (e.g.): > > type(x) is type([]) # test specifically for a list > >If you want to know whether you have been told to write to standard >output, one possible test is > > if f is not sys.stdout > >Similarly, of course, you can test for the other standard IO channels. > >The imputil module contains the test > > if importer is not self > >to determine whether a reload() should be performed in the context of >the current package. > >When you need to establish a specific sentinel value that can never be >provided by an outside caller it's normal to create an instance of >object (the simplest possible thing you can create in a Python program) >and test for that instance, as in > > sentinel = object() > ... > if value is sentinel: > >You can test whether a class is new-style as opposed to old-style, which >can help to unify old-style and new-style objects: > >class MetaProperty(type): > def __new__(cls, name, bases, dct): > if bases[0] is object: # allow us to create class Property > return type.__new__(cls, name, bases, dct) > return property(dct.get('get'), dct.get('set'), > dct.get('delete'), dct.get('__doc__')) > > def __init__(cls, name, bases, dct): > if bases[0] is object: > return type.__init__(cls, name, bases, dct) > > >That gets you started ... Sure does. Thanks very much, Steve. Dick From steve at holdenweb.com Fri Aug 31 15:28:08 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 31 Aug 2007 15:28:08 -0400 Subject: strings (dollar.cents) into floats In-Reply-To: <1188586725.667740.255700@o80g2000hse.googlegroups.com> References: <mailman.140.1188483282.28954.python-list@python.org> <877incd20i.fsf@benfinney.id.au> <46d75cf3$0$7698$9b4e6d93@newsspool2.arcor-online.net> <1188575044.874256.42960@50g2000hsm.googlegroups.com> <fb9eas$tnc$1@sea.gmane.org> <mailman.218.1188577696.28954.python-list@python.org> <46d84a47$0$1346$834e42db@reader.greatnowhere.com> <1188586725.667740.255700@o80g2000hse.googlegroups.com> Message-ID: <fb9q4a$55a$2@sea.gmane.org> MRAB wrote: > On Aug 31, 5:39 pm, David H Wild <dhw... at talktalk.net> wrote: >> In article <mailman.218.1188577696.28954.python-l... at python.org>, >> Chris Mellon <arka... at gmail.com> wrote: >> >>> I believe that to the degree that "real" accounting was done in those >>> currencies it did in fact use non-decimal bases. Just as people don't >>> use decimal time values (except us crazy computer folk), you're write >>> 1 pound 4 shillings, not 1.333... pounds. >> When I worked on the British Railways National Payroll system, about 35 >> years ago, we, in common with many large users, wrote our system to deal >> with integer amounts of pennies, and converted to pounds, shillings and >> pence in the output part of the system. >> > So you never handled halfpennies? > Nobody was paid to the ha'penny. You could spend them in the shops, but payroll systems didn't use them. I am happy to say that I didn't become involved in financial programming until after decimalization (February 1971, IIRC - I was in Sweden at the time). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From raul at cgb.cl Mon Aug 27 16:54:01 2007 From: raul at cgb.cl (Raul Araya) Date: Mon, 27 Aug 2007 16:54:01 -0400 Subject: include folder Message-ID: <46D339E9.1000200@cgb.cl> Dear Python users and developers: My trouble is as follows: I'm putting back on line an old pc-linux cluster. Today while trying to install a python based program I got an error regarding the Python.h file that should be in the /include/Phyton2.3 folder. So I went looking for the file but it wasn't there, I mean the whole folder /Phyton2.3 inside the /usr/include directory was not there. I am not te administrator of that cluster that has been off for at least 2 years, so I really don't know what to do. Please help. My Linux version is: Debian GNU-Linux My Python version is: 2.3 Many thanks Ra?l Araya Faculty of sciences Universidad de Chile Santiago Chile From laurent.pointal at limsi.fr Tue Aug 28 06:38:32 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 28 Aug 2007 12:38:32 +0200 Subject: SCF released to GPL In-Reply-To: <zHLAi.102$7P7.54@newssvr19.news.prodigy.net> References: <ZBnAi.21498$eY.43@newssvr13.news.prodigy.net> <46d29a6c$0$27404$ba4acef3@news.orange.fr> <zHLAi.102$7P7.54@newssvr19.news.prodigy.net> Message-ID: <fb0tv8$njd$1@news2.u-psud.fr> hg a ?crit : > 2) I'm desperately searching for the French NG from my client but cannot > find it ... any clue ? Maybe you can pass the message ? Contact Michel Claveau ( enleverlesX.XmcX at XmclaveauX.com ) for a solution via his Usenet relay. A+ Laurent. From brotherjenos at gmail.com Wed Aug 1 18:55:51 2007 From: brotherjenos at gmail.com (Walker Lindley) Date: Wed, 1 Aug 2007 15:55:51 -0700 Subject: sending very large packets over the network Message-ID: <9c8d48280708011555l5d1d439fu3c5fbcc61dc41f07@mail.gmail.com> OK, I'm back with another networking question. I'm trying to seend large amounts of information over TCP (the length of data being given to send() is on the order of 16000 characters in length). Unfortunately on the receiving end, the packets appear to be truncated. So I wrote some code that continuously tries to send bigger and bigger packets until it fails and noticed that it never fails at the same length. I'm not even sure these two things are related, but is there some undocumented (or documented and I missed it) maximum size for data you can pass to send()? the sample code is as follows #server import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 2000)) s.listen(0) sock, addrinfo = s.accept() for i in range(2 ** 16): length = int(sock.recv(16)) print "excpecting data of length:", length data = sock.recv(length) print "received data of length:", len(data) print s.close() sock.close() #client import socket import time s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 2001)) s.connect(("localhost", 2000)) for i in range(2 ** 16): packet = "h" * i s.send("%16d" % len(packet)) print "attempting to send data of length:", len(packet) tmp = s.send(packet) print "actually sent data of length:", tmp print time.sleep(.001) s.close() i just put them in different files and ran them from the command line. Any help or suggestions would be greatly appreciated. Thanks. -Walker -- This e-mail is licensed under the Creative Commons Attribution-NoDerivs 2.5License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nd/2.5/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070801/46f7ce5c/attachment.html> From mcl.office at googlemail.com Sun Aug 19 16:29:33 2007 From: mcl.office at googlemail.com (mosscliffe) Date: Sun, 19 Aug 2007 13:29:33 -0700 Subject: Symbolic Link In-Reply-To: <iwWxi.28394$RX.20505@newssvr11.news.prodigy.net> References: <1187475296.173269.263080@k79g2000hse.googlegroups.com> <iwWxi.28394$RX.20505@newssvr11.news.prodigy.net> Message-ID: <1187555373.202634.163160@57g2000hsv.googlegroups.com> On 19 Aug, 13:16, samwyse <dejan... at email.com> wrote: > mosscliffewrote: > > I am trying to create a link to a file, which I can then use in an > > HTML page. > > > The system is Linux on a hosted web service, running python 2.3. > > Other than that I have no knowledge of the system. > > > The link is created OK, but when I try to use it as filename for the > > IMG TAG, it does not get displayed. The page source of the created > > page is pointing to the link as temp/test1.jpg > > What are you trying to do that you can't use the original file instead > of creating a link? There might be a way to side-step the entire problem. The source file is in an area which python can see, but not the browser. I am trying to make a link in a browser friendly area so I can use it to display an image file. Thanks Richard From bbxx789_05ss at yahoo.com Mon Aug 6 12:03:45 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 06 Aug 2007 09:03:45 -0700 Subject: udp, datagram sockets Message-ID: <1186416225.769753.307110@o61g2000hsh.googlegroups.com> I'm trying to understand datagrams. My client program sends a message to the server, and then the server infinitely loops over the recv() to make sure all the data was received. I'm trying to use an * to signal the end of the message, so that the server can break out of the infinite while loop used to check the recv(). However, my server repeatedly outputs the client message over and over again. Can anyone tell me why? When I start the server, I get the following debug output as expected: --------- debug: start outer while loop #this infinite while loop endlessly listens for messages from the client debug: recv while loop #this infinite while loop checks to make sure the whole message was received ----------- and then the recv() blocks and waits for data to be sent by the client. But when I start the client, the server repeatedly outputs the client message over and over again. My expectation was that after processing the message from the client, the server would block the next time it executed the recv() statement and wait for more data from the client. client: ---------- import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) message = "hello*" #asterisk to delimit end of message msg_size = len(message) total_sent = 0 print "debug:", total_sent, msg_size while total_sent < msg_size: size_sent = s.sendto(message[total_sent:], ("localhost", 7777) ) total_sent += size_sent print "debug:", total_sent, msg_size print 'debug: while loop ended' s.close() ----------- Here's the client output: ------------- debug: 0 6 debug: 6 6 debug: while loop ended --------------- server: ------------------ import socket import sys s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(("", 7777)) try: while True: #This loop listens endlessly for messages. print "debug: start outer while loop" #Receive messages from client: my_list = [] while True: #This loop checks to see if the whole message was received. print "debug: recv while loop" data = s.recv(1024) my_list.append(data) if data.rfind("*"): message = "".join(my_list) print "Received message:\n%s" % message[:-1] break #Send messages back to client: total_sent = 0 while total_sent < len(message): print "debug: send while loop" size_sent = s.sendto(message[total_sent:], ("localhost", 7777) ) total_sent += size_sent print "debug:", total_sent, len(message) finally: s.close() -------------------------- Here's the server output: --------------- debug: start outer while loop debug: recv while loop Received message: hello debug: send while loop debug: 6 6 debug: start outer while loop debug: recv while loop Received message: hello debug: send while loop debug: 6 6 .... .... .... ------------------ From horpner at yahoo.com Tue Aug 14 10:50:08 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 14 Aug 2007 14:50:08 GMT Subject: Module imports during object instantiation References: <4c3vo4-u7k.ln1@learner.hq.netapp.com> <f9pcuj$6n4$1@sea.gmane.org> <mailman.1931.1187030415.22759.python-list@python.org> <46c16ec9$0$405$426a34cc@news.free.fr> <mailman.1956.1187091452.22759.python-list@python.org> <slrnfc36p9.21o.horpner@FIAD06.norwich.edu> <mailman.1965.1187101832.22759.python-list@python.org> Message-ID: <slrnfc3gg4.1l4.horpner@FIAD06.norwich.edu> On 2007-08-14, Ritesh Raj Sarraf <rrs at researchut.com> wrote: > Neil Cerutti wrote: > >> If you want an import inside an __init__ to run, you must call >> the __init__ function that contains it. > > Doesn't __init__ get called automatically ? It gets called automatically when you construct an instance of the class in which it's defined. > I thought __init__ was required to be called explicitly only > when you were doing inheritance and wanted to pass separate > values to the base class. You don't have to call it explicitly to get it to run. -- Neil Cerutti Customers who consider our waitresses uncivil ought to see the manager --sign at New York restaurant From martin at v.loewis.de Wed Aug 22 16:35:59 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 22 Aug 2007 22:35:59 +0200 Subject: MsiLib In-Reply-To: <mailman.136.1187813962.32294.python-list@python.org> References: <mailman.136.1187813962.32294.python-list@python.org> Message-ID: <46cc9e2f$0$1456$9b622d9e@news.freenet.de> Charlie schrieb: > Thanks for pointing that out. It solved the one problem and along came > another. Now I get the following error when I try running it. Thanks for > the help. > > Traceback (most recent call last): > File "msi.py", line 7, in <module> > record = view.Fetch() > _msi.MSIError: function failed Ah. You need to call view.Execute() first. See http://msdn2.microsoft.com/en-us/library/aa370514.aspx Regards, Martin From a.schmolck at gmail.com Wed Aug 1 12:01:39 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Wed, 01 Aug 2007 17:01:39 +0100 Subject: What is the "functional" way of doing this? References: <1185835690.530367.66600@m37g2000prh.googlegroups.com> Message-ID: <yfsabtbi6qk.fsf@gmail.com> beginner <zyzhu2000 at gmail.com> writes: > Hi, > > If I have a number n and want to generate a list based on like the > following: > > def f(n): > l=[] > while n>0: > l.append(n%26) > n /=26 > return l > > I am wondering what is the 'functional' way to do the same. This is very 'functional' (and also quite concise): f = compose(list,partial(unfold, divmod(_,26))) The definitions of compose, unfold, and _ are left as excercises (of increasing difficulty) for the reader. 'as From steven.bethard at gmail.com Sun Aug 12 18:35:05 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 12 Aug 2007 16:35:05 -0600 Subject: A dumb question about a class In-Reply-To: <mailman.1888.1186957809.22759.python-list@python.org> References: <mailman.1887.1186955369.22759.python-list@python.org> <TqSdnWYzVdWvGCLbnZ2dnUVZ_saknZ2d@comcast.com> <mailman.1888.1186957809.22759.python-list@python.org> Message-ID: <euCdnYM4sfSHFiLbnZ2dnUVZ_gadnZ2d@comcast.com> Dick Moores wrote: > At 03:09 PM 8/12/2007, Steven Bethard wrote: > >> Here's how I'd write the recipe:: >> >> import itertools >> >> def iter_primes(): >> # an iterator of all numbers between 2 and +infinity >> numbers = itertools.count(2) >> >> # generate primes forever >> while True: >> >> # get the first number from the iterator (always a prime) >> prime = numbers.next() >> yield prime >> >> # remove all numbers from the (infinite) iterator that are >> # divisible by the prime we just generated >> numbers = itertools.ifilter(prime.__rmod__, numbers) >> >> >> class PrimeList(object): >> def __init__(self): >> # infinite iterator of primes >> self._prime_iter = iter_primes() >> >> # the last prime we've seen >> self._last_prime = None >> >> # all primes seen so far >> self._prime_set = set() >> >> # add the first prime (so that _last_prime is set) >> self._add_prime() >> >> def __contains__(self, n): >> # add primes to the list until we exceed n >> while n > self._last_prime: >> self._add_prime() >> >> # return True if n is one of our primes >> return n in self._prime_set >> >> def _add_prime(self): >> # take a prime off the iterator and update the prime set >> self._last_prime = self._prime_iter.next() >> self._prime_set.add(self._last_prime) > > I'm afraid my next question is "How do I run this"? The same way I showed at the top (which you snipped in your reply):: >>> plist = PrimeList() >>> 1 in plist False >>> 2 in plist True >>> 22 in plist False >>> 23 in plist True >>> 782 in plist False >>> 787 in plist True The first line, ``plist = PrimeList()`` creates a PrimeList object and names it ``plist``. You can then check whether a prime is in that PrimeList object much like you might check a normal ``list`` or ``set`` object -- using the ``in`` operator as above. Note that if you just want to iterate over all the primes, there's no need for the class at all. Simply write:: for prime in iter_primes(): ... HTH, STeVe From simon at brunningonline.net Fri Aug 31 11:00:16 2007 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 31 Aug 2007 16:00:16 +0100 Subject: Question involving a Python app... In-Reply-To: <1188571968.529938.55770@i38g2000prf.googlegroups.com> References: <1188571968.529938.55770@i38g2000prf.googlegroups.com> Message-ID: <8c7f10c60708310800o864e28cif5b0bbe0e8e10d41@mail.gmail.com> On 8/31/07, sberry <sean at buildingonline.com> wrote: > So, how do I create an executable (on Windows) > to install the program so it will run without the aforementioned > framework being installed? Check out py2exe. -- Cheers, Simon B. simon at brunningonline.net From stargaming at gmail.com Wed Aug 1 02:10:54 2007 From: stargaming at gmail.com (Stargaming) Date: 01 Aug 2007 06:10:54 GMT Subject: Python end of file marker similar to perl's __END__ References: <1185940391.135261.130950@i38g2000prf.googlegroups.com> <1185947061.985093.306840@22g2000hsm.googlegroups.com> Message-ID: <46b023ee$0$6528$9b622d9e@news.freenet.de> On Wed, 01 Aug 2007 05:44:21 +0000, Michele Simionato wrote: > On Aug 1, 5:53 am, beginner <zyzhu2... at gmail.com> wrote: >> Hi All, >> >> This is just a very simple question about a python trick. >> >> In perl, I can write __END__ in a file and the perl interpreter will >> ignore everything below that line. This is very handy when testing my >> program. Does python have something similar? > > I wished from something like that. What you can do at the moment, is to > comment or triple quote the code you don't want to run. Or, if in a function body, you could insert a `return` statement. When in top-level code, invoking `sys.exit` (or exit/quit) can do the trick. A ``raise Exception`` might help, too, but could be kinda distracting sometimes. So, there is no general purpose solution as perl has it (I guess that __END__ works everywhere at least), rather different solutions for different cases. From cjw at sympatico.ca Thu Aug 16 17:33:43 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 16 Aug 2007 17:33:43 -0400 Subject: sub-classing the types in the builtin module datetime In-Reply-To: <1187294329.082872.230800@l22g2000prc.googlegroups.com> References: <mailman.2043.1187225689.22759.python-list@python.org> <1187294329.082872.230800@l22g2000prc.googlegroups.com> Message-ID: <46C4C2B7.6000701@sympatico.ca> attn.steven.kuo at gmail.com wrote: > On Aug 15, 5:54 pm, "Colin J. Williams" <c... at sympatico.ca> wrote: >> I posted this about 5 hours ago, but it seems to have gone astray. > > > (snipped) > >> > >> >> I wish to sub-class (if that's the right word) datetime and to use a >> >> different signature for the constructor. >> >> >> >> The second part has gone smoothly, but it is difficult to access the >> >> type's methods from the sub-class instance. >> >> >> >> I'm beginning to wonder whether it might might be simpler to write my >> >> own Date class. >> >> >> >> Does anyone have any comments please? >> >> >> >> Colin W. > > (snipped) > > >> Yes, I should have posted an example, but I thought that others might >> have experienced the problem. >> >> It is illustrated at the bottom of this script: >> >> # subClassing.py >> >> import datetime >> import new >> import sys >> import types >> >> class Date(datetime.datetime): >> ''' Date(s) -> a date object.__class__ >> where s is an 8 digit string''' >> >> def __new__(cls, YYmmdd): >> ''' YYmmdd is a string, in the form yyyymmdd i.e. 8 digits. >> or a 3-tuple of integers in the form (y, m, d) >> or a 6-tuple of integers in the form (y, m, d, h, m, >> s) ''' > > > (snipped) > >> a= datetime.datetime(2007, 7, 31) >> d= Date('20070731') >> tm= datetime.time(1, 2) >> try: >> print a.today() >> # print d.today() # grief >> print a.now() >> # print d.now() # grief >> print a.combine(a, tm) # OK, but why not a.combine(tm)? >> # e= d.combine(d, tm) # grief >> print a.utcnow() >> # print d.utcnow() # grief >> print a.ctime() >> print d.ctime() >> except: >> print 'Grief' >> print sys.exc_info() >> >> Colin W. > > > > > > This problem arises when you change the function signature of __new__. > I'm a little unclear as to why but it seems for the classmethods > (thosed marked with the METH_CLASS flag in the C source code), you > need to arrange to bypass the normal method resolution (I used a > metaclass > to do this): > > > > import datetime > > class Date(datetime.datetime): > pass > > class FixClassMethods(type): > def __init__(cls, classname, bases, classdict): > # add strptime if using Python 2.5 > flagged_as_meth_class = ('today', 'now', 'fromtimestamp', > 'fromordinal', 'now', 'utcnow', 'utcfromtimestamp', 'combine') > for meth in flagged_as_meth_class: > setattr(cls, meth, getattr(datetime.datetime, meth)) > > class DateChangesNewSignature(datetime.datetime): > @staticmethod > def str2ymd(strval): > yyyy, mm, dd = (int(substr) for substr in (strval[:4], > strval[4:6], strval[6:])) > return yyyy, mm, dd > > def __new__(cls, strval): > yyyy, mm, dd = DateChangesNewSignature.str2ymd(strval) > return super(DateChangesNewSignature,cls).__new__(cls, yyyy, > mm, > dd) > def __init__(self, strval): > yyyy, mm, dd = DateChangesNewSignature.str2ymd(strval) > super(DateChangesNewSignature, self).__init__(yyyy, mm, > dd) > > class DLast(DateChangesNewSignature): > __metaclass__ = FixClassMethods > > f = Date(2007,07,07) > print f > print f.today() > > f2 = DateChangesNewSignature("20070707") > print f2 > try: > print f2.today() > except TypeError, e: > print str(e) > print "Uh?" > > > f3 = DLast("20070707") > print f3 > print f3.today() > > > I get: > > 2007-07-07 00:00:00 > 2007-08-16 12:57:41.480679 > 2007-07-07 00:00:00 > __new__() takes exactly 2 arguments (9 given) > Uh? > 2007-07-07 00:00:00 > 2007-08-16 12:57:41.483104 > > > -- > Hope this helps, > Steven > Steven, Many thanks, I'll try this out tomorrow. Colin W From pyth0nc0d3r at gmail.com Wed Aug 22 23:12:23 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Wed, 22 Aug 2007 22:12:23 -0500 Subject: How do I get the current path of my python file that is currently running. Message-ID: <eb79828c0708222012o1dec7c82k24c4a4c9015b6df7@mail.gmail.com> Say I start i click on a python file on my desktop, how could I return the path of the current python file thats running? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070822/1064bddb/attachment.html> From jf.pieronne at laposte.net Tue Aug 7 07:37:35 2007 From: jf.pieronne at laposte.net (=?ISO-8859-15?Q?Jean-Fran=E7ois_Pi=E9ronne?=) Date: Tue, 07 Aug 2007 13:37:35 +0200 Subject: seeking tinter module In-Reply-To: <f99jr9$33f$01$1@news.t-online.com> References: <46b849cf$0$21841$426a74cc@news.free.fr> <f99jr9$33f$01$1@news.t-online.com> Message-ID: <46b85980$0$25013$426a74cc@news.free.fr> Peter Otten wrote: > Jean-Fran?ois Pi?ronne wrote: > >> I'm looking for a module name tinter (not tkinter...) >> >> from http://www.vex.net/parnassus/apyllo.py?i=97497223 >> status: Dead and Gone >> >> Google return no location to download it, only a few >> articles mentionned it, for example: >> http://www.ibm.com/developerworks/linux/library/l-python6.html >> >> >> Does someone has still a copy of this module? > > http://www.google.com/codesearch?q=lang%3Apython+file%3Atinter.py&hl=de&btnG=Code+suchen > > gives one hit. > Thanks From penten at gmail.com Tue Aug 28 09:01:07 2007 From: penten at gmail.com (penten at gmail.com) Date: Tue, 28 Aug 2007 13:01:07 -0000 Subject: Embedding the python interpreter In-Reply-To: <1188305107.028128.136960@d55g2000hsg.googlegroups.com> References: <1188305107.028128.136960@d55g2000hsg.googlegroups.com> Message-ID: <1188306067.339505.280210@i13g2000prf.googlegroups.com> On Aug 28, 8:45 pm, Tom Gur <gur.... at gmail.com> wrote: > Hey, > > Do you know an easy way to embed the python interpreter in a python > program (so a non-technical user, which has no idea how to install the > python interpreter would be able to run the script as an executable) ? py2exe does this very well for windows executables: http://www.py2exe.org/ From hhygcy at gmail.com Mon Aug 13 04:59:52 2007 From: hhygcy at gmail.com (Ge Chunyuan) Date: Mon, 13 Aug 2007 08:59:52 -0000 Subject: verify whether "str" is still callable in Python 2.5.1 In-Reply-To: <f9p5sc$oar$01$1@news.t-online.com> References: <1186994287.527549.119170@19g2000hsx.googlegroups.com> <f9p5sc$oar$01$1@news.t-online.com> Message-ID: <1186995592.919369.286560@b79g2000hse.googlegroups.com> On Aug 13, 4:48 pm, Peter Otten <__pete... at web.de> wrote: > Ge Chunyuan wrote: > > Once use ActivePython latest version for Python 2.5.1. > > I happened to find function "str" is not callable, but it is available > > for Python 2.5. > > If it's not callable it's not the str() function, but something else with a > badly chosen variable name. > > >>> callable(str) > True > >>> str = "yadda" > >>> callable(str) > > False > > Peter oh, please forget my silly question. you are absolutely right. From povkra at gmail.com Fri Aug 17 07:21:35 2007 From: povkra at gmail.com (fritz) Date: Fri, 17 Aug 2007 04:21:35 -0700 Subject: Air conditioners for cars! Message-ID: <1187349695.724671.193520@k79g2000hse.googlegroups.com> Have a problem with car air conditioner, go here http://car-air-conditioning.blogspot.com/ From greg at cosc.canterbury.ac.nz Sun Aug 12 20:52:08 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 13 Aug 2007 12:52:08 +1200 Subject: who is simpler? try/except/else or try/except In-Reply-To: <f9ni70$uhr$00$1@news.t-online.com> References: <46bf4074$0$10626$4fafbaef@reader2.news.tin.it> <f9ni70$uhr$00$1@news.t-online.com> Message-ID: <5i9oh1F3oh4roU1@mid.individual.net> Peter Otten wrote: > try: > <operation that may fail> > except <Error I can handle>: > <fix it> > else: > <build on successful operation> > > When you move the else suite into the try...except > > try: > <operation that may fail> > <build on successful operation> # > except <Error I can handle>: > <fix it> Note that in general the semantics of these are different, since in the first version the except clause will only catch exceptions in <operation that may fail>, whereas in the second it may catch exceptions in <build on successful operation> as well. It probably doesn't make a difference in this example, but there are situations where it can. -- Greg From tdwdotnet at gmail.com Thu Aug 23 16:05:46 2007 From: tdwdotnet at gmail.com (Tim Williams) Date: Thu, 23 Aug 2007 21:05:46 +0100 Subject: Using Regular Expresions to change .htm to .php in files In-Reply-To: <B81995429.43.65370.1@mxextra> References: <B81995429.43.65370.1@mxextra> Message-ID: <9afea2ac0708231305v539390dew84926f0b0dcd6974@mail.gmail.com> On 23/08/07, sebzzz at gmail.com <sebzzz at gmail.com> wrote: > Hi, > > I have a bunch of files that have changed from standard htm files to > php files but all the links inside the site are now broken because > they point to the .htm files while they are now .php files. > > Does anyone have an idea about how to do a simple script that changes > each .htm in a given file to a .php > > Thanks a lot in advance > Something like: Infile = open(f_name,'r+') Data = Infile.read() InFile.write(Data.replace('.htm','.php')) Infile.close() :) From robert.kern at gmail.com Fri Aug 31 17:42:12 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 31 Aug 2007 16:42:12 -0500 Subject: Biased random? In-Reply-To: <fb9v07$iij$2@sea.gmane.org> References: <favd0c$fcu$1@ss408.t-com.hr> <mailman.80.1188332647.28954.python-list@python.org> <fb77bq$jtk$1@ss408.t-com.hr> <fb7a3d$phj$1@sea.gmane.org> <fb9bg9$ibi$1@sea.gmane.org> <fb9nc1$s6v$1@sea.gmane.org> <fb9v07$iij$2@sea.gmane.org> Message-ID: <fba1vp$u2f$1@sea.gmane.org> Jeffrey Barish wrote: > I'm sorry that I took the time to respond. I'm sorry. I didn't intend my post to be as harsh as it was. -- 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 rbonvall at gmail.com Thu Aug 9 19:22:14 2007 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Thu, 09 Aug 2007 16:22:14 -0700 Subject: programmatically define a new variable on the fly In-Reply-To: <1186697500.024593.303820@x35g2000prf.googlegroups.com> References: <1186697500.024593.303820@x35g2000prf.googlegroups.com> Message-ID: <1186701734.914467.279620@q3g2000prf.googlegroups.com> On Aug 9, 6:11 pm, Lee Sander <lesa... at gmail.com> wrote: > I would like to define a new variable which is not predefined by me. > For example, > I want to create an array called "X%s" where "%s" is to be determined > based on the data I am processing. Use a dictionary. From nospam at nospam.com Mon Aug 20 11:27:28 2007 From: nospam at nospam.com (Mark T) Date: Mon, 20 Aug 2007 08:27:28 -0700 Subject: Python equivalent of Perl's $/ References: <mailman.9.1187619031.26576.python-list@python.org> Message-ID: <Da6dncv3OJZGL1TbnZ2dnUVZ_sOdnZ2d@comcast.com> "John K Masters" <johnmasters at oxtedonline.net> wrote in message news:mailman.9.1187619031.26576.python-list at python.org... >I am currently working my way through Jeffrey Friedl's book Mastering > Regular Expressions. Great book apart from the fact it uses Perl for the > examples. > > One particular expression that interests me is '$/ = ".\n"' which, > rather than splitting a file into lines, splits on a period-newline > boundary. Combined with Perl's 'while (<>)' construct this seems a great > way to process the files I am interested in. > > Without wishing to start a flame war, is there a way to do this in Python? > > Regards, John > -- > War is God's way of teaching Americans geography > Ambrose Bierce (1842 - 1914) >>> 'test\ntest2.\ntest3\ntest4.\ntest5'.split('.\n') ['test\ntest2', 'test3\ntest4', 'test5'] -Mark T. From programmer.py at gmail.com Thu Aug 30 14:55:27 2007 From: programmer.py at gmail.com (programmer.py at gmail.com) Date: Thu, 30 Aug 2007 18:55:27 -0000 Subject: We need PIGs :) In-Reply-To: <mailman.131.1188450658.28954.python-list@python.org> References: <mailman.131.1188450658.28954.python-list@python.org> Message-ID: <1188500127.398478.95540@x40g2000prg.googlegroups.com> On Aug 30, 12:10 am, "Martin Marcher" <martin.marc... at gmail.com> wrote: [snip!] > > My idea was to define "Python Implementation Guidelines" (PIGs) that > specify a problem formalize it enough so that implementations are > interchangeable (in this example create a module that has an > "authenticate(username, password)" method so that one could easily > take that module for any given app and then authenticate against > postgres, and also against my plaintext file (which was the original - > quite useless - implementation). > > Does that sound like a good idea or would that be over formalization? > This may be over-formalization. For specific problems, there generally is a pythonic choice. For instance, suppose your problem is 'I need an ORM' - well the pythonic choice is something along the lines of SQLObject or SQLAlchemy. Then there are other cases where there are too many choices - "I need a web framework." -- turbogears, django, pylons, and whatever else you want to throw into the pot. (Be smart, choose pylons [just kidding, but I did promote pylons and attach a just kidding disclaimer -- clever, huh?]) > Personally I think that would be great as I could search the PIGs at > (hopefully) python.org find out the number and search at koders.com or > code.google.com for python code that has "PIG: XXX" in the metadata > docstring or wherever - maybe even a __pig__ = XXX variable. > I think most of what you're after may be in the python cookbook (http://aspn.activestate.com/ASPN/Cookbook/Python) or the PyPi (http:// pypi.python.org/pypi). > any input is welcome (also point me to the place where that can be > found if it already exists) > martin Or maybe I completely misunderstand what you mean. G' Day! jw From david at asdf.asdf Mon Aug 27 01:47:25 2007 From: david at asdf.asdf (bambam) Date: Mon, 27 Aug 2007 15:47:25 +1000 Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com> <1187898049.734696.9500@l22g2000prc.googlegroups.com> <13csi2tn49esmc3@corp.supernews.com> <mailman.230.1187928865.32294.python-list@python.org> <13csqk47j0c56b0@corp.supernews.com> <CqSdnRl2x8928FPbnZ2dnUVZ_jSdnZ2d@speakeasy.net> <13ct7v3qn2v5206@corp.supernews.com> <mailman.238.1187948359.32294.python-list@python.org> <13d49lk6ue2as6d@corp.supernews.com> <13d4hutad1dq699@corp.supernews.com> <7xk5rhvcq0.fsf@ruckus.brouhaha.com> Message-ID: <13d4pbce7uqva68@corp.supernews.com> Thank you. I figured the set would probably be faster, but the lists are small, and I'm concerned that the code is going to look Byzantine if I keep swapping between lists, sets and dictionaries :~). At the moment there are no sets or dictionaries in the entire code base I am working with. I'm not sure if the place I am looking at right now is supposed to support duplicates or not: duplicates are permitted, but they cause report anomalies. Steve. "Paul Rubin" <http://phr.cx at NOSPAM.invalid> wrote in message news:7xk5rhvcq0.fsf at ruckus.brouhaha.com... > "bambam" <david at asdf.asdf> writes: >> Is it safe to write >> A = [x for x in A if x in U] >> or is that undefined? I understand that the slice operation >> can be used to make a temporary copy, so I could write >> A=[x for x in A[:] if x in U] >> but I've just copied that without any understanding. > > You get a temporary copy either way; note you're going to linearly > search U on every pass. Maybe you want: > > SU = set(u) > A = [a for x in A if x in SU] > > or possibly > > A = list(set(A) & set(U)) > > which will remove duplicate elements from A and not necessarily keep > them in the same order, but is likely to be fastest of the bunch. From bbxx789_05ss at yahoo.com Sun Aug 12 16:42:06 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 12 Aug 2007 13:42:06 -0700 Subject: wxPython - drawing without paint event In-Reply-To: <5i98bsF3nmbavU1@mid.individual.net> References: <1186710391.148396.113490@d30g2000prg.googlegroups.com> <1186738813.373909.96230@x35g2000prf.googlegroups.com> <1186796567.331348.42450@q3g2000prf.googlegroups.com> <5i5l0dF2lortaU1@mid.individual.net> <1186883988.585048.16590@m37g2000prh.googlegroups.com> <5i8befF3o5no1U1@mid.individual.net> <1186928595.014008.61950@b79g2000hse.googlegroups.com> <5i98bsF3nmbavU1@mid.individual.net> Message-ID: <1186951326.218981.17820@b79g2000hse.googlegroups.com> On Aug 12, 2:20 pm, Bjoern Schliessmann <usenet- mail-0306.20.chr0n... at spamgourmet.com> wrote: > But any suggestions what's > better for a beginner? The (incomplete) tutorial surely not. > Another GUI toolkit. From bj_666 at gmx.net Sat Aug 11 14:56:05 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Aug 2007 18:56:05 GMT Subject: decorators - more than just syntactic sugar References: <46be005e$0$13866$ba620e4c@news.skynet.be> Message-ID: <5i6f25F3ml00gU5@mid.uni-berlin.de> On Sat, 11 Aug 2007 20:30:54 +0200, Helmut Jarausch wrote: > are decorators more than just syntactic sugar in python 2.x and what > about python 3k ? They are just syntactic sugar. @spam def ham(): pass is the same as def ham(): pass ham = spam(ham) > How can I find out the predefined decorators? *The* predefined decorators? Decorators are just functions after all. There are some meant to be used as decorators but there are also "ordinary" functions that may make sense as decorators. Ciao, Marc 'BlackJack' Rintsch From mark.dufour at gmail.com Fri Aug 24 14:46:44 2007 From: mark.dufour at gmail.com (srepmub) Date: Fri, 24 Aug 2007 18:46:44 -0000 Subject: ANN: Compyler 0.1 In-Reply-To: <1187020875.575423.58000@o61g2000hsh.googlegroups.com> References: <mailman.1859.1186862018.22759.python-list@python.org> <46bf2ea3$0$240$e4fe514c@news.xs4all.nl> <1187020875.575423.58000@o61g2000hsh.googlegroups.com> Message-ID: <1187981204.406664.158160@e9g2000prf.googlegroups.com> > + Generates C++ so you need an intermediate compiler (probably only > an issue on windows) Shed Skin comes with a stripped down MingW/G++, so compiling and running/importing compiled code is as easy as 'ss blah.py; make run' or 'ss -e blah.py; python; import blah' under both Windows and Linux (in theory, of course). Mark Dufour (Shed Skin author). From bronger at physik.rwth-aachen.de Fri Aug 24 05:04:33 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 24 Aug 2007 11:04:33 +0200 Subject: Co-developers wanted: document markup language References: <87odgyyx9u.fsf@wilson.homeunix.com> <fakrtb$2ts$1@panix3.panix.com> <87tzqpew22.fsf@wilson.homeunix.com> <fal3cv$bi2$1@panix3.panix.com> <87tzqp77my.fsf@wilson.homeunix.com> <7xy7g1if24.fsf@ruckus.brouhaha.com> Message-ID: <87mywh717i.fsf@wilson.homeunix.com> Hall?chen! Paul Rubin writes: > Torsten Bronger <bronger at physik.rwth-aachen.de> writes: > >> The differences to LaTeX are explained comprehensively on the >> webpage, and actually LaTeX is the real competitor rather than >> reStructuredText. > > TeX/LateX have been around forever and are well established > standards, as awful as they are. Why do we want ANOTHER markup > language? Well, because they are awful. ;-) I don't see that there is a bunch of already existing projects, in fact, I don't see anyone challenging LaTeX at all. However, competition is a good thing, and I think there are enough aspects about LaTeX that can be done better so that this project is worth being done. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From steve at holdenweb.com Mon Aug 27 22:22:47 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 27 Aug 2007 22:22:47 -0400 Subject: Socket - gaierror In-Reply-To: <1188253525.718844.115500@q5g2000prf.googlegroups.com> References: <1188242671.182072.130150@r23g2000prd.googlegroups.com> <OIidnbjzCJVLu07bnZ2dnUVZ_gidnZ2d@comcast.com> <1188244050.029920.314700@i13g2000prf.googlegroups.com> <1188253525.718844.115500@q5g2000prf.googlegroups.com> Message-ID: <fb00tm$vu2$1@sea.gmane.org> half.italian at gmail.com wrote: > On Aug 27, 12:47 pm, half.ital... at gmail.com wrote: >> On Aug 27, 12:32 pm, Larry Bates <larry.ba... at websafe.com> wrote: >> >> >> >>> half.ital... at gmail.com wrote: >>>> Hi all, >>>> I'm having trouble with the socket module resolving a hostname. It >>>> seems like this is a system level problem, but I'm not even sure where >>>> to start. I can ping the smtp server by name and IP, but when >>>> smtp.SMTP("theHost") tries to get the hostname, it keeps giving me the >>>> following error: >>>> File "bin/program.py", line 123, in notify >>>> smtp = smtplib.SMTP("theHost") >>>> File "/usr/lib/python2.4/smtplib.py", line 255, in __init__ >>>> addr = socket.gethostbyname(socket.gethostname()) >>>> gaierror: (-2, 'Name or service not known') >>>> I tried changing to a different smtp server, using an ip instead of a >>>> host name. I could ping both boxes by name oor IP. >>>> any ideas? >>>> ~Sean >>> The specific error shown is a DNS resolution problem. Based on the >>> URL "theHost" smtplib can't resolve to an IP address (which is what >>> socket.gethostbyname does). You don't say what happened when you changed to ip, >>> but I suspect it is a different error or some other problem. Maybe a firewall >>> issue (port 25 not open?), but I'm just guessing. >>> -Larry >> Changing it to IP gives me the same exact error... >> >> File "bin/prgram.py", line 123, in notify >> smtp = smtplib.SMTP("XXX.XXX.XXX.XXX") >> >> File "/usr/lib/python2.4/smtplib.py", line 255, in __init__ >> addr = socket.gethostbyname(socket.gethostname()) >> >> gaierror: (-2, 'Name or service not known') >> >> Looks like the smtp port is closed on the client machine...doh Should >> have gotten to that! >> >> Thank you. >> >> ~Sean > > I take it back, that wasn't the solution. I got it to work by > haacking smtplib with a static host instead of the > socket.gethostbyname(socket.gethostname()) call...but if I leave that > in there I might get shot one day. What could cause the shell to be > able to resolve the addresses properly, but not python? > nnsswitch.conf ? > > I don't know enough about what's going on in the background. Any > other ideas? Or should I try this on a unix board? > Well the first thing to do is call socket.gethostname() and see what it returns, then call socket.gethostbyname() on the result. Once you know what's failing we might be able to help. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From roger.miller at nova-sol.com Fri Aug 10 19:15:51 2007 From: roger.miller at nova-sol.com (Roger Miller) Date: Fri, 10 Aug 2007 16:15:51 -0700 Subject: float to string with different precision In-Reply-To: <1186771026.472118.137090@d30g2000prg.googlegroups.com> References: <1186731617.128913.279360@m37g2000prh.googlegroups.com> <f9h6kj$sj6$00$1@news.t-online.com> <1186771026.472118.137090@d30g2000prg.googlegroups.com> Message-ID: <1186787751.850838.150010@x40g2000prg.googlegroups.com> On Aug 10, 8:37 am, Zentrader <zentrad... at gmail.com> wrote: > > If the above does not work > [/code]test_list = [ 5.32, 10.35634, 289.234 ] > for num in test_list : > str_num = "%11.5f" % (num) ## expand to at least 5 > print str_num, "-->", str_num.strip()[:5][/code] This has the disadvantage that it doesn't round the last digit. For example 10.356634 yields 10.356 instead of 10.357. You can use '*' in format strings to take a numeric field value from a variable. For example ndecimals = 2 print "%5.*f" % (ndecimals, x) formats x with 2 digits following the decimal point. Or you can simply cobble up a format string at run time: format = "%%5.%df" % ndecimals print format % x From rschroev_nospam_ml at fastmail.fm Sun Aug 19 18:46:24 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 19 Aug 2007 22:46:24 GMT Subject: Syntax Question - list multiplication In-Reply-To: <1187560273.146491.90530@r29g2000hsg.googlegroups.com> References: <1187560273.146491.90530@r29g2000hsg.googlegroups.com> Message-ID: <4L3yi.61391$W21.1628190@phobos.telenet-ops.be> Pablo Torres schreef: > Hi guys! > > I am working on Conway's Game of Life right now and I've run into a > little problem. > I represent dead cells with 0s and live ones with 1s. Check this out: > > >>> grid = [[0] * 3] * 3 > >>> grid > [[0, 0, 0], [0, 0, 0], [0, 0, 0]] > >>> grid[0][0] = 1 > [[1, 0, 0], [1, 0, 0], [1, 0, 0]] > > Now, that's not what I want. I just want the first element of the > first sublist to be a 1, not the first of every one. Here's what I > tried and didn't work: > > 0. grid = [[0] * 3][:] * 3 then the same grid[0][0] = 1 statement > 1. grid = [[0][:] * 3] * 3 followed by the same assignment > 2. (grid[0])[0] = 1 with the original initialization of the grid > > So, that means that it isn't a problem with two different variables > refering to the same list (0. and 1. prove that). What I don't > understand is why 2. doesn't work either. I'm baby-feeding my > instructions to Python and the mistake is still there. Any ideas? > > Hope you can help. Thanks in advance, The multiplication operator doesn't make new copies; all elements reference the same object, as you can see with id(): >>> lst = [0] * 3 >>> lst [0, 0, 0] >>> id(lst[0]), id(lst[1]), id(lst[2]) (9788716, 9788716, 9788716) As a consequence, if you modify one element, you change them all (since it's all the same object). Solution: make sure to create independent lists. >>> grid = [[0] * 3 for i in range(3)] >>> grid [[0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> grid[0][0] = 1 -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From ldo at geek-central.gen.new_zealand Sun Aug 12 23:34:30 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 13 Aug 2007 15:34:30 +1200 Subject: question: how to transfer objects between server and client? References: <1186823076.923464.294120@57g2000hsv.googlegroups.com> <46bd7faa$0$239$e4fe514c@news.xs4all.nl> <1186826410.019139.121680@l70g2000hse.googlegroups.com> Message-ID: <f9ojbl$bpi$1@lust.ihug.co.nz> In message <1186826410.019139.121680 at l70g2000hse.googlegroups.com>, OpenPavilion wrote: > just found out, that if I use "pickle.dumps(object)" (on client side) > and "pickle.loads(object)" (on server side) before and after sending, > I have access to the object. That's assuming that the client and server can trust each other. If you can't be sure of that, then this sounds like it could be a security hole. From robert.kern at gmail.com Mon Aug 27 19:02:58 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 27 Aug 2007 18:02:58 -0500 Subject: Biased random? In-Reply-To: <favgh4$1gm3$1@grapevine.csail.mit.edu> References: <favd0c$fcu$1@ss408.t-com.hr> <favgh4$1gm3$1@grapevine.csail.mit.edu> Message-ID: <favl75$98i$1@sea.gmane.org> Jun-geun Park wrote: > Ivan Voras wrote: >> Hi, >> >> I have a list of items, and need to choose several elements from it, >> "almost random". The catch is that the elements from the beginning >> should have more chance of being selected than those at the end (how >> much more? I don't care how the "envelope" of probability looks like at >> this point - can be linear). I see that there are several functions in >> Python standard libraries for various distribution, but is there an easy >> pythonic way to make them do what I need? > > That's weird. random.randint(a,b) will be enough for most cases. Test > your system to see the distribution is uniform with something like: The distribution is uniform. However, he wants a way to get non-uniform sampling of that list. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From david at nospam.spam Mon Aug 13 23:19:35 2007 From: david at nospam.spam (david) Date: Tue, 14 Aug 2007 13:19:35 +1000 Subject: wxPython before MainLoop In-Reply-To: <mailman.1948.1187055857.22759.python-list@python.org> References: <13bl9a75laqcm70@corp.supernews.com> <13bnh5bs4b9h427@corp.supernews.com> <5i3b1jF3n5bdtU1@mid.individual.net> <13c1v79hs0dob3@corp.supernews.com> <mailman.1948.1187055857.22759.python-list@python.org> Message-ID: <13c27q5meq90lb2@corp.supernews.com> Steve, it wasn't me that raised the comparison with MFC. If you don't think that's a helpful comparison, why not reply to that post instead? I don't mind Bj?rn's suggestion that I don't know what I'm talking about, because I started it by telling him he was wrong. But you don't have that excuse. (david) Steve Holden wrote: > [david] wrote: >> Well yes, I have tried this app with native windows, >> and I know how to do it. >> >> But if all wxPython can offer is a poor imitation >> of MFC, I'm better off using MFC aren't I? >> >> And too all those people who wrote back to insist >> that users MUST explicitly build a multi-threaded >> framework for wxPython: >> >> It's supposed to already be a framework :~) >> > The answer is simple. If you don't see any advantage to using wxPython > then don't use it. Personally I believe wxPython is far from a poor > imitation of MFC, but if you are already familiar with MFC then go ahead > and use it. > > regards > Steve From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Aug 30 04:53:09 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 30 Aug 2007 10:53:09 +0200 Subject: Python doesn't see the directories I create In-Reply-To: <ldvBi.293202$LE1.92748@newsfe13.lga> References: <ldvBi.293202$LE1.92748@newsfe13.lga> Message-ID: <46d6856b$0$17674$426a74cc@news.free.fr> mr_gadget a ?crit : > When I create a subfolder, python is not seeing it. Can someone please > explain this behaviour ? I just started with python, read the tutorial over > the weekend and am writing my very first script. So I may not be seeing > something. Both os.path and glob.glob seem not to see a folder I created. > Other sibling folders seem to work fine. On a whim I tried paths with \\ > double slashes and that worked. But why should single slashes work for some > folders and not for others ?? s/slash/antislash/g It's a very well known gotcha due to MS's choice to use the antislash as path separator. In most languages - Python included - the antislash is used for escape sequences (non-printable characters). '\r' is the escape sequence for CR (carriage return). Doubling the antislash prevents escaping. You can avoid all escaping by using raw strings: mypath = r"C:\enhancement\rawfiles\" Also and IIRC, using slash instead should also work, ie: mypath = r"C:/enhancement/rawfiles/" HTH From erik at myemma.com Mon Aug 13 10:49:44 2007 From: erik at myemma.com (Erik Jones) Date: Mon, 13 Aug 2007 09:49:44 -0500 Subject: Database intensive application In-Reply-To: <1186922698.918184.31210@x40g2000prg.googlegroups.com> References: <1186895306.237395.189530@z24g2000prh.googlegroups.com> <1186922698.918184.31210@x40g2000prg.googlegroups.com> Message-ID: <AFFD6229-B995-4356-948F-962F175FDB0C@myemma.com> On Aug 12, 2007, at 7:44 AM, Viewer T. wrote: > and Yes, Python > has awesome database support and can satisfy almost all database > needs. Wow. Nobody ever told me Python was *that* kind of language :) Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From deets at nospam.web.de Mon Aug 20 10:58:55 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 20 Aug 2007 16:58:55 +0200 Subject: Newbee Question In-Reply-To: <mailman.15.1187620149.26576.python-list@python.org> References: <mailman.15.1187620149.26576.python-list@python.org> Message-ID: <5itohrF3qv9t4U1@mid.uni-berlin.de> HD1956 schrieb: > This is probably a simple code. I am a truck driver who gets paid by > stops and cases. I am trying to figure out how to code my stop pay. I > get 40 cents per stop up to 22 stops, and $1.40 per stops after that. > Sounds a bit like homework. Which usually isn't simply delivered here. Can you show us some code you worked on, then we might suggest enhancements. Diez From Graham.Dumpleton at gmail.com Mon Aug 20 18:48:46 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Mon, 20 Aug 2007 22:48:46 -0000 Subject: Overriding Thread.join in derived class. In-Reply-To: <1187552425.752125.302290@a39g2000hsc.googlegroups.com> References: <1187422280.018913.184990@q3g2000prf.googlegroups.com> <1187552425.752125.302290@a39g2000hsc.googlegroups.com> Message-ID: <1187650126.708308.18310@z24g2000prh.googlegroups.com> On Aug 20, 5:40 am, Gabriel Genellina <gagsl-... at yahoo.com.ar> wrote: > On 18 ago, 04:31, Graham Dumpleton <Graham.Dumple... at gmail.com> wrote: > > > > > If one creates a thread using threading.Thread and makes it a daemon > > by calling setDaemon(), then when Python is exiting it will not > > attempt to call join() on that thread and wait for it to complete > > first. [...] > > End result is that it could result in a Python exception at some > > point, evidenced by messages starting with: > > Exception in thread Thread-1 (most likely raised during interpreter > > shutdown) [...] > > > In order to avoid this, do people think that as an alternative to > > creating daemonised thread that it would be reasonable to create a > > derived Thread class for the particular task which overrides > > Thread.join() method to set some flag or otherwise take some action > > that the thread would notice to tell it to stop, and then call base > > class Thread.join(). > > > This way you can flag the thread to shutdown automatically when Python > > is going around calling join() on non daemonised threads. > > > Or am I missing the obvious as far as ways of flagging threads to tell > > them to stop? > > > Note that this is where Python is being used embedded in a C program. > > There is no Python main function where code can be put to signal > > threads to otherwise stop. > > This last statement is important. You need "some" way to tell the > threads to stop working. Usually the thread's run() method is a big > loop; you need to tell it somehow to exit the loop. By example, if you > are using a Queue, put a sentinel object in it; or use an Event > object; or at least a global variable. > Overriding thread.join() as you suggest above may be a good place to > do that, if you don't have another chance. I already use the Queue method to flag the thread to stop. In practice the question is more theoretical at the moment as I am able to stop the thread by registering an atexit callback which stuffs something on the queue and everything works okay. The question was me more thinking out loud and wandering what other peoples opinions were in it. What makes this stuff even more tricky is that prior to Python 2.5, the joining with non daemonised threads was done in a callback registered with the atexit module. This meant it could occur in the middle of other atexit callbacks being called and thus no absolute certainty as to ordering. In Python 2.5, the joining with non daemonised threads was moved to a distinct phase before atexit callbacks were called. This was good for non daemonised threads as it gave you more certainty. Still less for daemonised thread though as although can use atexit callbacks to trigger a thread to shutdown and then wait on it if necessary, still doing stuff when some atexit callbacks may have already been called. Thus why I was hunting for a slightly more predictable method for daemonised threads, although would be dependent on Python 2.5 or later being used if you absolutely need it to occur before atexit callbacks called. Also, just to make it even more complicated, when using Python in an embedded manner and using secondary sub interpreters, destroying a secondary sub interpreter does not result in the atexit callbacks being called, nor joining with non daemonised threads (at least for < 2.5, can't remember for certain about 2.5 but don't think it does it either). Thus, if you need these things to occur for secondary sub interpreters, you must write code yourself to trigger both the thread joining and atexit callbacks. :-( Graham From oliver at obeattie.com Sun Aug 19 13:05:16 2007 From: oliver at obeattie.com (oliver at obeattie.com) Date: Sun, 19 Aug 2007 17:05:16 -0000 Subject: Sorting a list of Unicode strings? In-Reply-To: <46C87772.2010603@web.de> References: <1187542237.139346.6910@o80g2000hse.googlegroups.com> <46C87772.2010603@web.de> Message-ID: <1187543116.941243.200960@r34g2000hsd.googlegroups.com> On Aug 19, 6:01 pm, Stefan Behnel <stefan.behnel-n05... at web.de> wrote: > oli... at obeattie.com wrote: > > Hey Guys, > > ... and girls - maybe ... > > > Maybe I'm missing something fundamental here, but if I have a list of > > Unicode strings, and I want to sort these alphabetically, then it > > places those that begin with unicode characters at the bottom. > > That's because "Unicode" is more than one alphabet. unicode objects compare > based on the Unicode character value, so sort() does alike. > > Stefan Thanks for putting me right -- gals indeed! Anyway, I know _why_ it does this, but I really do need it to sort them correctly based on how humans would look at it. Any ideas? From zentraders at gmail.com Sat Aug 18 21:13:30 2007 From: zentraders at gmail.com (Zentrader) Date: Sat, 18 Aug 2007 18:13:30 -0700 Subject: How to call module functions inside class instance functions? In-Reply-To: <1187484041.838615.259980@e9g2000prf.googlegroups.com> References: <1187484041.838615.259980@e9g2000prf.googlegroups.com> Message-ID: <1187486010.565278.264150@l22g2000prc.googlegroups.com> On Aug 18, 5:40 pm, beginner <zyzhu2... at gmail.com> wrote: > Hi Everyone, > > I have encountered a small problems. How to call module functions > inside class instance functions? For example, calling func1 in func2 > resulted in a compiling error. > > "my module here" > > def func1(): > print "hello" > > class MyClass: > def func2(): > #how can I call func1 here. > func1() #results in an error > > Thanks, > Geoffrey You might want to check one of the online tutorials about how to code classes. Google or look at "Learning Python" here http://www.python-eggs.org/ def func1(): print "hello" class MyClass: def func2(self): #how can I call func1 here. func1() #results in an error MC= MyClass() MC.func2() From rabidpoobear at gmail.com Sat Aug 4 15:25:29 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 04 Aug 2007 14:25:29 -0500 Subject: [pygame] pyweek is happening august 02 - august 09 In-Reply-To: <200708041832.l74IWkRY027388@theraft.openend.se> References: <200708041832.l74IWkRY027388@theraft.openend.se> Message-ID: <46B4D2A9.1010405@gmail.com> Laura Creighton wrote: > 00:00 UTC 2007-09-02 to 00:00 UTC 2007-09-09 exactly. See > www.pyweek.org > > PyconUK is happening. http://www.pyconuk.org/ 8th and 9th September. > > This means that those of us who generally do not see each other but are > going to PyconUK could put together an entry and then sprint together > on it before PyCon UK. There would be this terrible torment -- do > I attend the con or get my game to work -- but it is still the > best chance some of us have to work together yet. > > Talk to me if you are interested in maybe making a PyconUK pygame > team. I think that this could be a lot of fun. Sign up on > www.pyweek.org if you think so, as well. But mail me. > > John -- assuming we want to meet up _before_ PyConUK -- can that > work? Can you point us at a cheap hostel for a few days? > > Laura Creighton > Laura - Pyweek is happening the first week in September, not august. Thanks for giving me a good scare, thinking i missed the first half already! From nick at craig-wood.com Mon Aug 20 11:30:10 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 20 Aug 2007 10:30:10 -0500 Subject: How to decompress .Z file? References: <mailman.1.1187600927.13175.python-list@python.org> Message-ID: <slrnfcjbqd.57s.nick@irishsea.home.craig-wood.com> Hyunchul Kim <sundol at sfc.keio.ac.jp> wrote: > How can .Z file be decompressed? The old unix program compress used to generate these files. http://packages.debian.org/unstable/utils/ncompress You'll find the command line programs gzip/gunzip/zcat can decompress them too. > According to python library reference, .Z file might not be > supported by python, yet. Unfortunately the python gzip library doesn't read .Z files. I'd pipe the data to zcat using subprocess to decompress from python. I haven't used a .Z files for many many years - where are you getting them from? -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From hat at se-162.se.wtb.tue.nl Wed Aug 15 10:08:33 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 15 Aug 2007 16:08:33 +0200 Subject: Retry: Question about FutureWarning References: <mailman.1994.1187142273.22759.python-list@python.org> <ubKdnTirKeU6xl_bnZ2dnUVZ_rzinZ2d@speakeasy.net> <1187183459.675090.194800@w3g2000hsg.googlegroups.com> Message-ID: <slrnfc6271.vuq.hat@se-162.se.wtb.tue.nl> On 2007-08-15, Paul McGuire <ptmcg at austin.rr.com> wrote: > On Aug 14, 8:49 pm, Erik Max Francis <m... at alcyone.com> wrote: > > So if by '0xFFFFFFFF' you meant -1, then change this line to use -1. > Otherwise, if you really meant 4294967295L, leave it at 0xFFFFFFFF and > move on. A third option is to specify 0xFFFFFFFF as 0xFFFFFFFFL in the latter case to get rid of the warning. Albert From seancron at gmail.com Thu Aug 30 15:45:49 2007 From: seancron at gmail.com (seancron) Date: Thu, 30 Aug 2007 19:45:49 -0000 Subject: Python weather application Message-ID: <1188503149.066836.245000@l22g2000prc.googlegroups.com> Does anybody have any suggestions for getting started on desigining a desktop weather application in Python? I've been looking for access to weather data and while I have found several including the weather.com service I've decided to use the Yahoo! Rss Weather feed since it doesn't have a license like the weather.com service does. However one problem I have with it is that it only accepts zip codes or locations ids. So if a user was to enter the name of the city instead of those two there would be an error. I could make it so they could only enter in the location code or zip code but I would really prefer to have it be automatically corrected. Does anyone have ideas on how to go about this or have an other suggestions? Thanks, Sean From fabioztessitore at libero.it Sun Aug 12 13:16:36 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 12 Aug 2007 17:16:36 GMT Subject: who is simpler? try/except/else or try/except Message-ID: <46bf4074$0$10626$4fafbaef@reader2.news.tin.it> Hi all, reading Dive Into Python, on Chapter 6 (exception), I've found: "This code comes from the getpass module, a wrapper module for getting a password from the user" try: import termios, TERMIOS except ImportError: try: import msvcrt except ImportError: try: from EasyDialogs import AskPassword except ImportError: getpass = default_getpass else: getpass = AskPassword else: getpass = win_getpass else: getpass = unix_getpass Knowing that this code is very simple, my question is about simplicity. I think it is simpler the following code. I haven't a long experience on Python, so I'd like to know your opinions about. try: import termios, TERMIOS getpass = unix_getpass except ImportError: try: import msvcrt getpass = win_getpass except ImportError: try: from EasyDialogs import AskPassword getpass = AskPassword except ImportError: getpass = default_getpass thanks, Fabio From dogatemycomputer at gmail.com Mon Aug 20 14:44:12 2007 From: dogatemycomputer at gmail.com (dogatemycomputer at gmail.com) Date: Mon, 20 Aug 2007 18:44:12 -0000 Subject: urllib2.urlopen(url) pulling something other than HTML Message-ID: <1187635452.841155.88720@a39g2000hsc.googlegroups.com> I am reading "Python for Dummies" and found the following example of a web crawler that I thought was interesting. The first time I keyed the program and executed it I didn't understand it well enough to debug it so I just skipped it. A few days later I realized that it failed after a few seconds and I wanted to know if it was a shortcoming of Python, a mistype on my part or just an inherent problem with the script so I retyped it and started trying to figure out what went wrong. Please keep in mind I am very new to coding so I have tried RTFM without much success. I have a basic understanding of what the application is doing but I want to understand WHY it is doing it or what the rationale is for doing it. Not necessarily how it does it.. In any case here is the gist of the app. 1 - a new spider is created 2 - it takes a single argument which is a web address (http:// www.google.com) 3 - the spider pulls a copy of the page source 4 - the spider parses it for links and if the link is on the same domain and has not already been parsed then it appends the link to the list of pages to be parsed Being new I have a couple of questions that I am hoping someone can answer with some degree of detail. ---------------------------------------------------------- f = formatter.AbstractFormatter(formatter.DumbWriter(StringIO())) parser = htmllib.HTMLParser(f) parser.feed(html) parser.close() return parser.anchorlist ---------------------------------------------------------- I get the idea that we're allocating some memory that looks like a file so formatter.dumbwriter can manipulate it. The results are passed to formatter.abstractformatter which does something else to the HTML code. The results are then passed to "f" which is then passed to htmllib.HTMLParser so it can parse the html for links. I guess I don't understand with any great detail as to why this is happening. I know someone is going to say that I should RTFM so here is the gist of the documentation: formatter.DumbWriter = "This class is suitable for reflowing a sequence of paragraphs." formatter.AbstractFormatter = "The standard formatter. This implementation has demonstrated wide applicability to many writers, and may be used directly in most circumstances. It has been used to implement a full-featured World Wide Web browser." <-- huh? So.. What is dumbwriter and abstractformatter doing with this HTML and why does it need to be done before parser.feed() gets a hold of it? The last question is.. I can't find any documentation to explain where the "anchorlist" attribute came from? Here is the only reference to this attribute that I can find anywhere in the Python documentation. ---------------------- anchor_bgn( href, name, type) This method is called at the start of an anchor region. The arguments correspond to the attributes of the <A> tag with the same names. The default implementation maintains a list of hyperlinks (defined by the HREF attribute for <A> tags) within the document. The list of hyperlinks is available as the data attribute anchorlist. ---------------------- So .. How does an average developer figure out that parser returns a list of hyperlinks in an attribute called anchorlist? Is this something that you just "figure out" or is there some book I should be reading that documents all of the attributes for a particular method? It just seems a bit obscure and certainly not something I would have figured out on my own. Does this make me a poor developer who should find another hobby? I just need to know if there is something wrong with me or if this is a reasonable question to ask. The last question I have is about debugging. The spider is capable of parsing links until it reaches: "html = get_page(http://www.google.com/jobs/fortune)" which returns the contents of a pdf document, assigns the pdf contents to html which is later passed to parser.feed(html) which crashes. I'm smart enough to know that whenever you take in some input that you should do some basic type checking to make sure that whatever you are trying to manipulate (especially if it originates from outside of your application) won't cause your application to crash. If you're expecting an ASCII character then make sure you're not getting an object or string of text. How would an experienced python developer check the contents of "html" to make sure its not something else other than a blob of HTML code? I should note an obviously catch-22.. How do I check the HTML in such a way that the check itself doesn't possibly crash the app? I thought about: try: parser.feed(html) except parser.HTMLParseError: parser.close() .... but i'm not sure if that is right or not? The app still crashes so obviously i'm doing something wrong. Here is the full app for your review. Thank you for any help you can provide! I greatly appreciate it! #!/usr/bin/python #these modules do most of the work import sys import urllib2 import urlparse import htmllib, formatter from cStringIO import StringIO def log_stdout(msg): """Print msg to the screen.""" print msg def get_page(url, log): """Retrieve URL and return comments, log errors.""" try: page = urllib2.urlopen(url) except urllib2.URLError: log("Error retrieving: " + url) return '' body = page.read() page.close() return body def find_links(html): """return a list of links in HTML""" #We're using the parser just to get the hrefs f = formatter.AbstractFormatter(formatter.DumbWriter(StringIO())) parser = htmllib.HTMLParser(f) parser.feed(html) parser.close() return parser.anchorlist class Spider: """ The heart of this program, finds all links within a web site. run() contains the main loop. process_page() retrieves each page and finds the links. """ def __init__(self, startURL, log=None): #this method sets initial values self.URLs = set() #create a set self.URLs.add(startURL) #add the start url to the set self.include = startURL self._links_to_process = [startURL] if log is None: #use log_stdout function if no log provided self.log = log_stdout else: self.log = log def run(self): #process list of URLs one at a time while self._links_to_process: url = self._links_to_process.pop() self.log("Retrieving: " + url) self.process_page(url) def url_in_site(self, link): #checks weather the link starts with the base URL return link.startswith(self.include) def process_page(self, url): #retrieves page and finds links in it html = get_page(url, self.log) for link in find_links(html): #handle relative links link = urlparse.urljoin(url,link) self.log("Checking: " + link) #make sure this is a new URL within current site if link not in self.URLs and self.url_in_site(link): self.URLs.add(link) self._links_to_process.append(link) if __name__ == '__main__': #this code runs when script is started from command line startURL = sys.argv[1] spider = Spider(startURL) spider.run() for URL in sorted(spider.URLs): print URL From gherron at islandtraining.com Thu Aug 16 12:05:48 2007 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 16 Aug 2007 09:05:48 -0700 Subject: A problem with Time In-Reply-To: <46c469be$0$66145$7b0f0fd3@mistral.news.newnet.co.uk> References: <46c469be$0$66145$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <46C475DC.2@islandtraining.com> special_dragonfly wrote: > Hello, > > I need to return the date yesterday in the form DDMMYYYY. I looked through > the modules: time, datetime and calendar but can't find anything that leaps > out at me. > > The problem I'm having is that although I can use time.localtime and get a > tuple of the year, month, day and so forth, I don't believe I can just minus > 1 from the day, because I don't think it's cyclic, also, I can't see the > date being linked in with the month. > > So is there any way of getting yesterdays date? > > Thank You > > Dominic > > > Here's how I'd do it: >>> import time >>> secondsPerDay = 24*60*60 >>> today = time.time() >>> yesterday = today - secondsPerDay >>> print time.strftime("%d%m%Y",time.localtime(today)) 16082007 >>> print time.strftime("%d%m%Y",time.localtime(yesterday)) 15082007 Gary Herron From fabioztessitore at libero.it Sun Aug 12 14:01:22 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 12 Aug 2007 18:01:22 GMT Subject: who is simpler? try/except/else or try/except References: <46bf4074$0$10626$4fafbaef@reader2.news.tin.it> <mailman.1879.1186940975.22759.python-list@python.org> Message-ID: <46bf4af2$0$10626$4fafbaef@reader2.news.tin.it> Il Sun, 12 Aug 2007 13:49:18 -0400, Steve Holden ha scritto: >> > In matters of style such as this there *are* only opinions. I don't > think there are definite grounds for preferring either one. Opinions are what I'd like to see, because most of you have bigger experience than me. maybe this example is too trivial for that ... ;-) > If you were to propose such a patch on the python-dev list, Oh no, I didn't think that thanks, bye Fabio From bjourne at gmail.com Mon Aug 13 07:10:28 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 13 Aug 2007 13:10:28 +0200 Subject: decorators - more than just syntactic sugar In-Reply-To: <46be005e$0$13866$ba620e4c@news.skynet.be> References: <46be005e$0$13866$ba620e4c@news.skynet.be> Message-ID: <740c3aec0708130410h72f057ffy70db3cc447aa36e@mail.gmail.com> On 8/11/07, Helmut Jarausch <jarausch at skynet.be> wrote: > How can I find out the predefined decorators? There are two in the standard library, @classmethod for declaring class methods and @staticmethod for declaring static methods. They are listed at the built ins page http://docs.python.org/dev/lib/built-in-funcs.html, unpedagogically not separated from ordinary functions. -- mvh Bj?rn From bignose+hates-spam at benfinney.id.au Wed Aug 8 06:57:58 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 08 Aug 2007 20:57:58 +1000 Subject: Seek the one billionth line in a file containing 3 billion lines. References: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> <7xzm12o7o7.fsf@ruckus.brouhaha.com> <1186555297.877273.40540@o61g2000hsh.googlegroups.com> Message-ID: <874pja70p5.fsf@benfinney.id.au> Sullivan WxPyQtKinter <sullivanz.pku at gmail.com> writes: > On Aug 8, 2:35 am, Paul Rubin <http://phr... at NOSPAM.invalid> wrote: > > Sullivan WxPyQtKinter <sullivanz.... at gmail.com> writes: > > > This program: > > > for i in range(1000000000): > > > f.readline() > > > is absolutely every slow.... > > > > There are two problems: > > > > 1) range(1000000000) builds a list of a billion elements in memory [...] > > > > 2) f.readline() reads an entire line of input [...] > > Thank you for pointing out these two problem. I wrote this program > just to say that how inefficient it is to use a seemingly NATIVE way > to seek a such a big file. No other intention........ The native way isn't iterating over 'range(hugenum)', it's to use an iterator. Python file objects are iterable, only reading eaach line as needed and not creating a companion list. logfile = open("foo.log", 'r') for line in logfile: do_stuff(line) This at least avoids the 'range' issue. To know when we've reached a particular line, use 'enumerate' to number each item as it comes out of the iterator. logfile = open("foo.log", 'r') target_line_num = 10**9 for (line_num, line) in enumerate(file): if line_num < target_line_num: continue else: do_stuff(line) break As for reading each line: that's unavoidable if you want a specific line from a stream of variable-length lines. -- \ "I have never made but one prayer to God, a very short one: 'O | `\ Lord, make my enemies ridiculous!' And God granted it." -- | _o__) Voltaire | Ben Finney From nick at craig-wood.com Mon Aug 20 11:30:10 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 20 Aug 2007 10:30:10 -0500 Subject: Python equivalent of Perl's $/ References: <mailman.9.1187619031.26576.python-list@python.org> Message-ID: <slrnfcjcqq.557.nick@irishsea.home.craig-wood.com> John K Masters <johnmasters at oxtedonline.net> wrote: > I am currently working my way through Jeffrey Friedl's book Mastering > Regular Expressions. Great book apart from the fact it uses Perl for the > examples. > > One particular expression that interests me is '$/ = ".\n"' which, > rather than splitting a file into lines, splits on a period-newline > boundary. Combined with Perl's 'while (<>)' construct this seems a great > way to process the files I am interested in. > > Without wishing to start a flame war, is there a way to do this in Python? > > Regards, John Something like this maybe? import re input_data = """I am currently working my way through Jeffrey Friedl's book Mastering Regular Expressions. Great book apart from the fact it uses Perl for the examples. One particular expression that interests me is '$/ = ".\\n"' which, rather than splitting a file into lines, splits on a period-newline boundary. Combined with Perl's 'while (<>)' construct this seems a great way to process the files I am interested in. Without wishing to start a flame war, is there a way to do this in Python? """ for para in re.split(r"\.\n", input_data): print "para = %r" % para -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From claird at lairds.us Fri Aug 3 09:48:10 2007 From: claird at lairds.us (Cameron Laird) Date: Fri, 3 Aug 2007 13:48:10 +0000 Subject: Best way to capture output from an exec'ed (or such) script? References: <1186084086.212050.264270@q3g2000prf.googlegroups.com> <mailman.1547.1186097565.22759.python-list@python.org> Message-ID: <q9obo4-v3b.ln1@lairds.us> In article <mailman.1547.1186097565.22759.python-list at python.org>, Gabriel Genellina <gagsl-py2 at yahoo.com.ar> wrote: >En Thu, 02 Aug 2007 16:48:06 -0300, <exscape at gmail.com> escribi?: > >> In any case. I've added some minor scripting support, so that you can >> write dynamic pages in Python. To do this, I use execfile(), and pass >> the script a dictionary with some basic variables. The script then >> sets a "ret" variable that's sent back to the browser. That's some >> major ugliness right there! If I do a "print" inside the script, then >> it'll end up on the server console. I want it to end up in the web >> browser. > >If `print` were a function, this would be easy: just provide a replacement >into the dictionary you pass to the script. But print is a statement, and >this becomes a bit harder. > >If your web server only processes a single request at a time, you can >replace sys.stdout (and perhaps sys.stderr) with a suitable object having >a write() function: a true open file, or a StringIO instance, or even a >custom object that collects "printed" lines into a list. > >If your web server is multithreaded (or you use some other way to process >many simultaneous requests) you have to be more careful - remember that >sys.stdout is global, you must find a way to distinguish between output > from different processes all going into the same collector. . . . While we're on the subject of Web servers so small as to be educational, I'll recommend <URL: http://www.ibm.com/developerworks/web/library/wa-ltwebserv/ >. From iapain at gmail.com Mon Aug 27 13:21:07 2007 From: iapain at gmail.com (iapain) Date: Mon, 27 Aug 2007 17:21:07 -0000 Subject: sorting a list of lists In-Reply-To: <1188233798.684136.263640@22g2000hsm.googlegroups.com> References: <1188233798.684136.263640@22g2000hsm.googlegroups.com> Message-ID: <1188235267.790442.193830@q5g2000prf.googlegroups.com> > i would like to sort a list of lists. The list is first sorted on the > second item in the sub-lists (which I can do), then on the third item > (which I can't). Write a comparator instead of dirty hacks mylistoflist.sort(mycomparator) def mycomparator(a, b): #do From zentraders at gmail.com Mon Aug 6 15:48:31 2007 From: zentraders at gmail.com (Zentrader) Date: Mon, 06 Aug 2007 12:48:31 -0700 Subject: is it possible to improve traceback messages ? In-Reply-To: <mailman.1686.1186422892.22759.python-list@python.org> References: <46B75F9E.5020309@mailbox.kun.nl> <mailman.1686.1186422892.22759.python-list@python.org> Message-ID: <1186429711.511166.140780@i38g2000prf.googlegroups.com> On Aug 6, 10:54 am, "Chris Mellon" <arka... at gmail.com> wrote: > On 8/6/07, Stef Mientki <S.Mientki-nos... at mailbox.kun.nl> wrote: > > > > > hello, > > > Most of time I get an error message, it is sufficient to solve to problem. > > Sometimes it's not clear to me what the problem is > > like this one: > > > N = int (log10(self.Value)) + 1 > > TypeError: int() argument must be a string or a number > > > In order to solve it, in general I put some print statements, > > before the line with the problem, > > printing values and types of all variables. > > > I think it would be much more convenient, > > if the traceback or error exception ( don't know how it works exactly), > > would print the type and value of all variables and constants used in the last line. > > > Can this be done (in a easy way). > > See the cgitb module. This is the "standard" way AFAIK .try : . some_process .except : . import trackback, sys . et, ev, tb = sys.exc_info() . while tb : . co = tb.tb_frame.f_code . print "Filename = " + str(co.co_filename) . print "Error Line # = " + str(traceback.tb_lineno(tb)) . tb = tb.tb_next . print "error type = ", et . print "error var name = ", ev From S.Mientki-nospam at mailbox.kun.nl Thu Aug 2 17:47:49 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 02 Aug 2007 23:47:49 +0200 Subject: (no) fast boolean evaluation ? Message-ID: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> hello, I discovered that boolean evaluation in Python is done "fast" (as soon as the condition is ok, the rest of the expression is ignored). Is this standard behavior or is there a compiler switch to turn it on/off ? thanks, Stef Mientki From ArarghMail708NOSPAM at NOT.AT.Arargh.com Thu Aug 30 17:26:19 2007 From: ArarghMail708NOSPAM at NOT.AT.Arargh.com (ArarghMail708NOSPAM at NOT.AT.Arargh.com) Date: Thu, 30 Aug 2007 16:26:19 -0500 Subject: Important Research Project References: <13ddcvm1bsu3s94@corp.supernews.com> <46D6CA0E.E66ED5C8@yahoo.com> Message-ID: <0dded397gquvo23fjvjfta1131evcb4or0@4ax.com> On Thu, 30 Aug 2007 09:45:50 -0400, CBFalconer <cbfalconer at yahoo.com> wrote: >"E.D.G." wrote: >> >> This report is being posted to a number of Internet Newsgroups to >> see if there are any experienced computer programmers who would >> like to provide some assistance with an effort to develop a Perl >> language computer program. > >Where is Perl described in the C standard? This seems rather OT. > A little OT for basic groups, too. Followups set. Fortran group dropped, too. -- ArarghMail708 at [drop the 'http://www.' from ->] http://www.arargh.com BCET Basic Compiler Page: http://www.arargh.com/basic/index.html To reply by email, remove the extra stuff from the reply address. From google at mrabarnett.plus.com Thu Aug 9 20:39:23 2007 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 09 Aug 2007 17:39:23 -0700 Subject: Threaded Design Question In-Reply-To: <1186683909.797328.68770@i13g2000prf.googlegroups.com> References: <1186683909.797328.68770@i13g2000prf.googlegroups.com> Message-ID: <1186706363.947909.185460@e9g2000prf.googlegroups.com> On Aug 9, 7:25 pm, half.ital... at gmail.com wrote: > Hi all! I'm implementing one of my first multithreaded apps, and have > gotten to a point where I think I'm going off track from a standard > idiom. Wondering if anyone can point me in the right direction. > > The script will run as a daemon and watch a given directory for new > files. Once it determines that a file has finished moving into the > watch folder, it will kick off a process on one of the files. Several > of these could be running at any given time up to a max number of > threads. > > Here's how I have it designed so far. The main thread starts a > Watch(threading.Thread) class that loops and searches a directory for > files. It has been passed a Queue.Queue() object (watch_queue), and > as it finds new files in the watch folder, it adds the file name to > the queue. > > The main thread then grabs an item off the watch_queue, and kicks off > processing on that file using another class Worker(threading.thread). > > My problem is with communicating between the threads as to which files > are currently processing, or are already present in the watch_queue so > that the Watch thread does not continuously add unneeded files to the > watch_queue to be processed. For example...Watch() finds a file to be > processed and adds it to the queue. The main thread sees the file on > the queue and pops it off and begins processing. Now the file has > been removed from the watch_queue, and Watch() thread has no way of > knowing that the other Worker() thread is processing it, and shouldn't > pick it up again. So it will see the file as new and add it to the > queue again. PS.. The file is deleted from the watch folder after it > has finished processing, so that's how i'll know which files to > process in the long term. > I would suggest something like the following in the watch thread: seen_files = {} while True: # look for new files for name in os.listdir(folder): if name not in seen_files: process_queue.add(name) seen_files[name] = True # forget any missing files and mark the others as not seen, ready for next time seen_files = dict((name, False) for name, seen in seen_files.items() if seen) time.sleep(1) From i3dmaster at gmail.com Tue Aug 14 12:42:52 2007 From: i3dmaster at gmail.com (i3dmaster) Date: Tue, 14 Aug 2007 09:42:52 -0700 Subject: Simple python iteration question In-Reply-To: <1187108787.998690.37500@q3g2000prf.googlegroups.com> References: <bFkwi.675$Oo.563@newssvr17.news.prodigy.net> <1187108787.998690.37500@q3g2000prf.googlegroups.com> Message-ID: <9DBE382C-73FD-4EEC-88CA-AA7B7983ADC7@gmail.com> or use its builtin enumerate function: for i, j in enumerate(list): print i, j --Jim On Aug 14, 2007, at 9:26 AM, danmcleran at yahoo.com wrote: > On Aug 14, 10:22 am, Bryan <b... at bcc.com> wrote: >> Hi, >> >> I just started with python, and have a for loop question >> >> In c++ (or a number of other languages) I can do this: >> >> for (int i=0, j=0; i < i_len, j< j_len; ++i, ++j) {} >> >> If I have this in python: >> l = ['a', 'b', 'c'] >> >> I want to get the value and also an iterator: >> for i,v in len(l), l: >> print v >> print i >> >> Or something like this without declaring the iterator outside my >> loop... >> >> How do I do this? >> Thanks! > > this will get index and item at index, > > for i in range(0, len(l)): > print i > print l[i] > > > -- > http://mail.python.org/mailman/listinfo/python-list From ptmcg at austin.rr.com Wed Aug 1 23:43:12 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 01 Aug 2007 20:43:12 -0700 Subject: Extending Python by Adding Keywords & Data types In-Reply-To: <1185973687.883520.227540@k79g2000hse.googlegroups.com> References: <1185913739.879602.212950@w3g2000hsg.googlegroups.com> <1185973687.883520.227540@k79g2000hse.googlegroups.com> Message-ID: <1186026192.659767.306960@d55g2000hsg.googlegroups.com> On Aug 1, 8:08 am, Paul McGuire <pt... at austin.rr.com> wrote: > > def add(self,other): > if len(self.contents) < self.capacity: > self.contents.append( other ) > else: > raise ValueError("can't add any more to this Box") > I guess that really should raise an OverflowError... -- Paul From ptmcg at austin.rr.com Thu Aug 16 22:01:53 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 16 Aug 2007 19:01:53 -0700 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: <1187314114.873306.187500@e9g2000prf.googlegroups.com> References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> <1187314114.873306.187500@e9g2000prf.googlegroups.com> Message-ID: <1187316113.424465.34650@19g2000hsx.googlegroups.com> On Aug 16, 8:28 pm, Jonathan Gardner <jgardner.jonathangardner.... at gmail.com> wrote: > On Aug 16, 3:35 pm, beginner <zyzhu2... at gmail.com> wrote: > > > > > In perl it is just one line: $a=$b->{"A"} ||={}. > > a = b.setdefault('A', {}) > > This combines all two actions together: > - Sets b['A'] to {} if it is not already defined > - Assigns b['A'] to a > > More info on dict methods here: > > http://docs.python.org/lib/typesmapping.html No, this has already been proposed and discarded. The OP does NOT want this, because it always generates an empty {} whether it is needed or not. Not really a big hardship, but if the default value were some expensive-to-construct container class, then you would be creating one every time you wanted to reference a value, on the chance that the key did not exist. Carl Banks' post using defaultdict is the correct solution. The raison d'etre for defaultdict, and the reason that it is the solution to the OP's question, is that instead of creating a just-in-case default value every time, the defaultdict itself is constructed with a factory method of some kind (in practice, it appears that this factory method is usually the list or dict class constructor). If a reference to the defaultdict gives a not-yet-existing key, then the factory method is called to construct the new value, that value is stored in the dict with the given key, and the value is passed back to the caller. No instances are created unless they are truly required for initializing an entry for a never-before-seen key. -- Paul From bjourne at gmail.com Wed Aug 29 06:32:21 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 29 Aug 2007 12:32:21 +0200 Subject: advice about `correct' use of decorator In-Reply-To: <op.txjpo7ixx6zn5v@gabriel2.softlabbsas.com.ar> References: <46C4B097.4080309@fmed.uba.ar> <740c3aec0708170529s6f7e7fe2l8c92771c2d0a51d4@mail.gmail.com> <46C5C9AE.5020508@fmed.uba.ar> <mailman.112.1187787625.32294.python-list@python.org> <1187792001.935204.42330@e9g2000prf.googlegroups.com> <740c3aec0708230520h6a92a29ar180efed41730f563@mail.gmail.com> <op.txjpo7ixx6zn5v@gabriel2.softlabbsas.com.ar> Message-ID: <740c3aec0708290332k3c125d9el16250939e22ea8c4@mail.gmail.com> On 8/24/07, Gabriel Genellina <gagsl-py2 at yahoo.com.ar> wrote: > En Thu, 23 Aug 2007 09:20:21 -0300, BJ?rn Lindqvist <bjourne at gmail.com> > escribi?: > > > def check_user_logged_in(func): > > def f(*args, **kwargs): > > if global_state.the_user.is_logged_in: > > return func(*args, **kwargs) > > return show_login_page() > > return f > > I think there is a semantic problem, perhaps we are not talking > about the same thing. I'm considering the software complexity AS > PERCEIVED BY THE PROGRAMMER, looking at the interactions between a > program and a programmer who is working on some task; some people > would say "cognitive complexity" to make it clear. There is no semantic problem. You are just mistaken in your belief that the complexity that the user of the decorator has to deal with is different from the complexity in implementing the decorator. > Which API is more complex: one in which you can play a movie with > just a single call like PlayMovie(Title), or one on which you must > call a zillion functions to firtly initialize the stream format, > configure the display, disable undesired user interfase elements, > locate the movie file, load it in chunks, etc.? The first one is > certainly much simpler to use (simpler = less complex), and maybe > internally it calls the same functions as the second one, but nobody > cares. "nobody cares" is your guess. I'd bet that the caller of the PlayMovie function cares a lot: Is the movie played full screened? Which encodings are supported? Can you set the title of the movie window? Is streaming supported? Does it even work on windows? Which URI schemes does it support? And so on and so on. That is why no video decoding API:s have a PlayMovie(Title) function and why I haven't seen a single 3d engine with a MakeReallyCoolDoomCloneFPSGame() function. "hiding details" only works if the client programmer really doesn't care about the details. > Back to your example, the fact that a decorator builds a higher order > function, does NOT make it more complex - because the programmer does not > see that. In fact, hiding the details makes it simpler. Yes, the programmer does see that. The example decorator I posted requires about a zillion preconditions to work correctly and will fail in weird ways when those preconditions are not satisfied. The programmer is interested in the crazy failures he or she will experience. I dare you to try and implementing the code both as a decorator and as a function, then write the unit tests and documentation. The complexity of those three items together (implementation + tests + documentation) will be much higher for the decorator choice because the complexity of the decorator implementation is a bit higher than using a plain old function. Note also that it is extremely rare to see well-documented or well-tested code, which means that the programmer WILL have to analyze the implementation which means that implementation complexity matters a lot. -- mvh Bj?rn From steveo at syslang.net Tue Aug 14 21:44:17 2007 From: steveo at syslang.net (Steven W. Orr) Date: Tue, 14 Aug 2007 21:44:17 -0400 (EDT) Subject: Retry: Question about FutureWarning Message-ID: <alpine.LFD.0.999.0708142137550.22214@saturn.syslang.net> I'm trying again, since no response indicates that I'm not providing enough info. I have module M1 which has the following line in it: StartTime = safe_dict_get ( dic, 'starttime', 0xFFFFFFFF ) It gets imported by modules M2 and M3. And finally, M4 imports both M2 and M3. So the idea is that in total we have 4 files called M1.py M2.py M3.py and M4.py M4 |\M3 | |\M1 |\M2 | |\M1 I need to compile the python modules as part of the package building process. The shell compile command I use to generate both the .pyc and the .pyo files is: python=/usr/bin/python2.3 i_python () { $python -c "import $1" $python -O -c "import $1" } i_python M1 i_python M2 i_python M3 i_python M4 When M1 is compiled, there's no problem. The same for when I compile M2 and M3. But when M4 is compiled, I get the following message: M1.py:268: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up StartTime = safe_dict_get ( dic, 'starttime', 0xFFFFFFFF ) I get the message twice, ostensibly because of M3 and M2 both being imported into M1 I was able to shut off the warning by adding the following lines *before* the import of M2 and M3 in M4: import warnings warnings.filterwarnings('ignore', category=FutureWarning) My question is this: Why can the warning not be shut off by putting the two lines in M1 where the reference exists to 0xFFFFFFFF ? I'm just leary of fixing warnings by looking for ways to shut them off. Also, do I need to supply any more information? Thanks for your patience. -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From robert.kern at gmail.com Sun Aug 12 19:02:04 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 12 Aug 2007 18:02:04 -0500 Subject: Python not freeing memory (?) In-Reply-To: <loom.20070812T224243-317@post.gmane.org> References: <loom.20070812T224243-317@post.gmane.org> Message-ID: <f9o3hn$td$1@sea.gmane.org> Chris wrote: > I have a Bayesian simulation package that keeps running into memory > allocation problems. I have a feeling this has something to do with > Python (2.5.1.1) not freeing memory. The program essentially > iterates n times, each time proposing new arrays (numpy) of values > that are evaluated using statistical likelihoods. All variables in > the loop are re-assigned at each iteration, so there should not be > a leak. Nevertheless, at approximately the same iteration every > time, I run into malloc errors: There might be a bug in numpy. It's unlikely that the bug is in Python. Let's bring it over to numpy-discussion. What version of numpy are you using? Can you give us a complete example that demonstrates the leak? -- 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 andmart at gmail.com Fri Aug 3 08:37:05 2007 From: andmart at gmail.com (=?ISO-8859-1?Q?Andr=E9_Martins?=) Date: Fri, 3 Aug 2007 09:37:05 -0300 Subject: How to create python script which can create csv we file with relationship In-Reply-To: <1186141530.243539.6370@q75g2000hsh.googlegroups.com> References: <1186141530.243539.6370@q75g2000hsh.googlegroups.com> Message-ID: <bfc796de0708030537l67cc4a2clf866bba5dc60dd1c@mail.gmail.com> http://docs.python.org/lib/module-csv.html 2007/8/3, Sonu <patelkundan at gmail.com>: > > hello, > i need to create script > that can create a csv file as i want > for example i have two table in database that are person ,country > if i want to create csv file to person,then wht to do ,, > how to connect database,how to create csv of interrelated field > eg :in person table :country_id (which is primary key of country table) > > -- > http://mail.python.org/mailman/listinfo/python-list > -- []'s Andr? Martins -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070803/620d7abe/attachment.html> From jgodoy at gmail.com Sun Aug 12 16:42:52 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 12 Aug 2007 17:42:52 -0300 Subject: Web based Reporting tool for Python References: <1186460956.945148.162610@k79g2000hse.googlegroups.com> <mailman.1722.1186522221.22759.python-list@python.org> <1186547726.383996.291360@d55g2000hsg.googlegroups.com> <2007080808575016807-jon@turnthepageorg> <1186891194.582444.222010@r34g2000hsd.googlegroups.com> <mailman.1871.1186916944.22759.python-list@python.org> <2007081212120450073-jon@turnthepageorg> Message-ID: <iv74p4-b2f.ln1@strongwill.g2ctech> Jon Rosebaugh wrote: > Sure, but again, these aren't reporting engines; they're just template > engines. And I don't think any of the web template engines have PDF > output. I generate my PDFs with Genshi / Kid and ReportLab. For the markup processing I use z3c.rml. Works flawlessly. From zzbbaadd at aol.com Thu Aug 30 15:24:25 2007 From: zzbbaadd at aol.com (zzbbaadd at aol.com) Date: Thu, 30 Aug 2007 12:24:25 -0700 Subject: subclassing Python types In-Reply-To: <46d717f5$0$30367$9b4e6d93@newsspool4.arcor-online.net> References: <1188500442.434722.157350@q5g2000prf.googlegroups.com> <46d717f5$0$30367$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <1188501865.541186.272290@e9g2000prf.googlegroups.com> On Aug 30, 12:18 pm, Wildemar Wildenburger <lasses_w... at klapptsowieso.net> wrote: > zzbba... at aol.com wrote: > > I have read that you can derive from the base classes such as str, > > list, dict. > > > I guess this would look like: > > > def MyString(str): > > def MyList(list): > > def MyDict(dict): > > Well, replace 'def' with 'class' and you're right. > > > How do you access the data that is contained in the super class? > > This way: > >>> class MyList(list): > ... def do_something(self): > ... self.append(3) > ... print self > ... > >>> l = MyList((1, 2)) > >>> l > [1, 2] > >>> l.do_something() > [1, 2, 3] > > That is: Whenever you want to refer to the value refer to self (that is, > refer to the instance of your class). > > /W Ok, thanks. So it's: class MyString(str): def __init__(self,strInput): self = strInput From rdm at rcblue.com Sun Aug 12 21:28:29 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 12 Aug 2007 18:28:29 -0700 Subject: Binary, Hex, and Decimal string conversions In-Reply-To: <496954360708121620r4dd68ac9o430326ae8c8ae04d@mail.gmail.co m> References: <496954360708111559s1cef4212pabd14e95b27435ea@mail.gmail.com> <C5FFAC23-F5DC-4112-A508-EC9BDF2FAB43@jedimindworks.com> <496954360708121620r4dd68ac9o430326ae8c8ae04d@mail.gmail.com> Message-ID: <20070813013344.2A7A41E4013@bag.python.org> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070812/94edc1df/attachment.html> From tjollans at googlemail.com Wed Aug 15 04:40:26 2007 From: tjollans at googlemail.com (stef mientki) Date: Wed, 15 Aug 2007 10:40:26 +0200 Subject: buggie in else syntax ? In-Reply-To: <200708150138.57816.thomas@jollans.com> References: <46C21D70.8000409@gmail.com> <200708150138.57816.thomas@jollans.com> Message-ID: <46C2BBFA.7040001@gmail.com> Thomas Jollans wrote: > On Tuesday 14 August 2007, stef mientki wrote: > >> hello, >> >> I've the idea that the "else" syntax is not always handled correctly, >> or I'm overlooking something. >> >> This pieces of code are automatic translation from another language, >> sometimes it works, sometimes it doesn't ??? >> >> This piece of code works nice: >> >> a = 2 >> >> def JSM (line_nr): >> print line_nr >> >> if a>3: >> print 'asddas' >> else: JSM(230) ; \ <== this is the problem line, that's ok here >> print 'aaps' >> >> While this piece of code gives a syntax error: >> >> #Function button_antidender(bit in pin,sbyte in out >> Button_Counter_Temp,byte in demp) return bit is >> def button_antidender ( pin, button_counter_temp, demp ): >> #serial_hw_write(counter) >> Serial_HW_Write ( button_counter_temp ) ;JSM(226) >> if JSM(227) and ( button_counter_temp >= 0 ): >> if JSM(228) and ( pin == on ): >> button_counter_temp = button_counter_temp + 1 >> ;JSM(229) >> else: JSM(230) ; >> \ <=== SYNTAX ERROR >> > > is there a newline before the backslash ? Or a space after the backslash but > before the newline ? > > I investigated this some further in a hex editor, and indeed sometimes there's a space, ok that's my stupid mistake. But I found a situation that also in the very simple example always gives a syntax error a = 2 b = 5 def JSM (line_nr): print line_nr if a>3: print 'asddas' else: JSM(230) ; \ if b>3: <== SYNTAX ERROR pointing to the "f" of if print 'bbbbb' else: print 'ccccc' print 'aaps' And I don't see the syntax error. And if you're interested in the hex file data: 65 6C 73 65 3A 20 4A 53 4D 28 32 33 30 29 20 3B 20 5C 0D 0A btw, I now split the else line over more than 1 line, and everything is perfect. thanks, Stef Mientki From as at hut.at Wed Aug 29 08:32:49 2007 From: as at hut.at (hyena) Date: Wed, 29 Aug 2007 14:32:49 +0200 Subject: handling tabular data in python--newbie question Message-ID: <6cf42$46d56771$839b8704$5034@news1.tudelft.nl> Hi, Just jump in python few days. I am wondering how to store and index a table in python effectively and easily.I think the basic data types are not very straight foward to handle a table (eg, from csv or data base.) I have a csv file, the first row of it is column names and the rest rows are data. There are some tens of columns and hundreds rows in the file. I am planning to use the column names as variables to access data, currently I am thinking of using a dictionary to store this file but did not figure out a elegant way to start. Any comments and suggestions are wellcomed. Please forgive me if this question is too naive , and yes, I did search google a while but did not find what I want. Thanks From cousinstanley at gmail.com Sat Aug 4 22:53:05 2007 From: cousinstanley at gmail.com (Cousin Stanley) Date: Sat, 04 Aug 2007 21:53:05 -0500 Subject: Efficient Rank Ordering of Nested Lists References: <1186104049.022836.253470@e9g2000prf.googlegroups.com> <1i29gpw.1vh7eku1iauistN%aleax@mac.com> <1186279182_8217@sp12lax.superfeed.net> <1i2c5qo.ynsani1aobwaN%aleax@mac.com> Message-ID: <1186282385_8239@sp12lax.superfeed.net> > Cousin Stanley <cousinstanley at gmail.com> wrote: > ... >> for i , item in reversed( enumerate( sorted( single_list ) ) ) : > ... >> TypeError: argument to reversed() must be a sequence > > Oops, right. Well then, > > aux_seq = list(enumerate(sorted(single_list))) > for i, item in reversed(aux_seq): ... Alex .... That fixed it. Thanks .... -- Stanley C. Kitching Human Being Phoenix, Arizona ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From gnewsg at gmail.com Wed Aug 22 15:09:58 2007 From: gnewsg at gmail.com (billiejoex) Date: Wed, 22 Aug 2007 12:09:58 -0700 Subject: Impersonate another user temporarily (Unix and Windows) Message-ID: <1187809798.274511.230240@z24g2000prh.googlegroups.com> Hi there. I'm writing a modification for a FTP server library I'm maintaining. Depending on the system I'd want to temporarily impersonate the logged user to perform actions on filesystem. Something like: try: change_user('user', 'password') os.rmdir('dir') except: print "some error" finally: change_user('old_user', 'password') On Unix I took at look at os.seteuid() and os.setegid() functions and I noticed they could be useful for my purpose. On Windows I have no idea about how could I emulate a similar behaviour. Could someone please point me in the right direction? Thanks in advance From jarausch at skynet.be Mon Aug 13 10:18:15 2007 From: jarausch at skynet.be (Helmut Jarausch) Date: Mon, 13 Aug 2007 16:18:15 +0200 Subject: Drawing a graph In-Reply-To: <mailman.1917.1187012829.22759.python-list@python.org> References: <mailman.1917.1187012829.22759.python-list@python.org> Message-ID: <46C06827.9060804@skynet.be> Ghirai wrote: > Hello list, > > I need to draw a graph, 2 axes, 2D, nothing fancy. > One of the axes is time, the other one is a series of integers. > > I don't care much about the output format. > > Are there any specialized libraries for this, or should i use PIL? > What about Gnuplot.py http://gnuplot-py.sourceforge.net/ -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From oliver-at-hallmarkins.net Thu Aug 16 18:26:14 2007 From: oliver-at-hallmarkins.net (Oliver Nelson) Date: Thu, 16 Aug 2007 15:26:14 -0700 Subject: Canceling events from COM Objects Message-ID: <46c4cf1c$0$17203$39cecf19@news.twtelecom.net> I have MapPoint working in Python, and I'm trying to cancel events on the map, but I can't seem to make that happen. I'm responding to the events successfully in my panel object. My code is like this: global MapPointMod MapPointMod = win32com.client.gencache.EnsureModule("{51C0A9CA-F7B7-4F5A-96F4-43927C6FA50F}", 0, 1, 0) class MyPanel(wx.Panel): def __init__(self, *args, **kwds): # begin wxGlade: MyPanel.__init__ kwds["style"] = wx.TAB_TRAVERSAL wx.Panel.__init__(self, *args, **kwds) self.frame = args[0] MyMap = MakeActiveXClass(MapPointMod.MappointControl, eventObj=self) self.window_1 = MyMap(self, -1) self.window_1.OpenMap("C:\\TEMP\\GPS_ON.ptt") ... ... def OnBeforeClick(self, Button, Shift, X, Y, Cancel): print "tada" My event fires just fine, but I can't seem to figure out how to cancel the event so that mappoint doesn't do its stuff with it...I've tried setting Cancel based on the mappoint specs, but it doesn't seem to get sent back anywhere... Any ideas please? Thanx, OLIVER From hniksic at xemacs.org Fri Aug 31 07:06:00 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 31 Aug 2007 13:06:00 +0200 Subject: Registering a python function in C References: <1188508874.879215.319400@i13g2000prf.googlegroups.com> Message-ID: <87y7fsq7zb.fsf@mulj.homelinux.net> fernando <fernandofariajunior at gmail.com> writes: > Could someone post an example on how to register a python function as > a callback in a C function? If I understand correctly, your C function receives a Python function (as a function object of type PyObject *), which you need to call from C. To do that, call PyObject_CallFunction(obj, format, args...) where format and args are documented in http://docs.python.org/api/arg-parsing.html. Does that help? Also note that there is a dedicated mailing list for the Python/C API; see http://mail.python.org/mailman/listinfo/capi-sig . From basilisk96 at gmail.com Tue Aug 21 22:39:45 2007 From: basilisk96 at gmail.com (Basilisk96) Date: Wed, 22 Aug 2007 02:39:45 -0000 Subject: How to optimise this code? In-Reply-To: <faf33r$rb8$01$1@news.t-online.com> References: <mailman.68.1187711977.32294.python-list@python.org> <faf33r$rb8$01$1@news.t-online.com> Message-ID: <1187750385.511936.318560@i13g2000prf.googlegroups.com> David, If your true design intent is to run X number of test cases, unittest is the biggest bang for your buck, like shown by Peter's example. You just subclass unittest.TestCase, and def your test methods in the class body; they will simply be executed in the order you list them. It's just nice how it works that way. Otherwise, the function factory approach like Hrvoje's functionToCall = getattr(self, "testCase%s" % tc) is the best optimization. Cheers, -Basilisk96 From happyriding at yahoo.com Sun Aug 19 02:07:38 2007 From: happyriding at yahoo.com (happyriding) Date: Sat, 18 Aug 2007 23:07:38 -0700 Subject: Understanding closures In-Reply-To: <1187499818.125192.12930@m37g2000prh.googlegroups.com> References: <1187499818.125192.12930@m37g2000prh.googlegroups.com> Message-ID: <1187503658.855745.263390@d55g2000hsg.googlegroups.com> On Aug 18, 11:03 pm, Ramashish Baranwal <ramashish.li... at gmail.com> wrote: > Hi, > > I want to use variables passed to a function in an inner defined > function. Something like- > > def fun1(method=None): > def fun2(): > if not method: method = 'GET' > print '%s: this is fun2' % method > return > fun2() > > fun1() > > However I get this error- > UnboundLocalError: local variable 'method' referenced before > assignment > > This however works fine. > > def fun1(method=None): > if not method: method = 'GET' > def fun2(): > print '%s: this is fun2' % method > return > fun2() > > fun1() > > Is there a simple way I can pass on the variables passed to the outer > function to the inner one without having to use or refer them in the > outer function? > > Thanks, > Ramashish This works error free: def fun1(x=None): y = 10 def fun2(): print x if not x: method = 'GET' print '%s: this is fun2' % method fun2() fun1() Python reads x from the fun1 scope. But the following produces an error for the print x line: def fun1(x=None): y = 10 def fun2(): print x if not x: x = 'GET' #CHANGED THIS LINE print '%s: this is fun2' % method fun2() fun1() Traceback (most recent call last): File "3pythontest.py", line 8, in ? fun1() File "3pythontest.py", line 7, in fun1 fun2() File "3pythontest.py", line 4, in fun2 print x UnboundLocalError: local variable 'x' referenced before assignment It's as if python sees the assignment to x and suddenly decides that the x it was reading from the fun1 scope is the wrong x. Apparently, the assignment to x serves to insert x in the local scope, which makes the reference to x a few lines earlier an error. From tjreedy at udel.edu Thu Aug 2 14:24:22 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 2 Aug 2007 14:24:22 -0400 Subject: python 3.0, pywin32 and scipy References: <1186070475.659511.24130@q3g2000prf.googlegroups.com> Message-ID: <f8t7gk$f8r$1@sea.gmane.org> "vml" <victor.lebrun at gmail.com> wrote in message news:1186070475.659511.24130 at q3g2000prf.googlegroups.com... | I am trying to promote python in my job, my collegue only see matlab | and microsoft scripting language. | I understood that there willl be no backward compatibility between | python 2.x and 3.0, does it means that: Most of the basic language and syntax will be unchanged. Many to most of the new features will be introduced in 2.6 also so you can add their usage gradually, as needed, without converting everything. Most of the incompatibilities between 2.6+ and 3.0+ will be handled by 2to3.py. | - my script using pywin32 for the COM layer and scipy for the maths | won't work under 3.0 | - will we have the equivalent of pywin32 and scipy in python ? As with all 3rd party addons, that will depend on the authors or author groups. The same is true today for every new release, especially in regards to Windows binaries. | I will be incharge of designing a python module which will be a | 'matrix calculator' in our current software. Will it be compatible | with python 3.0 ? I guess no. But you will be able to use it *and distribute it* with Python2.5 indefinitely. Some people still run 1.5.2 code with the nearly decade old 1.5.2 interpreter. And I expect that there will be people running 2.5 code with Py2.5 a decade or more from now. The PSF still distributes versions back to about the first. Compare this with Microsoft pulling from distrubution the free version of VC2003 early in 2006, while maintaining the prohibition on anyone else distributing it. This has been a MAJOR nuisance for new Python-C-Windows developers who did not download it in time. | What can I answer to my collegue who will say 'Python is changing and | the stuff you are doing now is useless'? Short answer: stuff that is useful now will continue to be useful until requirements change. A possible longer answer: Google continues to make major use of Python without handcuffing themselves with such misunderstandings. They hired Python's main developer both to write Python code for internal use and to continue Python's development as he saw fit. They will be a test site for both the conversion process and the usability of the new version, giving Guido face-to-face feedback. When both are good enough for Google's developers, they should be good enough for most of the rest of us too. Terry Jan Reedy From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Aug 1 09:50:53 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 01 Aug 2007 15:50:53 +0200 Subject: access the name of my method inside it In-Reply-To: <1185973639.234450.305690@g12g2000prg.googlegroups.com> References: <1185959202.302467.276080@x35g2000prf.googlegroups.com> <5hb1ebF3inuf2U6@mid.uni-berlin.de> <1185973639.234450.305690@g12g2000prg.googlegroups.com> Message-ID: <46b08fb0$0$29143$426a74cc@news.free.fr> james_027 a ?crit : > Hi, > > On Aug 1, 5:18 pm, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote: >> On Wed, 01 Aug 2007 09:06:42 +0000, james_027 wrote: >>> for example I have this method >>> def my_method(): >>> # do something >>> # how do I get the name of this method which is my_method here? >> Why do you need this? There are ways but those are not really good for >> production code. >> > > I am going to use this in Django. I am trying to implement a > permission here, where in the database store the methods that the user > are allowed to execute. for example if the method is def > create_event(): the method will look for create_event in the database > to see if it allow to be execute. Then the solution is definitively to use a decorator, cf Paul's answer. From horpner at yahoo.com Mon Aug 27 14:44:18 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 27 Aug 2007 18:44:18 GMT Subject: convert non-delimited to delimited References: <1188237563.889663.228970@o80g2000hse.googlegroups.com> Message-ID: <slrnfd66eo.1r4.horpner@FIAD06.norwich.edu> On 2007-08-27, RyanL <ryanlauritsen at gmail.com> wrote: > I'm a newbie! I have a non-delimited data file that I'd like to > convert to delimited. > > Example... > Line in non-delimited file: > 0139725635999992000010100534+42050-102800FM-15+1198KAIA > > Should be: > 0139,725635,99999,2000,01,01,00,53,4,+42050,-102800,FM-15,+1198,KAIA It looks like a fixed format data file, also called flat-record files, in which fields are of fixed lengths, and records are separated by newlines. > What is the best way to go about this? Check out chapter 2 of _Text Processing in Python_ for one solution. http://gnosis.cx/TPiP/chap2.txt -- Neil Cerutti Weight Watchers will meet at 7 p.m. Please use large double door at the side entrance. --Church Bulletin Blooper From tjreedy at udel.edu Mon Aug 20 23:41:10 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 20 Aug 2007 23:41:10 -0400 Subject: str().join() isn't working References: <496954360708200905i2100b32ag5983ab729e5d216f@mail.gmail.com><mailman.4.1187633821.32294.python-list@python.org><1187634895.387910.179500@m37g2000prh.googlegroups.com><496954360708201249y1db0aa14qf0de14538fb51b9d@mail.gmail.com><fad17f$252$1@sea.gmane.org> <496954360708201446s331f9763vc5a629067594a0d9@mail.gmail.com> Message-ID: <fadmts$mjo$1@sea.gmane.org> "Robert Dailey" <rcdailey at gmail.com> wrote in message news:496954360708201446s331f9763vc5a629067594a0d9 at mail.gmail.com... | Yeah! That's it lol. Sorry, I wasn't looking at the documentation. At least | you got the point! But newbies might not have. In any case, 'dir(list)' in interactive mode prints the list methods and similarly for other types. From dwoo at voicesignal.com Thu Aug 30 18:01:11 2007 From: dwoo at voicesignal.com (Woo, Daniel) Date: Thu, 30 Aug 2007 18:01:11 -0400 Subject: wx.DirDialog defaultPath Message-ID: <4BFBA39857A02A4D9C92496D7E14001901D2E5CE@blackhole.voicesignal.com> Is there some kind of parsing/checking that is done on the defaultPath? The path I would like to set as default is something like this: "c:\Somedirectory\engineering\somedirectory". When providing this as the default, the control seems to think it is an invalid path, although it IS a valid path under Windows. I'm pretty sure this is because two directories in the hierarchy have the same name. Since it believes this is an invalid path, the dialog opens up browsing in the root directory. I can successfully set the default to other directories, nested as deep as I want and it works as expected. Anyway around this? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070830/70e723b8/attachment.html> From thomas at jollans.com Mon Aug 20 10:55:22 2007 From: thomas at jollans.com (Thomas Jollans) Date: Mon, 20 Aug 2007 16:55:22 +0200 Subject: How to decompress .Z file? In-Reply-To: <1187593343.30969.4.camel@hckim-desktop> References: <1187593343.30969.4.camel@hckim-desktop> Message-ID: <200708201655.26301.thomas@jollans.com> On Monday 20 August 2007, Hyunchul Kim wrote: > Hi, all > > How can .Z file be decompressed? > > According to python library reference, .Z file might not be supported by > python, yet. The GNU zip program (gzip) supports .Z and .z archives, so if you only want to support UNIX-like systems you could simply look for a program named "gunzip" or "uncompress" and use that. See also: http://mail.python.org/pipermail/python-list/2004-May/261669.html The format is now so antiquated (replaced almost totally with zlib/gzip compression) that I doubt you'll see it in python, but http://en.wikipedia.org/wiki/LZW seams to sport a python implementation. -- Regards, Thomas Jollans GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu Hacker key <http://hackerkey.com/>: v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part. URL: <http://mail.python.org/pipermail/python-list/attachments/20070820/ac1d271d/attachment.sig> From Muhammad_Shiraz at Dell.com Fri Aug 24 10:17:56 2007 From: Muhammad_Shiraz at Dell.com (Muhammad_Shiraz at Dell.com) Date: Fri, 24 Aug 2007 09:17:56 -0500 Subject: Win32: Detecting when system is locked or sleeping Message-ID: <2F8A7E1ED7BCED4A84FE44EAFEAED096029B4611@ausx3mpc122.aus.amer.dell.com> Hi I saw your post on the net. We are having a similar problem. Did you ever find out how to detect system lock? Muhammad Asif Shiraz Dell Inc. - eIntelligence Ph: 512.728.6479 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070824/b4de101e/attachment.html> From see at signature.invalid Mon Aug 27 23:07:48 2007 From: see at signature.invalid (Douglas Wells) Date: Mon, 27 Aug 2007 23:07:48 -0400 (EDT) Subject: Socket - gaierror References: <1188242671.182072.130150@r23g2000prd.googlegroups.com> <1188260349.031088.69010@l22g2000prc.googlegroups.com> Message-ID: <fb03i4$2bjg$1@flame.contek.com> In article <1188260349.031088.69010 at l22g2000prc.googlegroups.com>, half.italian at gmail.com writes: > On Aug 27, 4:22 pm, s... at signature.invalid (Douglas Wells) wrote: > > In article <1188244050.029920.314... at i13g2000prf.googlegroups.com>, > > > > half.ital... at gmail.com writes: > > > On Aug 27, 12:32 pm, Larry Bates <larry.ba... at websafe.com> wrote: > > > > > Changing it to IP gives me the same exact error... > > > > > File "bin/prgram.py", line 123, in notify > > > smtp = smtplib.SMTP("XXX.XXX.XXX.XXX") > > > > > File "/usr/lib/python2.4/smtplib.py", line 255, in __init__ > > > addr = socket.gethostbyname(socket.gethostname()) > > > > > gaierror: (-2, 'Name or service not known') > > > > > ~Sean > > > > Note that the lookup is of your *local* system name > > (socket.gethostname()). I suspect that the name of your client > > system (the one running the python script) is not registered in > > DNS. > > > > Try ping'ing your own system and see if that resolves in DNS. In > > UNIX/Linux you can use the hostname command; in any system you can > > write a python script to print the result of socket.gethostname(). > > > > - dmw > > I found a solution...but still not sure why that happened. > > root at 00:17:08:5E:EF:0F:/usr/local/sw/program/bin# hostname > 00:17:08:5E:EF:0F > root at 00:17:08:5E:EF:0F:/usr/local/sw/program/bin# ping 00:17:08:5E:EF:0F > ping: unknown host 00:17:08:5E:EF:0F > > >>> socket.gethostname() > '00:17:08:5E:EF:0F' > > Workaround: pass the 'local_hostname' arg to the smtplib.SMTP() call > with "localhost" > > ie smtp.SMTP("some.computer", local_hostname="localhost") > > This is just overriding the socket.gethostname() call entirely. > > Did a bit of testing with the /etc/hosts file, and even with an entry > to the hostname it can't resolve the ip. > The problem is the name "00:17:08:5E:EF:0F" PS. I didn't choose to > set the hostname that way. > > ~Sean That would be a reasonable workaround. The process of sending e-mail via SMTP could need the local host name for at least two uses: 1) the SMTP initial connection (RFC 2821) requires the client to identify itself (provide its host name); 2) the mail headers (RFC 2822) should include a return address, which probably defaults to using your user name at your client host name. The hostname of your system (00:17:08:5E:EF:0F) is silly when used with SMTP. Your system administrator is either ill-informed or is actively trying to prevent users from using their systems as servers. It has the form of an IPv6 numeric host address. Given the pathnames in your command interchange, you have a UNIX, Linux, or UNIX-like system. According to the Linux and UNIX standards: - If your system is IPv6-capable, the use of such a name with gethostbyname invokes "unspecified behavior." First, the function is not defined to work with such "numeric" identifiers. Second, it is not guaranteed to work with non-IPv4 names, and probably can't be registered in pre-i18n DNS data bases. - Even if your system is not IPv6-capable, such a host name is going to confuse many other systems that would be IPv6-capable and attempt to resolve the odd-ball name that your system provides. - Even if that worked, you're providing an IPv6 name form in conjunction with an IPv4 protocol (at least when you explicitly provide the IP address as a dotted-quad). - dmw -- . Douglas Wells . Connection Technologies . . Internet: -sp9804- -at - contek.com- . From michael at jedimindworks.com Thu Aug 23 16:33:52 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 23 Aug 2007 13:33:52 -0700 Subject: Syslog In-Reply-To: <1187654214.498082.225300@r34g2000hsd.googlegroups.com> References: <1187654214.498082.225300@r34g2000hsd.googlegroups.com> Message-ID: <84338CF6-F7F3-4F19-A99B-5F453741D172@jedimindworks.com> On Aug 20, 2007, at 4:56 PM, greg wrote: > Hi All, > > Could anyone tell me how I could syslog to a specific log (e.g. /var/ > log/daemon.log, /var/log/syslog.log...)? > # something like this: import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='/var/log/whatever.log', filemode='a') logging.info('random message') hth, Michael --- # Something just doesn't seem right in those # "Every kiss begins with 'K'" commercials. >>> 'Every Kiss'.startswith('K') False From steve at holdenweb.com Tue Aug 21 19:10:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 21 Aug 2007 19:10:43 -0400 Subject: Trouble with CGI code from Code Example 7.3 of the "Python Interactive CGI Tutorial" In-Reply-To: <1187710122.354087.158910@o80g2000hse.googlegroups.com> References: <1187705685.007927.55030@z24g2000prh.googlegroups.com> <1187710122.354087.158910@o80g2000hse.googlegroups.com> Message-ID: <fafrda$5n3$1@sea.gmane.org> Gabriel Genellina wrote: [...]working crystall balls are hard to find nowadays :) Well, judging by the OP's response you appear to be in possession of a pair :-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From cajnnjonaj at fjireanjtjprodjuctijons.com Sun Aug 19 12:22:14 2007 From: cajnnjonaj at fjireanjtjprodjuctijons.com (Aaron) Date: Sun, 19 Aug 2007 11:22:14 -0500 Subject: yet another indentation proposal References: <fEZxi.8855$9W6.6492@fe103.usenetserver.com> <1187538922.849174.94870@19g2000hsx.googlegroups.com> Message-ID: <c7_xi.136$lJ2.120@fe089.usenetserver.com> "Paddy" <paddy3118 at googlemail.com> wrote in message news:1187538922.849174.94870 at 19g2000hsx.googlegroups.com... > > Oh wow. it never crossed my mind... > > Can screen reaaderss be customized? > Maybe their is a way to get the screen reader to say indent and dedent > at thee appropriate places? > Or maybe a filter to put those wordds into the source? > > - Paddy. > Interestingly enough, there is a feature in my screenreader that purports to do just that, but it has proven unreliable at best. I think a filter to insert an indent indicator at the beginning of each line would not be too practical, as it would make copy and paste operations from one indentation level to another rather tedious (you'd have to add or remove one or more indicators from each line of code). Finally, just to be clear, I do not want to change the way 99.9% of Python code is written. I feel that the indentation model is a good one for 99.9% of users. What I do want to do is simply give the Python interpreter a tiny bit more flexibility to handle code from users or environments where indentation is not possible or practical. Aaron -- To reply directly, remove j's from email address. From theokok2000 at gmail.com Tue Aug 14 19:34:47 2007 From: theokok2000 at gmail.com (theokok2000 at gmail.com) Date: Tue, 14 Aug 2007 23:34:47 -0000 Subject: ooh-yes Message-ID: <1187134487.947597.286040@w3g2000hsg.googlegroups.com> http://Theologos.kokkonis.googlepages.com/ http://kokonis.aygoystinos.googlepages.com/ From gregc at cgl.ucsf.edu Thu Aug 30 00:12:36 2007 From: gregc at cgl.ucsf.edu (Greg Couch) Date: 30 Aug 2007 04:12:36 GMT Subject: Python molecular viewer References: <mailman.103.1188394354.28954.python-list@python.org> Message-ID: <fb5g3k$b3mt$1@cgl.ucsf.edu> Andy Cheesman <Andy.cheesman at bristol.ac.uk> writes: >Dear People, >I was wondering if people could recommend a simple molecular viewing >package written in python. I'm working in Theoretical chemistry and I'm >not after an all-singing dancing molecular rendering package(pymol does >that rather well) but a program which reads XYZ files and displays >simple structures which can be rotated in 3D >Thanks >Andy Check out http://www.cgl.ucsf.edu/chimera/. Unlike PyMol, all of the molecular data is accesible from Python. It still might be too much of an all-singing dancing molecular rendering package for you though. Greg Couch UCSF Computer Graphics Lab From mail at microcorp.co.za Wed Aug 22 11:01:44 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 22 Aug 2007 17:01:44 +0200 Subject: Dispatching default application for file, cross platform. References: <01e101c7e48d$e0e9f860$03000080@hendrik> <46CBFF66.7030207@timgolden.me.uk> Message-ID: <00af01c7e4cd$8f22ce40$03000080@hendrik> "Tim Golden" <mail at timgolden.me.uk> wrote: > Hendrik van Rooyen wrote: > > How do I do the equivalent of clicking (in SuSe) or double clicking (in Windows) > > on a file? > > > > In effect I want to tell the OS - take this file and feed it to the application > > that is registered for it. > > > > Not too sure what to Google for. > > > > - Hendrik > > os.startfile > > TJG Brill - thanks Tim! - Hendrik From arkanes at gmail.com Tue Aug 28 18:12:32 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 28 Aug 2007 17:12:32 -0500 Subject: Haskell like (c:cs) syntax In-Reply-To: <fb25uh$gl9$1@online.de> References: <fb25uh$gl9$1@online.de> Message-ID: <4866bea60708281512q31635803x1b025274c94caf7e@mail.gmail.com> On 8/28/07, Stefan Niemann <stefan at 3niemann.de> wrote: > Hi, > > sorry that I'm relatively new to Python. But the syntax and semantics of > Python already fascinate me, because I'm familiar with functional languages > like Haskell. > > Is there a pattern matching construct in Python like (head : tail), meaning > 'head' matches the first element of a list and 'tail' matches the rest? I > could not find this in the Python documentation. > > Regards, > Stefan > > Python does not have haskell like pattern matching. Things are written and done in a different way. When working with lists, Python has a slice syntax (which is rather more powerful than Haskells limited head->tail linked list syntax) that you can use to chop a sequence up into various parts. From pavlovevidence at gmail.com Fri Aug 31 00:23:02 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 30 Aug 2007 21:23:02 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <7xlkbsmqe4.fsf@ruckus.brouhaha.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> Message-ID: <1188534182.970023.178290@i38g2000prf.googlegroups.com> On Aug 30, 9:41 pm, Paul Rubin <http://phr... at NOSPAM.invalid> wrote: > Bruno Desthuilliers <bdesth.quelquech... at free.quelquepart.fr> writes: > > FWIW, the "Eiffel and SPARK Ada folks" also "brilliantly explained" > > why one can not hope to "write reliable programs" without strict > > static declarative type-checking. > > I don't know about Eiffel but at least an important subset of SPARK > Ada's DBC stuff is done using static analysis tools (not actually > built into the compiler as it happens) to verify statically > (i.e. without actually running the code) that the code fulfills the > DBC conditions. I don't see any way to do that with Python > decorators. I don't see any way to do that in Python with built-in DBC syntax, either. :) Carl Banks From has.temp3 at virgin.net Mon Aug 6 05:46:19 2007 From: has.temp3 at virgin.net (has) Date: Mon, 06 Aug 2007 02:46:19 -0700 Subject: xlrd question In-Reply-To: <mailman.1654.1186339437.22759.python-list@python.org> References: <mailman.1654.1186339437.22759.python-list@python.org> Message-ID: <1186393579.221394.145020@w3g2000hsg.googlegroups.com> On 5 Aug, 19:43, jay <jyoun... at kc.rr.com> wrote: > So if I'm understanding this correctly, it really only > installs something in '/Library/Python/2.3/site-packages' Correct. > (as well as > an alias to it from '/System/Library/Frameworks/Python.framework/ > Versions/2.3/lib/python2.3/site-packages') No, /System.../python2.3/site-packages is a symlink to /Library/Python/ 2.3/site-packages set up by Apple. DistUtils makes no modification to anything under /System. HTH has -- http://appscript.sourceforge.net http://rb-appscript.rubyforge.org From Brian.McCann at viziant.net Wed Aug 29 17:03:05 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Wed, 29 Aug 2007 17:03:05 -0400 Subject: copying files References: <93066C069973ED448DC2BCEA9C44A7383BE30C@efmailx> <46D5C01B.7080202@bigfoot.com> Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE30E@efmailx> <mailto:brian.mccann at viziant.net> Hi Ricardo, what do the + signs do? ________________________________ From: Ricardo Ar?oz [mailto:ricaraoz at gmail.com] Sent: Wed 8/29/2007 2:51 PM To: Brian McCann Cc: python-list at python.org Subject: Re: copying files Brian McCann wrote: > Hi, > > with the code below I set a variable TEST_HOME to a path and the > variable m to a path > in my current dir. > I have a symbolic link setting m---->lib > when I run the script I get no errors and the lib dir with its 20 files > does not get copied to /v01/test_home > any help would be greatly appreciated > > --Brian > > #!/usr/bin/python > import string > import os > import sys > import errno > import shutil > import tarfile > > TEST_HOME = "/v01/test_home" > m = "./lib" > os.system("cp -r m TEST_HOME") > #os.system("tar -cvf viziant-ingestion.tar /v01/") > Sorry, meant : os.system("cp -r " + m + " " + TEST_HOME) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070829/5d461396/attachment.html> From michele.simionato at gmail.com Fri Aug 31 08:40:51 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 31 Aug 2007 12:40:51 -0000 Subject: Google spreadsheets Message-ID: <1188564051.726895.288860@y42g2000hsy.googlegroups.com> I would like to upload a tab-separated file to a Google spreadsheet from Python. Does anybody have a recipe handy? TIA, Michele Simionato From gherron at islandtraining.com Thu Aug 16 06:24:21 2007 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 16 Aug 2007 03:24:21 -0700 Subject: python socket usage In-Reply-To: <200708161153.12294.comp.ogz@gmail.com> References: <mailman.2046.1187250159.22759.python-list@python.org> <1187250839.541105.60900@r29g2000hsg.googlegroups.com> <46C408D6.8000907@islandtraining.com> <200708161153.12294.comp.ogz@gmail.com> Message-ID: <46C425D5.3060300@islandtraining.com> O?uz Yar?mtepe wrote: > On Thursday 16 August 2007 11:20:38 Gary Herron wrote: > >> If you really want to send any Python object through a socket, look up >> the Pickle and cPickle modules. These will marshal (as it's called) any >> Python object of any type and complexity into a byte string which can be >> sent across a socket. On the receiving end of the socket, the byte >> string can be turned back into an equivalent Python object. >> >> Gary Herron >> > > As i read pickle module is Python-spesific. I need to talk with a Java > application and get the infortion that it will send. What i do right now is > listening a socket and reding the string that is sent by the java > application. So the java application is sending a string and i am reading and > parsing it and getting the related infortion i need. A more professional way > may be the reading the object itself. Is it possible to get the array for ex. > object that is sent from the Java application with sockets? > > Then consider XMLRPC. It is a language/platform independent way of making a call to a remote procedure (with parameters). Your Python program would implement a XMLRPC server listening for calls to a single procedure, and your Java program would make a connection to the XMLRPC server and make a call to the procedure. The XMLRPC package in JAVA (don't know what it's called, but it's gotta exist) will package up the procedure being called and its parameters as an XML document, and send it to the server. The Python XMLRPC server package will decipher the XML document, extracting the procedure name and its arguments, make the call, and package up any return value (again as an XML document) and send it back on the socket. The calling JAVA program will receive the return value, just as in any normal procedure call, and continue on it's merry way. The XMLRPC protocol can only pass simple arguments, and (I think) arrays of simple arguments. But that's sufficient for a tuple of integers as you had in your example. Hope that helps, Gary Herron From jstroud at mbi.ucla.edu Sat Aug 4 02:35:21 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 03 Aug 2007 23:35:21 -0700 Subject: How to pass a reference to the current module In-Reply-To: <7xy7gr51ny.fsf@ruckus.brouhaha.com> References: <f90gsg$ek4$1@zinnia.noc.ucla.edu> <pan.2007.08.04.01.46.50.985228@REMOVE.THIS.cybersource.com.au> <7xy7gs9ioe.fsf@ruckus.brouhaha.com> <pan.2007.08.04.04.37.38.567054@REMOVE.THIS.cybersource.com.au> <7xy7gr51ny.fsf@ruckus.brouhaha.com> Message-ID: <B6Vsi.1312$qa3.889@nlpi069.nbdc.sbc.com> Paul Rubin wrote: > Hmm, it's a pain that there's no clean way to get at the current > module. PEP 3130 shows some icky and unreliable ways, e.g. > > func = getattr(sys.modules[__name__], 'f') > > PEP 3130's goal was to add a clean way to do this. Unfortunately it > was rejected. Yes, this is the essence of the problem. At least I'm not the only one to have needed (or at least wanted) this. James From steve at holdenweb.com Mon Aug 13 20:06:09 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 13 Aug 2007 20:06:09 -0400 Subject: chmod g+ Equivalent In-Reply-To: <1187042290.821786.178420@19g2000hsx.googlegroups.com> References: <1187042290.821786.178420@19g2000hsx.googlegroups.com> Message-ID: <f9qrle$7gt$1@sea.gmane.org> milan_sanremo wrote: > I've read the documentation on os.chmod() and can implement all the > standard commands, but what is the syntax for the equivalent of chmod g > + to set the group id? > I assume when you say "to set the group id" you actually mean "to assert the setgid bit"? I further presume that when you say "chmod g+" you actually mean "chmod g+s". You can't have read the documentation very thoroughly. It says right at the top: S_ISUID S_ISGID Of course, your process needs to have root privilege in order to be able to do that. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From me at privacy.net Tue Aug 28 06:13:49 2007 From: me at privacy.net (Dan Sommers) Date: Tue, 28 Aug 2007 10:13:49 GMT Subject: Biased random? References: <favd0c$fcu$1@ss408.t-com.hr> Message-ID: <pan.2007.08.28.10.15.57@privacy.net> On Mon, 27 Aug 2007 22:42:45 +0200, Ivan Voras wrote: > I have a list of items, and need to choose several elements from it, > "almost random". The catch is that the elements from the beginning > should have more chance of being selected than those at the end (how > much more? I don't care how the "envelope" of probability looks like at > this point - can be linear). I see that there are several functions in > Python standard libraries for various distribution, but is there an easy > pythonic way to make them do what I need? If you really just want to tend towards the beginning of the list, and don't care what the envelope looks like, how about this: def biasedselection(thelist): index = random.random() * random.random() * len(thelist) # or index random.random() ** 2 * len(thelist) return thelist[index] Dan -- Dan Sommers A death spiral goes clock- <http://www.tombstonezero.net/dan/> wise north of the equator. Atoms are not things. -- Werner Heisenberg -- Dilbert's PHB From nospam.themindstorm at gmail.com Wed Aug 1 19:57:38 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Wed, 1 Aug 2007 23:57:38 +0000 (UTC) Subject: Where do they tech Python officialy ? References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> <1185265091.276958.239910@r34g2000hsd.googlegroups.com> <1i23wyk.avc945i4dwsiN%aleax@mac.com> <mailman.1423.1185957645.22759.python-list@python.org> <1i25pjo.1mo5uqc1yxqsjkN%aleax@mac.com> Message-ID: <Xns99801DC5855C4themindstorm@80.91.229.5> aleax at mac.com (Alex Martelli) wrote in news:1i25pjo.1mo5uqc1yxqsjkN% aleax at mac.com: > Alex Popescu <nospam.themindstorm at gmail.com> wrote: > ... >> > and you will both learn a lot _and_ acquire "professional experience" >> > that any enlightened employer will recognize as such. >> >> It depends :-). In my experience I met employers being concerned by my >> implication in the oss world :-). > > Considering that even the King of Proprietary Software, Microsoft, now > happily hires major Open Source figures such as Jim Hugunin (MS was also > a top-tier sponsor at the recent OSCON, with both managerial and senior > technical employees giving keynotes and tech talks), it boggles the mind > to think about which kind of company would instead be "concerned" by a > candidate's OS experience. > > Have you seen/heard of Jim lately? Cause I haven't. By the time he was the lead of the AspectJ team his charismatic presence was everywhere (at least around that project). However I do agree with you. The only remark is that US trends are not hitting my part of Eu so quickly ;-) (things are indeed changing). > These are the ones you don't wan't to work for anyway !-) Well... this is sometimes debatable :-). bests, ./alex -- .w( the_mindstorm )p. From mccredie at gmail.com Thu Aug 30 19:27:03 2007 From: mccredie at gmail.com (Matimus) Date: Thu, 30 Aug 2007 23:27:03 -0000 Subject: Registering a python function in C In-Reply-To: <1188508874.879215.319400@i13g2000prf.googlegroups.com> References: <1188508874.879215.319400@i13g2000prf.googlegroups.com> Message-ID: <1188516423.744038.309700@z24g2000prh.googlegroups.com> On Aug 30, 2:21 pm, fernando <fernandofariajun... at gmail.com> wrote: > Could someone post an example on how to register a python function as > a callback in a C function? It expects a pointer to PyObject... how do > I expose that? Basically, the signature of the function is > foo(PyObject* obj), where obj is the callback function... It's not > exactly extending or embedding, I've looked at those examples but they > don't really show how to do this... > > Thanks for the help! It most definitely is extending or embedding, it just doesn't follow the examples provided. I can't be too specific because I don't know what your environment is like. As in, have you already initialized python and all of that? Do you have access to _any_ PyObject* variables? Here is something that _might_ help (not tested): [code] PyObject* mod; PyObject* func; mod = PyImport_ImportModule("mymodule"); func = PyObject_GetAttrString( mod, "myfunc") ; foo(func); [/code] It might be useful to look at the "Python/C API Reference Manual", not just the extending and embedding stuff. http://docs.python.org/api/api.html Matt From steve at holdenweb.com Mon Aug 13 19:44:58 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 13 Aug 2007 19:44:58 -0400 Subject: Finding gurus (was Re: Something in the function tutorial confused me.) In-Reply-To: <1187037060.708280.12820@i13g2000prf.googlegroups.com> References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <mailman.1737.1186577596.22759.python-list@python.org> <5hv705F3mk67nU1@mid.individual.net> <1i2nhnv.2y00l5173lfbbN%aleax@mac.com> <f9kd93$lg8$1@panix3.panix.com> <mailman.1935.1187032913.22759.python-list@python.org> <1187037060.708280.12820@i13g2000prf.googlegroups.com> Message-ID: <f9qqdn$355$1@sea.gmane.org> kyosohma at gmail.com wrote: > On Aug 13, 2:22 pm, Ricardo Ar?oz <ricar... at gmail.com> wrote: >> Aahz wrote: >>> In article <1i2nhnv.2y00l5173lfbbN%al... at mac.com>, >>> Alex Martelli <al... at mac.com> wrote: >>>> Because of this, a Google search for >>>> "<name> <surname>" python >>>> may sometimes help; when you get 116,000 hits, as for "Steve Holden" >>>> python, that may be a reasonable indication that the poster is one of >>>> the world's Python Gurus (in fact, the winner of the 2007 Frank WIllison >>>> Award -- congratulations, Steve!!!). >>> Sometimes that precise search pattern isn't appropriate, of course. ;-) >> Sorry, will answer as soon as I read the 52000 hits for "Aahz python". >> Be patient ;c) > > No offense to Steven but Alex has over twice as many hits. Gives the > rest of us something to shoot for, eh? > No offense taken: Alex won the award before me! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From lists at liquidtrust.org Thu Aug 23 16:37:07 2007 From: lists at liquidtrust.org (Charlie) Date: Thu, 23 Aug 2007 14:37:07 -0600 Subject: MsiLib In-Reply-To: <46CDE72F.2090009@v.loewis.de> References: <mailman.172.1187876423.32294.python-list@python.org> <46CDE72F.2090009@v.loewis.de> Message-ID: <20070823143707.su0fwun9jk84sc0w@mail.liquidtrust.org> Quoting "Martin v. L?wis" <martin at v.loewis.de>: > Charlie schrieb: >> Thank you everybody for your help. It finally runs without errors and I >> should be able to use this as I figure out more of it. I am curios if >> there is any idea as to when GetString will be implemented? > > If I can find the time, it may be for Python 2.6. If not, Python 2.7, > 3.1, or so. Faster if a patch is contributed. > > Regards, > Martin > Thank you. I would be willing to help out, but as of now I have no idea how to get started on it. If you would be willing to provide some guidance, then I would be fine with giving it a shot if nothing more. My guess is that it would have to implement the MsiRecordGetString function so that it is accessible, but I don't know beyond that. Charlie From durumdara at gmail.com Tue Aug 14 04:32:25 2007 From: durumdara at gmail.com (durumdara) Date: Tue, 14 Aug 2007 10:32:25 +0200 Subject: [half-off] LAMA - how to I use the news server with thunderbird Message-ID: <46C16899.5030906@gmail.com> Hi! Is anyone knows about an NNTP servers that containing newsgroups about these lists: - python win32 (python-win32) - mod_python - gimp-python - gimp I wanna set thes nntp servers in thunderbird so I need correct addresses. Thanks for your help: dd From gagsl-py2 at yahoo.com.ar Tue Aug 28 02:30:52 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 28 Aug 2007 03:30:52 -0300 Subject: Biased random? References: <favd0c$fcu$1@ss408.t-com.hr> Message-ID: <op.txra1qgsx6zn5v@gabriel2.softlabbsas.com.ar> En Mon, 27 Aug 2007 17:42:45 -0300, Ivan Voras <ivoras at __fer.hr__> escribi?: > I have a list of items, and need to choose several elements from it, > "almost random". The catch is that the elements from the beginning > should have more chance of being selected than those at the end (how > much more? I don't care how the "envelope" of probability looks like at > this point - can be linear). I see that there are several functions in > Python standard libraries for various distribution, but is there an easy > pythonic way to make them do what I need? Using a linear (or triangular) distribution: --- begin --- from random import randint def biased_choice(values): """Choose a random element from values; first elements are chosen more frequently than later ones. Weights are linearly assigned; given n elements, the first has weight n, second has n-1, ... last has weight 1. """ n = len(values) sumw = ((n + 1) * n) // 2 x = randint(1, sumw) F = 0 for i in xrange(1, n+1): F += i if x<=F: return values[-i] # test from collections import defaultdict values = ["a", "b", "c", "d", "e"] stats = defaultdict(int) for i in xrange(150000): stats[biased_choice(values)] += 1 for key in sorted(stats): print key, stats[key] --- end --- Output: a 50023 b 39869 c 30256 d 19784 e 10068 -- Gabriel Genellina From labrach at gmail.com Wed Aug 29 12:22:51 2007 From: labrach at gmail.com (labrach at gmail.com) Date: Wed, 29 Aug 2007 16:22:51 -0000 Subject: python + gcov Message-ID: <1188404571.590476.265840@r34g2000hsd.googlegroups.com> Hi I want to profile (and analyse coverage) some c++ code imported as a python module I've compiled python (2.4.2) with gcc 3.4.3 and flags=-Wall -fprofile- arcs -ftest-coverage in order to use gcov. However, the python binary does not generate any coverage file (such than *.gcno, gcda) during execution. any tips ? or may be another method to profile c++ wrapped modules within python ? thanks laurent From steve at holdenweb.com Tue Aug 14 19:30:01 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 14 Aug 2007 19:30:01 -0400 Subject: chmod g+ Equivalent In-Reply-To: <1187094251.540591.308320@g4g2000hsf.googlegroups.com> References: <1187042290.821786.178420@19g2000hsx.googlegroups.com> <mailman.1946.1187053563.22759.python-list@python.org> <1187094251.540591.308320@g4g2000hsf.googlegroups.com> Message-ID: <46C23AF9.3020107@holdenweb.com> milan_sanremo wrote: > On Aug 13, 8:06 pm, Steve Holden <st... at holdenweb.com> wrote: >> milan_sanremo wrote: >>> I've read the documentation on os.chmod() and can implement all the >>> standard commands, but what is the syntax for the equivalent of chmod g >>> + to set the group id? >> I assume when you say "to set the group id" you actually mean "to assert >> the setgid bit"? I further presume that when you say "chmod g+" you >> actually mean "chmod g+s". > > The g+s was an omission on my part. I can see how it would confuse > the issue. > > I'm not sure if I mean "to assert the setgid bit". My SUN docs refer > to it being 'on'. > http://docs.sun.com/app/docs/doc/819-3321/6n5i4b767?l=en&a=view&q=setgid+bit > >> You can't have read the documentation very thoroughly. It says right at >> the top: >> >> S_ISUID >> S_ISGID > > I did see this in the documentation: > > Change the mode of path to the numeric mode. mode may take one of the > following values (as defined in the stat module) or bitwise or-ed > combinations of them: > > * S_ISUID > * S_ISGID > > Which refers to: > http://docs.python.org/lib/module-stat.html > > After which it was still unclear. > > My question is in the command os.chmod(myDirectory, ?) what is the > value for ? to turn on the setgid bit. > > Contrary to your presumption, I did read the documentation > thoroughly. It is inability to understand the concept which prompted > me to post the question here. > Well, you don't tell us what (if anything) you have tried so far. Python has an interpreter that's very easy to use interactively. Why don't you try os.chmod(my_directory, os.S_ISGID) and see if it does what you want? You can often save time by trying such things for yourself. Though it needn't be a substitute for asking questions on this list, it can make your questions better-informed. In this particular case, now I understand your needs a little better, since you want to *add* a bit setting you will likely have to use something like current_permissions = os.fstat(my_directory).ST_MODE to read the directory's current permission bits. Then you will need to execute os.chmod(my_directory, current_permissions | stat.S_ISGID) Please don't take this as gospel, though, as I am currently on the road with only a Windows computer available, but I think it should get you closer to where you want to be. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From ldo at geek-central.gen.new_zealand Mon Aug 27 18:54:52 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 28 Aug 2007 10:54:52 +1200 Subject: Socket - gaierror References: <1188242671.182072.130150@r23g2000prd.googlegroups.com> <OIidnbjzCJVLu07bnZ2dnUVZ_gidnZ2d@comcast.com> <1188244050.029920.314700@i13g2000prf.googlegroups.com> <1188253525.718844.115500@q5g2000prf.googlegroups.com> Message-ID: <favkj8$akh$1@lust.ihug.co.nz> In message <1188253525.718844.115500 at q5g2000prf.googlegroups.com>, half.italian at gmail.com wrote: > What could cause the shell to be > able to resolve the addresses properly, but not python? > nnsswitch.conf ? How did you test the name resolution in the shell--was it with "host" or "ping"? I would recommend ping, because that would use the same C runtime gethostbyname call that your Python code is trying to use. From tdwdotnet at gmail.com Thu Aug 23 16:10:26 2007 From: tdwdotnet at gmail.com (Tim Williams) Date: Thu, 23 Aug 2007 21:10:26 +0100 Subject: Using Regular Expresions to change .htm to .php in files In-Reply-To: <9afea2ac0708231305v539390dew84926f0b0dcd6974@mail.gmail.com> References: <B81995429.43.65370.1@mxextra> <9afea2ac0708231305v539390dew84926f0b0dcd6974@mail.gmail.com> Message-ID: <9afea2ac0708231310i2b1292c4m60923b7fcd30829c@mail.gmail.com> On 23/08/07, Tim Williams <tdwdotnet at gmail.com> wrote: > On 23/08/07, sebzzz at gmail.com <sebzzz at gmail.com> wrote: > > Hi, > > > > I have a bunch of files that have changed from standard htm files to > > php files but all the links inside the site are now broken because > > they point to the .htm files while they are now .php files. > > > > Does anyone have an idea about how to do a simple script that changes > > each .htm in a given file to a .php > > > > Thanks a lot in advance > > > > Something like: > > Infile = open(f_name,'r+') > Data = Infile.read() > InFile.write(Data.replace('.htm','.php')) > Infile.close() > Actually, scrub that, its been a long day! You either need a Infile.seek(0) in the above before the write() , or you can do. Data = open(f_name).read() outfile = open(f_name,'w') outfile.write(Data.replace('.htm','.php')) outfile.close() From kyosohma at gmail.com Sun Aug 12 21:00:51 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 13 Aug 2007 01:00:51 -0000 Subject: Complexity of methods etc In-Reply-To: <mailman.1892.1186963490.22759.python-list@python.org> References: <mailman.1892.1186963490.22759.python-list@python.org> Message-ID: <1186966851.882346.244490@l22g2000prc.googlegroups.com> On Aug 12, 7:04 pm, "Nathan Harmston" <ratchetg... at googlemail.com> wrote: > Hi, > > I was wondering if anyone knew of any resources, where I might be able > to find information about the complexity of certain python functions > or little tips on how to reduce complexity. I mean like the "".join(), > kind of thing? > > I want to see if there are any improvements I can add to my coding in > order to reduce time/space usage/ > > Many Thanks in advance > > Nathan Read a book? Lutz's "Programming Python 3rd Ed." will teach you a lot of tricks. I would also recommend the Python Cookbook book or the online version here: http://aspn.activestate.com/ASPN/Python/Cookbook/ Mike From martin at v.loewis.de Tue Aug 14 05:30:57 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 14 Aug 2007 11:30:57 +0200 Subject: IDLE path browser not recognizing my PYTHONPATH In-Reply-To: <1187071523.150365.125590@x40g2000prg.googlegroups.com> References: <1187071523.150365.125590@x40g2000prg.googlegroups.com> Message-ID: <46C17651.6090407@v.loewis.de> > I set PYTHONPATH to /home/me/bin in bash.bashrc, however the IDLE path > browser is not recognizing this. Not sure why. > > Grateful for any insight. The file "bash.bashrc" has no relevance. If you meant to set the variable every time you start bash, put it into ".bashrc", in your home directory. If that still doesn't work, type "env" before starting idle, and inspect its output. Regards, Martin From fabioztessitore at libero.it Fri Aug 3 17:45:49 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 03 Aug 2007 21:45:49 GMT Subject: downloading files References: <1186166920.757662.269340@o61g2000hsh.googlegroups.com> <mailman.1584.1186168229.22759.python-list@python.org> <1186176739.765447.262720@w3g2000hsg.googlegroups.com> Message-ID: <46b3a20d$0$17946$4fafbaef@reader1.news.tin.it> Il Fri, 03 Aug 2007 14:32:19 -0700, Ehsan ha scritto: > It works but could you explain more what's wrong with just 'w'? On Unix-like systems newline means '\n' On Window newline means '\r\n' So, when you open a file on Window with 'w' option, Win replace downloaded '\n' with a local '\r\n' and the file isn't readable. If you use 'wb' you say that you want a binary copy ('b' option) and Win doesn't replace anything. Hope it is useful, bye Fabio From byte8bits at gmail.com Thu Aug 2 14:59:19 2007 From: byte8bits at gmail.com (brad) Date: Thu, 02 Aug 2007 14:59:19 -0400 Subject: Determining if file is valid image file In-Reply-To: <1186064275.652416.250540@d55g2000hsg.googlegroups.com> References: <1186064098.587590.91210@g4g2000hsf.googlegroups.com> <1186064275.652416.250540@d55g2000hsg.googlegroups.com> Message-ID: <f8t9l2$9vr$1@solaris.cc.vt.edu> Andr? wrote: > I should have added: I'm interesting in validating the file *content* > - not the filename :-) Some formats have identifying headers... I think jpeg is an example of this. Open it with a hex editor or just read the first few bytes and see for yourself. Brad From steve at holdenweb.com Fri Aug 10 08:17:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 10 Aug 2007 08:17:43 -0400 Subject: Question about properties. In-Reply-To: <1186742730.729034.256800@i13g2000prf.googlegroups.com> References: <1186741289.074717.174370@e16g2000pri.googlegroups.com> <5i2t7dF3kqc46U3@mid.uni-berlin.de> <1186742730.729034.256800@i13g2000prf.googlegroups.com> Message-ID: <f9hl13$7cq$1@sea.gmane.org> king kikapu wrote: > On Aug 10, 1:33 pm, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote: >> On Fri, 10 Aug 2007 03:21:29 -0700, king kikapu wrote: >>> Hi, >>> i read in a book the following code snippet that is dealing with >>> properties: >>> class ProtectAndHideX(object): >>> def __init__(self, x): >>> assert isinstance(x, int), '"x" must be an integer!"' >>> self.__x = ~x >>> def get_x(self): >>> return ~self.__x >>> x = property(get_x) >>> Can anyone please help me understand what the symbol "~" does here ?? >> This has nothing to do with properties. For integer objects ``~`` is the >> bitwise negation or invertion operator. >> >> Ciao, >> Marc 'BlackJack' Rintsch > > Xmmm...ok then but what is actually doing there ?? I removed it and > things seems to work the same way... > Observe the name of the class. I believe the integer value is inverted merely as a demonstration that the value can be "obscured" somehow - in a more complex example the author might have insisted in string values, the encrypted them. It's not essential to the example, it merely shows that the value retrieved from the property can be computed from underlying attributes. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From paddy3118 at googlemail.com Sun Aug 19 11:56:38 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 19 Aug 2007 15:56:38 -0000 Subject: Python syntax r prefix to a string In-Reply-To: <1187538233.285841.117280@e9g2000prf.googlegroups.com> References: <1187538233.285841.117280@e9g2000prf.googlegroups.com> Message-ID: <1187538998.016872.243160@w3g2000hsg.googlegroups.com> On Aug 19, 4:43 pm, goldtech <goldt... at worldpost.com> wrote: > Does anyone know this syntax and could link me to an explanation? > > Something like: > > Workspace = r'C:\foobar\mystuff\xyz' > > What's that "r" doing? Sometimes I see a "u" too. > > Explanation appreciated. > > Thanks, > Lee G. Search for raw strings and unicode stringss... From byte8bits at gmail.com Wed Aug 8 09:58:01 2007 From: byte8bits at gmail.com (brad) Date: Wed, 08 Aug 2007 09:58:01 -0400 Subject: This bit of code hangs Python Indefinitely In-Reply-To: <5htvm3F3md0abU3@mid.uni-berlin.de> References: <f9ch45$ku$1@solaris.cc.vt.edu> <5htvm3F3md0abU3@mid.uni-berlin.de> Message-ID: <f9ci85$1t3$2@solaris.cc.vt.edu> Marc 'BlackJack' Rintsch wrote: > Why did you put an upper bound to the queue? For clarity. Explicit is better than implicit, right? In our design, the queue should only have x number of things, so why not show that? Other than that, the limit is arbitrary and is not needed. From lists at liquidtrust.org Thu Aug 23 09:33:36 2007 From: lists at liquidtrust.org (Charlie) Date: Thu, 23 Aug 2007 07:33:36 -0600 Subject: MsiLib Message-ID: <20070823073336.cgppsh9yscccs0o4@mail.liquidtrust.org> Thank you everybody for your help. It finally runs without errors and I should be able to use this as I figure out more of it. I am curios if there is any idea as to when GetString will be implemented? Charlie From santi_anti at yahoo.com Tue Aug 21 05:18:26 2007 From: santi_anti at yahoo.com (susanti marsol) Date: Tue, 21 Aug 2007 02:18:26 -0700 (PDT) Subject: how to remove number In-Reply-To: <mailman.205.1187683205.32293.python-list@python.org> Message-ID: <763139.69891.qm@web63115.mail.re1.yahoo.com> how to remove all number in our's document? python-list-request at python.org wrote: Send Python-list mailing list submissions to python-list at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to python-list-request at python.org You can reach the person managing the list at python-list-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Python-list digest..." Today's Topics: 1. Re: GeneratorExit should derive from BaseException, not Exception (Chad Austin) 2. Re: GeneratorExit should derive from BaseException, not Exception (Chad Austin) 3. Re: Newbee Question (Asun Friere) 4. Re: Is there a way to change the default string encoding? (Ron Garret) 5. Re: Is there a way to change the default string encoding? (Fabio Z Tessitore) 6. Re: Newbee Question (Asun Friere) 7. Re: Is there a way to change the default string encoding? (Peter Otten) 8. Re: Newbee Question (Asun Friere) 9. Re: yet another indentation proposal (Dennis Lee Bieber) 10. Re: datetime in microseconds (Dennis Lee Bieber) 11. Re: Newbee Question (Dennis Lee Bieber) From: Chad Austin <chad at imvu.com> To: python-list at python.org Date: Tue, 21 Aug 2007 00:01:01 -0700 Subject: Re: GeneratorExit should derive from BaseException, not Exception Hi Terry, Thank you for your feedback. Responses inline: Terry Reedy wrote: > "Chad Austin" wrote in message > news:46CA0EFE.6020103 at imvu.com... > || try: > | result = yield chatGateway.checkForInvite({'userId': userId}) > | logger.info('checkForInvite2 returned %s', result) > > would not > except GeneratorExit: > solve your problem? Yes, we could add an "except GeneratorExit: raise" clause to every place we currently catch Exception, but I feel like this is one of those things where it's hard to get it right in all places and also hard to cover with unit tests. Instead, we'll have subtle bugs where finally clauses don't run because the GeneratorExit was swallowed. Also, SystemExit and KeyboardInterrupt were made into BaseExceptions for the same reasons as I'm giving. (As I understand it, anyway.) > | except Exception: > > Such catchalls are known to be prone to catch too much > and are therefore not encouraged ;-). > As in 'use at your own risk'. > Guido encourages specific catches just for the reasons you give here. More below: > There was a *long* discussion of the current 2.5 exception hierarchy on > pydev. Search either python.org's or gmane's archive if you want to pursue > this. But I expect the people involved would say much the same as above. I've actually read the background on the exception hierarchy (and agree with it all), especially other suggestions that GeneratorExit derive from BaseException. As I understand it, Guido's objections are threefold: 1) The previous "generators as coroutines" examples were too theoretical: I've wanted GeneratorExit to derive from BaseException for months now, but didn't write this proposal until I actually wrote code that failed in the presence of task cancellation. 2) You should avoid catching everything with except Exception: I think that's too idealistic. Just do a search for try: except: through publicly available Python. :) Sometimes, you really _do_ want to catch everything. When you're making a network request that involves xmlrpclib, urllib2, httplib, etc. you don't actually care what the error was. (Well, except that the exceptions are submitted for automated analysis.) Similarly, when loading a cache file with pickle, I don't care what went wrong, because it's not critical and should not be turned into a crash for the user. (We automatically report exceptions that bubble into the main loop as crashes.) 3) If GeneratorExit escapes from the generator somehow and gets raised in the main loop, then it will bubble out of the application like SystemExit and KeyboardInterrupt would: I think this argument is somewhat specious, because I can't imagine how that would happen. You'd have to store exceptions in your generator and explicitly bubble them out somehow. Our crash handling has to specially handle KeyboardInterrupt and SystemExit anyway, since there are currently non-Exception exceptions, such as strings and custom classes that forgot to derive from Exception, that should count as crashes. I personally can't think of any cases where I would _want_ to handle GeneratorExit. I just want finally: and with: clauses to do the right thing when a task is cancelled. Anyway, I haven't yet encountered any serious bugs due to this yet... I'm just worried that if a task is holding some resource and blocking on something, then the resource won't get released. If this really does come up, then I do have a little bit of python + ctypes that replaces GeneratorExit with ImvuGeneratorExit (deriving from BaseException), but that's not very appealing. Thanks again, -- Chad Austin http://imvu.com/technology From: Chad Austin <chad at imvu.com> To: python-list at python.org Date: Tue, 21 Aug 2007 00:41:03 -0700 Subject: Re: GeneratorExit should derive from BaseException, not Exception Oops, forgot to mention this: I wouldn't be opposed to a different extension that would effectively let me accomplish the same goals... arbitrary exception filters. Imagine this: try: raise GeneratorExit except ExceptionFilter: # blah where ExceptionFilter is any object that can be tested for containment. Perhaps implemented like this: class ExceptionFilter(object): def __init__(self): self.includes = set() self.excludes = set() self.include = self.includes.add self.exclude = self.excludes.add def __contains__(self, exc): return any(isinstance(exc, cls) for cls in self.includes) and \ not any(isinstance(exc, cls) for cls in self.excludes) ImvuExceptionFilter = ExceptionFilter() ImvuExceptionFilter.include(Exception) ImvuExceptionFilter.exclude(GeneratorExit) Then, our code could just "catch" ImvuExceptionFilter. This type of extension would be backwards compatible with the current except (FooError, BarError) tuple syntax. I've never hacked on CPython itself, so I don't know what kind of changes there would be involved, but if there is sufficient pushback against making GeneratorExit derive from BaseException, I think this is a fine alternative. Thoughts? Chad Chad Austin wrote: > Hi Terry, > > Thank you for your feedback. Responses inline: > > Terry Reedy wrote: >> "Chad Austin" wrote in message >> news:46CA0EFE.6020103 at imvu.com... >> || try: >> | result = yield chatGateway.checkForInvite({'userId': userId}) >> | logger.info('checkForInvite2 returned %s', result) >> >> would not >> except GeneratorExit: >> solve your problem? > > Yes, we could add an "except GeneratorExit: raise" clause to every place > we currently catch Exception, but I feel like this is one of those > things where it's hard to get it right in all places and also hard to > cover with unit tests. Instead, we'll have subtle bugs where finally > clauses don't run because the GeneratorExit was swallowed. > > Also, SystemExit and KeyboardInterrupt were made into BaseExceptions for > the same reasons as I'm giving. (As I understand it, anyway.) > >> | except Exception: >> >> Such catchalls are known to be prone to catch too much >> and are therefore not encouraged ;-). >> As in 'use at your own risk'. >> Guido encourages specific catches just for the reasons you give here. > > More below: > >> There was a *long* discussion of the current 2.5 exception hierarchy on >> pydev. Search either python.org's or gmane's archive if you want to pursue >> this. But I expect the people involved would say much the same as above. > > I've actually read the background on the exception hierarchy (and agree > with it all), especially other suggestions that GeneratorExit derive > from BaseException. As I understand it, Guido's objections are threefold: > > 1) The previous "generators as coroutines" examples were too > theoretical: I've wanted GeneratorExit to derive from BaseException for > months now, but didn't write this proposal until I actually wrote code > that failed in the presence of task cancellation. > > 2) You should avoid catching everything with except Exception: I think > that's too idealistic. Just do a search for try: except: through > publicly available Python. :) Sometimes, you really _do_ want to catch > everything. When you're making a network request that involves > xmlrpclib, urllib2, httplib, etc. you don't actually care what the error > was. (Well, except that the exceptions are submitted for automated > analysis.) Similarly, when loading a cache file with pickle, I don't > care what went wrong, because it's not critical and should not be turned > into a crash for the user. (We automatically report exceptions that > bubble into the main loop as crashes.) > > 3) If GeneratorExit escapes from the generator somehow and gets raised > in the main loop, then it will bubble out of the application like > SystemExit and KeyboardInterrupt would: I think this argument is > somewhat specious, because I can't imagine how that would happen. You'd > have to store exceptions in your generator and explicitly bubble them > out somehow. Our crash handling has to specially handle > KeyboardInterrupt and SystemExit anyway, since there are currently > non-Exception exceptions, such as strings and custom classes that forgot > to derive from Exception, that should count as crashes. > > I personally can't think of any cases where I would _want_ to handle > GeneratorExit. I just want finally: and with: clauses to do the right > thing when a task is cancelled. Anyway, I haven't yet encountered any > serious bugs due to this yet... I'm just worried that if a task is > holding some resource and blocking on something, then the resource won't > get released. If this really does come up, then I do have a little bit > of python + ctypes that replaces GeneratorExit with ImvuGeneratorExit > (deriving from BaseException), but that's not very appealing. > > Thanks again, > -- Chad Austin http://imvu.com/technology From: Asun Friere <afriere at yahoo.co.uk> To: python-list at python.org Date: Tue, 21 Aug 2007 00:41:59 -0700 Subject: Re: Newbee Question Oh well since a few solutions have already been posted I thought I might add another, just so you at the very least you have to do some work making up your mind which one to choose. Using an incremental approach just to be different ... from decimal import Decimal normal = Decimal('0.04') over = Decimal('1.40) def calcStopPay (stops) : pay = Decimal('0.00') while stops : incr = normal if stops < 23 else over pay += incr stops -= 1 return pay #testing: for x in range(50) : print "Stop pay for %s stops: $%s" % (x, calcStopPay(x)) From: Ron Garret <rNOSPAMon at flownet.com> To: python-list at python.org Date: Tue, 21 Aug 2007 00:42:45 -0700 Subject: Re: Is there a way to change the default string encoding? In article , Peter Otten <__peter__ at web.de> wrote: > If all else fails there's > > >>> sys.setdefaultencoding("latin1") > >>> "Andre\xe9 Ramel".decode() > u'Andre\xe9 Ramel' > > but that's an evil hack, you should rather talk to the maintainer of the > offending code to update it to accept unicode. Yes, but I need to hack around it until I can get it fixed. Thanks! rg From: Fabio Z Tessitore <fabioztessitore at libero.it> To: python-list at python.org Date: 21 Aug 2007 07:44:46 GMT Subject: Re: Is there a way to change the default string encoding? Il Mon, 20 Aug 2007 18:44:39 -0700, Ron Garret ha scritto: > Is there a way to change the default string encoding ... Dive Into Python. Section 9 on http://diveintopython.org/xml_processing/ unicode.html That will help. Bye Fabio From: Asun Friere <afriere at yahoo.co.uk> To: python-list at python.org Date: Tue, 21 Aug 2007 00:51:45 -0700 Subject: Re: Newbee Question On Aug 21, 5:41 pm, Asun Friere wrote: > over = Decimal('1.40) oops, that should of course be: over = Decimal('1.40') From: Peter Otten <__peter__ at web.de> To: python-list at python.org Date: Tue, 21 Aug 2007 09:49:56 +0200 Subject: Re: Is there a way to change the default string encoding? Ron Garret wrote: > In article , > Peter Otten <__peter__ at web.de> wrote: > >> If all else fails there's >> >> >>> sys.setdefaultencoding("latin1") >> >>> "Andre\xe9 Ramel".decode() >> u'Andre\xe9 Ramel' >> >> but that's an evil hack, you should rather talk to the maintainer of the >> offending code to update it to accept unicode. > > Yes, but I need to hack around it until I can get it fixed. Oops, the snippet above omits the actual hack. It should be >>> import sys >>> reload(sys) >>> sys.setdefaultencoding("latin1") >>> "Andre\xe9 Ramel".decode() u'Andre\xe9 Ramel' Peter From: Asun Friere <afriere at yahoo.co.uk> To: python-list at python.org Date: Tue, 21 Aug 2007 00:54:53 -0700 Subject: Re: Newbee Question On Aug 21, 5:51 pm, Asun Friere wrote: > On Aug 21, 5:41 pm, Asun Friere wrote:> over = Decimal('1.40) > > oops, that should of course be: > over = Decimal('1.40') oh boy ... and it should also be normal = Decimal('0.40') I really need to test before posting ... From: Dennis Lee Bieber <wlfraed at ix.netcom.com> To: python-list at python.org Date: Tue, 21 Aug 2007 00:57:39 -0700 Subject: Re: yet another indentation proposal On Mon, 20 Aug 2007 04:51:06 GMT, James Stroud declaimed the following in comp.lang.python: > What's wrong with just saying the current indent level? I'd much rather > hear "indent 4" than "tab tab tab tab". > Well... the latter doesn't require a Python aware vocalizer... Though yes... something that would report on repeated "whitespace" would be nicer... "four-tabs" vs "32-spaces" -- Wulfraed Dennis Lee Bieber KD6MOG wlfraed at ix.netcom.com wulfraed at bestiaria.com HTTP://wlfraed.home.netcom.com/ (Bestiaria Support Staff: web-asst at bestiaria.com) HTTP://www.bestiaria.com/ From: Dennis Lee Bieber <wlfraed at ix.netcom.com> To: python-list at python.org Date: Tue, 21 Aug 2007 00:57:39 -0700 Subject: Re: datetime in microseconds On Mon, 20 Aug 2007 07:58:42 -0700, mroeloffs at gmail.com declaimed the following in comp.lang.python: > microsecs -= 31536000000000 # -1 Year There is no "year 0", one goes from 1 BC to AD 1 > microsecs -= 1123200000000 # -13 Days (magic?) Sounds like the conversion from Julian to Gregorian calendars... I wonder what would result if one converted your microseconds into fraction days, and fed that to a JD to calendar conversion. -- Wulfraed Dennis Lee Bieber KD6MOG wlfraed at ix.netcom.com wulfraed at bestiaria.com HTTP://wlfraed.home.netcom.com/ (Bestiaria Support Staff: web-asst at bestiaria.com) HTTP://www.bestiaria.com/ From: Dennis Lee Bieber <wlfraed at ix.netcom.com> To: python-list at python.org Date: Tue, 21 Aug 2007 00:57:39 -0700 Subject: Re: Newbee Question On Mon, 20 Aug 2007 07:51:10 -0700, kyosohma at gmail.com declaimed the following in comp.lang.python: > On Aug 20, 9:23 am, "HD1956" wrote: > > This is probably a simple code. I am a truck driver who gets paid by > > stops and cases. I am trying to figure out how to code my stop pay. I > > get 40 cents per stop up to 22 stops, and $1.40 per stops after that. > > def calc(num): > if num < 23: > return 0.4 * num > else: > overtime = num - 22 > x = 0.4 * 22 > x += overtime * 1.4 > return x > > # Use your own brain next time > > Mike pay = min(num, 22) * 0.4 + max(num-22, 0) * 1.4 -- Wulfraed Dennis Lee Bieber KD6MOG wlfraed at ix.netcom.com wulfraed at bestiaria.com HTTP://wlfraed.home.netcom.com/ (Bestiaria Support Staff: web-asst at bestiaria.com) HTTP://www.bestiaria.com/ -- http://mail.python.org/mailman/listinfo/python-list --------------------------------- Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games. --------------------------------- Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070821/a05c9962/attachment.html> From jeff.fw at gmail.com Wed Aug 29 10:33:28 2007 From: jeff.fw at gmail.com (Jeff) Date: Wed, 29 Aug 2007 14:33:28 -0000 Subject: Creating a multi-tier client/server application In-Reply-To: <46d57888$0$295$426a74cc@news.free.fr> References: <1188360460.838635.186930@w3g2000hsg.googlegroups.com> <7xbqcqhqbw.fsf@ruckus.brouhaha.com> <46d54ed8$0$429$426a34cc@news.free.fr> <1188393925.007952.313110@r29g2000hsg.googlegroups.com> <46d57888$0$295$426a74cc@news.free.fr> Message-ID: <1188398008.538820.21960@d55g2000hsg.googlegroups.com> > You could explore something like a custom-made GUI client app > communicating thru the http protocol with a web-server app. http is just > a protocol, and it doesn't necessarily imply using html and a browser... > IIRC, some GUI toolkits uses XML description files for the UI. That, or something similar, may be what I do. It would mean, however, developing my own method for transferring objects across the network, which, as far as I can tell, is what things like Pyro are supposed to take care of. > > 3) Easier to "lock down" who's using the program by only > > installing it on certain machines. > > Not a very reliable security scheme IMHO !-) You are 100% correct. That will most certainly *not* be the only means of security. There will be user authentication against a central LDAP server, SSL for all connections, and possibly IP address based blocking as well. I need to clarify what I meant (I didn't want to bore everyone with the tedious details)--while this system will mostly be used by supervisors/managers, the employees will also be using it to sign into their shifts. The managers want the employees to only be able to sign in from designated machines, while at the same time they want them to be able to look up their schedules from a web interface, but *not* use that to sign in. That wasn't the best point, but I think there's something to be said of the *perceived* security of desktop vs. web apps. > Extreme Programming doesn't mean "no preparation", and makes heavy use > of use cases. Of course you need to have some - hopefully accurate - > functional specs. The point was mostly along the lines of "don't try to > have full-featured detailed design before you start coding, because > chances are it will be wrong". > > > Hopefully, the amount of planning will be somewhere in between that > > and the bureaucratic nightmare of documenting up front what each > > module, class and function will do. > > Which would be totally non-sensical. I don't believe anyone on earth > could come up with such a thing - done right - *before* the application > is written. I'm not looking to layout how the GUI should look, or even how individual parts of it should work. What I need to do, though, is write very detailed specs with my clients on the data that will be used, and plan out as thoroughly as possible the architecture of the project as far as tiers and such. I don't have much choice in this aspect, sadly. But, in my experience, the more detail (and agreement on those details) I have up front, the less painful the rest of the process will be. Thanks again! From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Aug 28 15:36:15 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 28 Aug 2007 21:36:15 +0200 Subject: localhost, ?! References: <fb1id4$kpp$1@localhost.localdomain> Message-ID: <5jjbpfF3sm4m7U2@mid.individual.net> Boris Ozegovic wrote: > At job: > urllib2.urlopen("http://localhost") > raise BadStatusLine(line), after half a minute. Looks like name resolving problems. > urllib2.urlopen("http://127.0.0.1") > HTTP Error 503: Service Unavailable, immediately. Definitely a problem with the web server (503 means "service unavailable"). > Anybody have slightest clue wthat is going on? :-/ Try using wireshark or a similar tool to see what's going on on protocol level. Regards, Bj?rn -- BOFH excuse #103: operators on strike due to broken coffee machine From srikrishnamohan at gmail.com Thu Aug 2 08:13:27 2007 From: srikrishnamohan at gmail.com (km) Date: Thu, 2 Aug 2007 17:43:27 +0530 Subject: beginner in python In-Reply-To: <aa405c1f0708020425w12407dcfldb78540d19aa4990@mail.gmail.com> References: <aa405c1f0708020425w12407dcfldb78540d19aa4990@mail.gmail.com> Message-ID: <f4cc03640708020513v7f2804cfucabef3b6fbb0c35b@mail.gmail.com> Hi pls redefine ur problem. I donot understand what u wanted to accomplish . is it that u wanted to check and represent the redundant entry numbers as one entry or is it with the isoform id as a single entry and without considering other data like start and stop ? also observe that when u consider the whole line in the data file, they are all unique - there is no redundancy. KM ----------------------------------------------------------- On 8/2/07, Beema shafreen <beema.shafreen at gmail.com> wrote: > > Hi everybody , > I am a beginner in python, > I have to fetch the redundant entries from a file, > > code: > > import re > L = [] > fh = open('ARCHITECTURE_MAIN.txt', 'r') > for line in fh.readlines(): > data =line.strip() > # splitted = data.split('#') > L.append(data) > fh.close() > > > M=L > for x in L: > x = x.split('#') > for y in M: > y = y.split('#') > x_data = x[0],x[1],x[2],x[3] > #print x_data > y_data = y[0],y[1],y[2],y[3] > #print y_dat > if x_data[0] == y_data[0]: > print x_data > > > i get the result as a tupule, > the text file which has datas separated by hash > entry#isoform#start#stop# i have to check upto this > > 00250_1#ARCH_104#61#89#Literature#9224948#00250#### > 00250_1#ARCH_104#97#126#Literature#9224948#00250#### > 00250_1#ARCH_104#139#186#Literature#9224948#00250#### > 00251_1#ARCH_463#7#59#SMART##00251#### > 00251_1#ARCH_463#91#121#SMART##00251#### > 00251_1#ARCH_463#251#414#SMART##00251#### > 00251_1#ARCH_463#540#624#SMART##00251#### > 00252_1#ARCH_474#1#21#Literature#8136357#00252#### > 00252_1#ARCH_393#481#501#Literature#8136357#00252#### > 00252_1#ARCH_463#523#553#SMART##00252#### > 00253_1#ARCH_82#37#362#SMART##00253#### > 00253_1#ARCH_54#365#522#SMART##00253#### > 00253_1#ARCH_104#589#617#SMART##00253#### > 00253_1#ARCH_104#619#647#SMART##00253#### > 00253_1#ARCH_104#684#712#SMART##00253#### > 00254_1#ARCH_82#27#352#SMART##00254#### > 00254_1#ARCH_54#355#510#SMART##00254#### > 00254_1#ARCH_104#576#604#SMART##00254#### > 00254_1#ARCH_104#606#634#SMART##00254#### > 00254_1#ARCH_104#671#699#SMART##00254#### > 00255_1#ARCH_82#56#425#SMART##00255#### > 00255_1#ARCH_54#428#582#SMART##00255#### > 00255_1#ARCH_104#696#724#SMART##00255#### > > > > > can you suggest me ,what are the improvement i have to make in the above > code > regards > shafreen > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070802/6801ca9a/attachment.html> From steve at holdenweb.com Thu Aug 16 17:42:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 16 Aug 2007 17:42:11 -0400 Subject: Pass by reference or by value? In-Reply-To: <496954360708161402x58faba47x7a6eae6e68f81d4@mail.gmail.com> References: <496954360708161402x58faba47x7a6eae6e68f81d4@mail.gmail.com> Message-ID: <fa2gbe$uq7$1@sea.gmane.org> Robert Dailey wrote: > Hi, > > I previously created a topic named "Pass by reference or by value" where > I inquired on how python's function parameters work. I received a lot of > nice responses, however I'm still confused on the topic. Note that I > come from a C++ background to Python, so any comparisons to C++ would be > very helpful. > > I ran a few tests. There's two tests in particular I wanted to show you > guys: > ------------------------------------------------------------------------------------------------ > myvar = [] > > def changeme( param ): > param.append( "blah" ) > print param > > changeme( myvar ) > > print myvar > > The above code yields the following output: > ['blah'] > ['blah'] > > This means that the list passed in was modified by the function. > ------------------------------------------------------------------------------------------------ > Now test case 2: > > myvar = 4 > > def changeme( param ): > param = 5 > print param > > changeme( myvar ) > > print myvar > > The above code yields the following output: > 5 > 4 > > This means that the integer passed in was NOT modified by the function. > ------------------------------------------------------------------------------------------------ > > Between these two tests, both types passed in are mutable objects. I'm > having trouble figuring out what mandates an object to be changed from > within a function versus not. What is happening in test case 2 to cause > it to not be modified? > > Thanks for reading guys. Hopefully one day I'll understand this lol. > The first thin to realise is that all Python names are just bindings to values. In C++ terms you can think of them all as pointers. De-referencing is automatic when a value is to be retrieved. >>> def changeme( param ): ... param = 3 ... print param ... >>> myvar = [] >>> changeme(myvar) 3 >>> myvar [] >>> In this case there is no attempt to mutate the argument, the argument name is simply bound to another value. Since the argument is a name local to the function, this does not result in any change outside the function. In this case the argument is bound to a mutable value, so the call to append mutates the object (a list) referenced by the argument. Unlike C++ and similar languages a variable does not hold a value, it holds a pointer to a value. When a list is passed as a function argument the reference to the list is copied into the argument. Does this help at all? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From coxy1 at netspace.net.au Sat Aug 11 16:21:04 2007 From: coxy1 at netspace.net.au (Tony) Date: Sun, 12 Aug 2007 06:21:04 +1000 Subject: SUCK my HUSBAND'S CUM from my CUNT Message-ID: <20070811202122.F21781341EE@mail.netspace.net.au> -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070812/ea4f0090/attachment.html> From gdonald at gmail.com Sat Aug 11 18:26:14 2007 From: gdonald at gmail.com (Greg Donald) Date: Sat, 11 Aug 2007 17:26:14 -0500 Subject: I am giving up perl because of assholes on clpm -- switching to Python In-Reply-To: <496954360708111500k6764d019p7cbf74b1df399b94@mail.gmail.com> References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> <Lc1186058698244350x8ae3b4c@earth.podro.com> <496954360708111500k6764d019p7cbf74b1df399b94@mail.gmail.com> Message-ID: <15e66e4e0708111526u541bccacoc834a1e51815f233@mail.gmail.com> On 8/11/07, Robert Dailey <rcdailey at gmail.com> wrote: > I had this very same problem with the doxygen mailing list... doxygen is > such a great tool but full of assholes in their mailing list. I'm not defending any assholes you may have ran into, but I find the thing to do is only ask questions in such a way that no one can possibly have a reason to be an asshole. http://catb.org/~esr/faqs/smart-questions.html -- Greg Donald http://destiney.com/ From arkanes at gmail.com Thu Aug 30 16:38:14 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 30 Aug 2007 15:38:14 -0500 Subject: gc.garbage In-Reply-To: <1188505827.505656.243400@z24g2000prh.googlegroups.com> References: <1188467173.708043.44800@w3g2000hsg.googlegroups.com> <46D692FC.4030805@v.loewis.de> <1188498335.633506.90050@q4g2000prc.googlegroups.com> <mailman.157.1188499024.28954.python-list@python.org> <1188505827.505656.243400@z24g2000prh.googlegroups.com> Message-ID: <4866bea60708301338k5066a908s7e9944ebdc1b3765@mail.gmail.com> On 8/30/07, 7stud <bbxx789_05ss at yahoo.com> wrote: > On Aug 30, 12:36 pm, "Chris Mellon" <arka... at gmail.com> wrote: > > On 8/30/07, 7stud <bbxx789_0... at yahoo.com> wrote: > > > > > On Aug 30, 3:50 am, "Martin v. L?wis" <mar... at v.loewis.de> wrote: > > > > > gc.set_debug(gc.DEBUG_LEAK) > > > > > print gc.garbage > > > > > > > --output:-- > > > > > [] > > > > > gc: uncollectable <Dog 0x56e10> > > > > > gc: uncollectable <Cat 0x56e30> > > > > > gc: uncollectable <dict 0x58270> > > > > > gc: uncollectable <dict 0x43e40> > > > > > > gc.garbage is filled only after these messages > > > > are printed, not before. You need to add an explicit > > > > call to gc.collect() if you want to see what > > > > uncollectable garbage you have. > > > > > > Regards, > > > > Martin > > > > > Hi, > > > > > Thanks for the response. I had a cut and paste error in my reply, so > > > here it is again with the corrections... > > > > > Now, if I run the code: > > > > > ------------ > > > import gc > > > > > class Cat(object): > > > def __del__(): > > > pass > > > > > class Dog(object): > > > def __del__(): > > > pass > > > > > def some_func(): > > > the_dog = Dog() > > > the_cat = Cat() > > > the_dog.cat = the_cat > > > the_cat.dog = the_dog > > > > > some_func() > > > > > gc.set_debug(gc.DEBUG_LEAK) > > > gc.collect() > > > print gc.garbage > > > ----------- > > > > > I get this output: > > > > > ---------- > > > gc: uncollectable <Dog 0x56e10> > > > gc: uncollectable <Cat 0x56e30> > > > gc: uncollectable <dict 0x58300> > > > gc: uncollectable <dict 0x43e40> > > > [<__main__.Dog object at 0x56e10>, <__main__.Cat object at 0x56e30>, > > > {'cat': <__main__.Cat object at 0x56e30>}, {'dog': <__main__.Dog > > > object at 0x56e10>}] > > > ----------- > > > > > Why are there two entries in the list for each uncollectable > > > object(same addresses)? Also, I haven't bound the names "cat" or > > > "dog" anywhere in my program. What do those names mean in the list? > > > > Read your output carefully! > > > > gc.garbage is a list of objects. The objects are printed just as they > > would be anywhere else in Python. You've got the dog object, the cat > > object, and the __dict__ of each instance. > > > > > > Ah. I missed the braces inside the list, but I still don't understand > where the names "cat" and "dog" come from. > What happens when you print a dictionary? > > > DEBUG_SAVEALL is set, then all unreachable objects will be added to > > this list rather than freed." > > What is the definition of an "unreachable object"? If I add the > following: > Anything that the gc would have collected. > ----- > y = Cat() > del y > ----- > > That object doesn't make it into gc.garbage. Because it's already dead. In your previous code, you made dog and cat unreachable by virtue of making them a refcycle. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Mon Aug 20 09:22:28 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 20 Aug 2007 09:22:28 -0400 Subject: Where we need to use Python ? References: <1187596936.136499.200280@l22g2000prc.googlegroups.com> Message-ID: <fac4jr$im7$1@sea.gmane.org> <gperumal at gmail.com> wrote in message news:1187596936.136499.200280 at l22g2000prc.googlegroups.com... | And Is it a interpreted language or a programming language | It comes in which category Python is an algorithm programming language. The CPython implementation of the langauge compiles Python to proprietary byte code and then interprets the byte code. The Jython implementation compiles to javacode which is then handled however by a Java runtime. The IronPython implementation compiles to the .NET language handled by the .NET runtime. The PyPy implementation acts similarly to CPython, I believe, but can also compile a subset of the language to C or other low level languages that can be compiled to object code. There are other projects that compile subsets, possible with additional instructions to the compiler. Do visit www.python.org and take a look around. The documentation section has a tutorial that will give an experienced programmer a good overview in just a few hours. tjr From carsten at uniqsys.com Sat Aug 4 19:38:07 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 04 Aug 2007 19:38:07 -0400 Subject: Encoding DeprecationWarning In-Reply-To: <1186267926.233392.238460@w3g2000hsg.googlegroups.com> References: <1186254427.792114.173170@q75g2000hsh.googlegroups.com> <mailman.1623.1186255457.22759.python-list@python.org> <1186267419.999613.209480@q75g2000hsh.googlegroups.com> <1186267926.233392.238460@w3g2000hsg.googlegroups.com> Message-ID: <1186270687.3272.9.camel@localhost.localdomain> On Sat, 2007-08-04 at 15:52 -0700, oliver at obeattie.com wrote: > On Aug 4, 11:43 pm, "oli... at obeattie.com" <oli... at obeattie.com> wrote: > > >>> from wt.lib.misc_lists import all_countries > > > > __console__:1: DeprecationWarning: Non-ASCII character '\xc3' in file / > > Django/wt/../wt/lib/misc_lists.py on line 141, but no encoding > > declared; seehttp://www.python.org/peps/pep-0263.htmlfor details > > OK, well; no matter. Perhaps I should try actually reading the article > it recommended Right, that's why I asked you to post the full warning message, to get you to take another look at it. Mission accomplished ;) -- Carsten Haese http://informixdb.sourceforge.net From tommy.nordgren at comhem.se Sat Aug 25 16:18:29 2007 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Sat, 25 Aug 2007 22:18:29 +0200 Subject: Any python Module for generating DocBook? Message-ID: <C15CC70F-4403-4F08-80EC-9A9EEB549C50@comhem.se> Do anyone on this list know of a Python module for generating DocBook programlisting elements for programming language source code merked with special comments. I want to write a programming book, and want to mark significant lines in the source code for reference. My DocBook processing software xmlint, xsltproc, and fop, don't support numbering lines, when including source files via <xi:include parse="text" ... ------ What is a woman that you forsake her, and the hearth fire and the home acre, to go with the old grey Widow Maker. --Kipling, harp song of the Dane women Tommy Nordgren tommy.nordgren at comhem.se From tjreedy at udel.edu Fri Aug 3 15:11:00 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 3 Aug 2007 15:11:00 -0400 Subject: (no) fast boolean evaluation ? missing NOT References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl><mailman.1545.1186095368.22759.python-list@python.org><1186096979.397596.36640@e16g2000pri.googlegroups.com> <eb4fb$46b2f7a6$d443bb3a$21643@news.speedlinq.nl> Message-ID: <f8vuk5$glb$1@sea.gmane.org> "Stef Mientki" <S.Mientki-nospam at mailbox.kun.nl> wrote in message news:eb4fb$46b2f7a6$d443bb3a$21643 at news.speedlinq.nl... | John Machin wrote: | So now I'm left with just one question: | for bitwise operations I should use &, |, ^ | for boolean operations I should use and, or, xor | but after doing some test I find strange effects: | >>> A = 4 | >>> B = 5 | >>> A and B | 5 >>> B and A 4 | >>> A & B | 4 | >>> A or B | 4 >>> B or A 5 | >>> A | B | 5 | | So if I use the bitwise operation on integers, | "and" changes into (bitwise) "or" and vise versa. No, you hypnotised yourself by generalizing from insufficient data. Repeat experiment with, for instance, 3 and 4 instead of 4 and 5. Then 3&4 = 0, 3|4 = 7. tjr From vasudevram at gmail.com Fri Aug 31 14:13:05 2007 From: vasudevram at gmail.com (vasudevram) Date: Fri, 31 Aug 2007 18:13:05 -0000 Subject: Joining Big Files In-Reply-To: <1188157393.234494.62500@w3g2000hsg.googlegroups.com> References: <1188035844.616831.205350@i38g2000prf.googlegroups.com> <1188090939.364787.296630@r34g2000hsd.googlegroups.com> <1188092913.645157.15370@o80g2000hse.googlegroups.com> <1188139515.349468.315290@q5g2000prf.googlegroups.com> <1188157393.234494.62500@w3g2000hsg.googlegroups.com> Message-ID: <1188583985.639319.297240@r23g2000prd.googlegroups.com> On Aug 27, 12:43 am, mcl <mcl.off... at googlemail.com> wrote: > All, > > Thank you very much. > > As my background is much smaller memory machines than today's giants - > 64k being abigmachine and 640k being gigantic. I get very worried > about crashing machines when copying or editingbigfiles, especially > in a multi-user environment. > > Mr Knuth - that brings back memories. I rememeber implementing some > of his sort routines on a mainframe with 24 tape units and an 8k drum > and almost eliminating one shift per day of computer operator time. > > Thanks again > > Richard I can imagine ... though I don't go back that far. Cool ... Vasudev From nick at craig-wood.com Wed Aug 29 06:30:08 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 29 Aug 2007 05:30:08 -0500 Subject: Haskell like (c:cs) syntax References: <fb25uh$gl9$1@online.de> <4866bea60708281512q31635803x1b025274c94caf7e@mail.gmail.com> <mailman.86.1188340264.28954.python-list@python.org> Message-ID: <slrnfdahld.aai.nick@irishsea.home.craig-wood.com> Erik Jones <erik at myemma.com> wrote: > front, last = l[:len(l) - 1], l[len(l) - 1] Normally written as front, last = l[:-1], l[-1] -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From grante at visi.com Wed Aug 29 10:22:42 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 29 Aug 2007 14:22:42 -0000 Subject: self extracting zipefile (windows) and (standard module) zipefile References: <1188388421.010643.19050@50g2000hsm.googlegroups.com> <1188393907.080206.246270@y42g2000hsy.googlegroups.com> Message-ID: <13db09i6rrnjc22@corp.supernews.com> On 2007-08-29, Hyuga <hyugaricdeau at gmail.com> wrote: >> I try to read (and extract) some "self extracting" zipefiles >> on a Windows system. The standard module zipefile seems not to >> be able to handle this. [...] > > First of all, there's really no such thing as a "self > extracting zipefile". Perhaps there isn't "really such a thing," but that's the commonly used name for the type of file the OP is dealing with. > [...] You'll have to execute it--there's no way you can > operate on it like a normal zip file. Executing the file is a huge, huge security risk. Other zip tools (e.g. the "unzip" utility for Linux) seem know how to work with self-extracting zipfiles. Unfortunately there are multiple slightly different zip formats along with mutlple "self-extracting zip file" formats. Nonetheless, I've never run across one I couldn't unzip without executing it. On Linux, I'd probably just try exec'ing the "unzip" program. Another option is to search through the file from the beginning looking for whatever signature matches the beginning of a "normal" zip file. The self-extracting zipfiles that I've dissected are just an executable image concatenated with a "normal" zipfile. If you just start searching from the beginning of the file, it's simple to find the actual zip data and copy it into a separate file which then can be unzipped like any other plain zipfile. I haven't done that for many years since the normal zip tools that I use can operate on self-extracting files. -- Grant Edwards grante Yow! NEWARK has been at REZONED!! DES MOINES has visi.com been REZONED!! From pachiburke at gmail.com Mon Aug 20 06:40:30 2007 From: pachiburke at gmail.com (pachiburke at gmail.com) Date: Mon, 20 Aug 2007 03:40:30 -0700 Subject: best GUI library for vector drawing program In-Reply-To: <1187357244.883516.79840@j4g2000prf.googlegroups.com> References: <1187357244.883516.79840@j4g2000prf.googlegroups.com> Message-ID: <1187606430.924141.134800@g4g2000hsf.googlegroups.com> On Aug 17, 3:27 pm, chewie54 <dfabrizi... at gmail.com> wrote: > What would be the best cross-platform GUI library to use for a vector > based CAD program ( something like Visio on Windows ) WxWidgets, > Tk, PyQt, Java Swing, Java SWT,???? I need the capibility to > draw and edit in a window that looks like a page of paper so WYSIWYG > is very important, and I need to save the drawings in vector based > file formats like PS, EPS, SVG, as well as image formats like jpg, > png, and gif. Also, the images need to be high resolution so that > they can be pasted into various other programs in Windows OS, and > Linux OS, and the Mac OS. You could use pythoncad (www.pythoncad.org) as a base and develop it further, or even contract its main developer to expand its features to fulfill your needs and improve it. It's based on the GTK+ toolkit, written in python and has scripting capabilities. IMHO, it's the most promising free CAD effort around though even if it's not as mature as QCad. You could use it in commercial applications as long as you comply with the GPL, or the author agrees to dual license it for you, but it would be very welcome if the improvements are avaliable for all users. Regards, Rafael From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Aug 6 03:58:04 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 06 Aug 2007 09:58:04 +0200 Subject: Best programs written completly in Python In-Reply-To: <1186338373.738163.257890@o61g2000hsh.googlegroups.com> References: <vh8bb3h0bpc9c3f1v50tchb0sejr7j7smt@4ax.com> <1186338373.738163.257890@o61g2000hsh.googlegroups.com> Message-ID: <46b6d47b$0$647$426a74cc@news.free.fr> markacy a ?crit : > On 5 Sie, 12:14, Franz Steinh?usler <franz.steinhaeus... at gmx.at> > wrote: >> Hello NG, >> >> wWhat are the best programs in your opinion, written entirly >> in pyhton, divided into categories like: >> a) Games >> b) Utilities/System >> c) Office >> d) Web/Newsreader/Mail/Browser >> ... >> >> I don't want to start a long thread, if a site of such >> an discussion already exists, a link will be enough. >> >> Many thanks in advance! >> >> -- >> Franz Steinhaeusler > > I guess, that gentoo's portage is (almost?) entirely written in > python. IIRC, yes (or perahps does it use a couple bash scripts too). > The same is with Zope/Plone "Zope/Plone" makes two distinct applications : the web application server Zope, and the CMS Plone. > (Web category), though I know, > that Zope has some parts of code written in C. Yes. Mostly for low-level parts that couldn't be done in pure Python, at least by the time they were written. > Django? Then mention CherryPy, Turbogears and Pylons (and *quite* a lot of web frameworks FWIW) too !-) Oh, and yes, there's Twisted too... From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Aug 8 07:55:11 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 08 Aug 2007 13:55:11 +0200 Subject: Seek the one billionth line in a file containing 3 billion lines. References: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> <f9bp75$vbq$03$1@news.t-online.com> Message-ID: <5htp8sF3m6tquU1@mid.individual.net> Peter Otten wrote: > n = 10**9 - 1 > assert n < sys.maxint > f = open(filename) > wanted_line = itertools.islice(f, n, None).next() > > should do slightly better than your implementation. It will do vastly better, at least in memory usage terms, because there is no memory eating range call. Regards, Bj?rn -- BOFH excuse #31: cellular telephone interference From heikki at osafoundation.org Fri Aug 10 00:47:40 2007 From: heikki at osafoundation.org (Heikki Toivonen) Date: Thu, 09 Aug 2007 21:47:40 -0700 Subject: wxPython before MainLoop In-Reply-To: <13bl9a75laqcm70@corp.supernews.com> References: <13bl9a75laqcm70@corp.supernews.com> Message-ID: <6a6dnfbbFJNzcCbbnZ2dnUVZ_oudnZ2d@comcast.com> [david] wrote: > I'd like to refresh the display before I start the main loop. We have this kind of situation in Chandler, where we display and update the splash screen before we enter MainLoop. 1. Create app object http://lxr.osafoundation.org/source/chandler/Chandler.py#080 2. During app object creation, in OnInit, put up splash screen and update it http://lxr.osafoundation.org/source/chandler/application/Application.py#433 3. The splash screen refresh is basically: draw new stuff, self.Layout(), self.Update(), wx.Yield() http://lxr.osafoundation.org/source/chandler/application/Application.py#1421 3. Start MainLoop http://lxr.osafoundation.org/source/chandler/Chandler.py#086 -- Heikki Toivonen From aahz at pythoncraft.com Thu Aug 23 16:48:14 2007 From: aahz at pythoncraft.com (Aahz) Date: 23 Aug 2007 13:48:14 -0700 Subject: Problems with threading in embedded Python References: <mailman.2129.1187387690.22759.python-list@python.org> Message-ID: <fakrqe$mcu$1@panix3.panix.com> In article <mailman.2129.1187387690.22759.python-list at python.org>, Nico Blodow <nicoblodow at gmx.net> wrote: > >I hope this hasn't been brought up before, but if it did i missed it, >so bear with me please :) anyway, i'm trying to embed Python into a C >program. A sample python syript i want to run is as follows: Looks like nobody here wants to touch this, maybe try http://mail.python.org/mailman/listinfo/capi-sig -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From sturlamolden at yahoo.no Fri Aug 10 11:08:31 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 10 Aug 2007 08:08:31 -0700 Subject: High performance binary data In-Reply-To: <1186705614.728812.284460@j4g2000prf.googlegroups.com> References: <1186705614.728812.284460@j4g2000prf.googlegroups.com> Message-ID: <1186758511.702475.281150@i38g2000prf.googlegroups.com> On Aug 10, 2:26 am, Steve <steve.mo... at gmail.com> wrote: > I want to ready binary data from a udp socket effeciently as possible > in python. I know of the struct package but do people have any tips > when dealing with binary data in python? Is there a library or api > that is faster when dealing with binary data. I am looking for a any > one with experience or ideas on the subject. Pointers any one? I would recommend NumPy for manipulating binary data. It is primarily intended for numerics, but it is excellent for dealing with any kind of binary data as well. It can handle mutable buffers of any kind of integer or float, as well as arrays of C-like structs (record arrays in numpy). You can typecast and create subarrays without copying any data, simply by providing a new "view" into the buffer. You can also get access to strided subsections without creating copies. And it is very fast. www.scipy.org From carsten at uniqsys.com Wed Aug 29 22:33:32 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 29 Aug 2007 22:33:32 -0400 Subject: Is LOAD_GLOBAL really that slow? In-Reply-To: <aac2c7cb0708291823h15e3f675mbeae9ecf37d653b6@mail.gmail.com> References: <aac2c7cb0708291823h15e3f675mbeae9ecf37d653b6@mail.gmail.com> Message-ID: <1188441212.3251.39.camel@localhost.localdomain> On Wed, 2007-08-29 at 19:23 -0600, Adam Olsen wrote: > It seems a common opinion that global access is much slower than local > variable access. However, my benchmarks show a relatively small > difference: > > ./python -m timeit -r 10 -v -s 'x = [None] * 10000 > def foo(): > for i in x: > list; list; list; list; list; list; list; list; list; list' 'foo()' > 10 loops -> 0.0989 secs100 loops -> 0.991 secs > raw times: 0.999 0.985 0.987 0.985 0.985 0.982 0.982 0.982 0.981 0.985 > 100 loops, best of 10: 9.81 msec per loop > > ./python -m timeit -r 10 -v -s 'x = [None] * 10000 > def foo(): > mylist = list > for i in x: > mylist; mylist; mylist; mylist; mylist; mylist; mylist; mylist; > mylist; mylist' 'foo()' > 10 loops -> 0.0617 secs > 100 loops -> 0.61 secs > raw times: 0.603 0.582 0.582 0.583 0.581 0.583 0.58 0.583 0.584 0.582 > 100 loops, best of 10: 5.8 msec per loop > > So global access is about 70% slower than local variable access. To > put that in perspective, two local variable accesses will take longer > than a single global variable access. > > This is a very extreme benchmark though. In practice, other overheads > will probably drop the difference to a few percent at most. Not that > important in my book. Your comparison is flawed, because the function call and the inner for loop cause a measurement offset that makes the locals advantage seems smaller than it is. In the interest of comparing the times for just the local lookup versus just the global lookup, I think the following timings are more appropriate: $ python2.5 -mtimeit -r10 -s"y=42" -s"def f(x): pass" "f(42)" 1000000 loops, best of 10: 0.3 usec per loop $ python2.5 -mtimeit -r10 -s"y=42" -s"def f(x): x" "f(42)" 1000000 loops, best of 10: 0.331 usec per loop $ python2.5 -mtimeit -r 10 -s"y=42" -s"def f(x): y" "f(42)" 1000000 loops, best of 10: 0.363 usec per loop There is no loop overhead here, and after subtracting the function call overhead, I get 31 nanoseconds per local lookup and 63 nanoseconds per global lookup, so local lookups are just about twice as fast as global lookups. True, whether this difference is significant does depend on how many name lookups your code makes and how much else it's doing, but if you're doing a lot of number crunching and not a lot of I/O, the difference might be significant. Also, even if using local names is only slightly faster than using globals, it's still not slower, and the resulting code is still more readable and more maintainable. Using locals is a win-win scenario. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From http Fri Aug 31 06:11:25 2007 From: http (Paul Rubin) Date: 31 Aug 2007 03:11:25 -0700 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <1188373707.922509.205070@g4g2000hsf.googlegroups.com> Message-ID: <7xps149foy.fsf@ruckus.brouhaha.com> Michele Simionato <michele.simionato at gmail.com> writes: > > http://archive.eiffel.com/doc/manuals/technology/contract/ariane/page... > > That paper contains only a good think: a link to the contrarian view > http://home.flash.net/~kennieg/ariane.html#s3.1.5 I like the contrarian article much better than the Eiffel sales pitch. From programmer.py at gmail.com Tue Aug 28 10:50:14 2007 From: programmer.py at gmail.com (programmer.py at gmail.com) Date: Tue, 28 Aug 2007 14:50:14 -0000 Subject: wxpython:how to minimize to taskbar In-Reply-To: <1188310247.587456.103440@i13g2000prf.googlegroups.com> References: <1188310247.587456.103440@i13g2000prf.googlegroups.com> Message-ID: <1188312614.463169.93890@k79g2000hse.googlegroups.com> On Aug 28, 9:10 am, Jimmy <mcknight0... at gmail.com> wrote: > I'm kinda newbie to python and wxPython. Now I'm confronting a thorny > problem: how can I make my program minimize to the taskbar > represented as an ico, and when there is some message from network > coming, it will pop out? Warning. I have not tested this. I happened to have some old code that would iconify to the system tray. Here's what I think you need to do. (If it does not work, just yell and I'll try to hack something together for you.) Inside the ctor of your mainframe, you'll need to construct a wxTaskBarIcon (I derive from it). This is my code that derives from wxTaskBarIcon. The comments should give you a good idea of how this thing works. I *think* this will shove the icon in the system tray, even if you're not `iconified` -- so only create it if you want to show up in the system tray. ## My wxTaskBarIcon derived object... """ Taskbar icon. Not much functionality here, not even a menu. In the future, this will be a good place to allow dclient functionality from the systray. """ from wx import TaskBarIcon, EVT_TASKBAR_LEFT_DCLICK class ddTaskBarIcon(TaskBarIcon): def __init__(self, icon, tooltip, frame): TaskBarIcon.__init__(self) self.SetIcon(icon, tooltip) self.frame = frame # # At the very least, restore the frame if double clicked. Add other # events later. # self.Bind(EVT_TASKBAR_LEFT_DCLICK, self.on_left_dclick) def on_left_dclick(self, e): if self.frame.IsIconized(): self.frame.Iconize(False) if not self.frame.IsShown(): self.frame.Show(True) self.frame.Raise() def CreatePopupMenu(self): """ Override with menu functionality, later. """ return None Next is where I use it in my wxFrame derived object. This is the code in my ctor. # ddTaskBarIcon is defined above... self.trayicon = ddTaskBarIcon(self.frame_icon, "Dap Daemon", self) # Handle the window being `iconized` (err minimized) self.Bind(wx.EVT_ICONIZE, self.on_iconify) # This is the event handler referenced in the ctor above def on_iconify(self, e): """ Being minimized, hide self, which removes the program from the taskbar. """ self.Hide() So how does this work? Well, the ddTaskBarIcon (err, i realize this is a misnomer) is constructed, which puts an icon in the system tray. The icon has a dbl-click event handler that will `raise` and show the window if necessary. The iconify event handler will hide the window if a minimize event occurs. This keeps the window from showing up in the windows taskbar. Thats the magic. YMMV. FWIW - the code I reference is over 5 years old and still runs with wxPython 2.8ish... Kudos to Robin Dunn and crew. Great job. jw From tjreedy at udel.edu Wed Aug 15 00:15:03 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 15 Aug 2007 00:15:03 -0400 Subject: FM synthesis using Numpy References: <3657a8860708141639l7e90ebdoe844691627152e40@mail.gmail.com> Message-ID: <f9tulg$sau$1@sea.gmane.org> "Joost Molenaar" <dzjoost at gmail.com> wrote in message news:3657a8860708141639l7e90ebdoe844691627152e40 at mail.gmail.com... | I'm trying to build a simple FM synthesizer in Python. As a beginner, | I take 'FM synthesizer' to | mean: "using a sine wave to control the frequency of another sine wave." If you don't get an answer here, try the numpy/scipy list(s) From mbrown at phys.ksu.edu Sun Aug 19 17:53:38 2007 From: mbrown at phys.ksu.edu (yagyala) Date: Sun, 19 Aug 2007 14:53:38 -0700 Subject: desperately in need of a tool Message-ID: <1187560418.339131.283470@i38g2000prf.googlegroups.com> Hi. I recently started working for a company that has just implemented its first set of software standards. So far, so good. Here's the problem: one of those standards is that the comments for each routine must indicate every other routine that it calls. As I try to keep my routines small, and factor out methods alot, this can lead to an enormous ammount of extra typing. I really, really, really don't want to do this by hand. Does anyone know of a tool that could do this for me, or at least a tool that can tell what other routines a given routine calls that I could program against? (Preferably something that works under pydev, but I'm not going to be choosy.) I'm sure some will wonder about the reasoning of this standard. The company primarily has experience writing scientific alogorythms which can get rather long. It makes a bit more sense to document all routines called for a very long routine, but for short routines that primarily call other routines, as most mine do, well.... Thanks. From steven.bethard at gmail.com Tue Aug 14 18:41:07 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 14 Aug 2007 16:41:07 -0600 Subject: A dumb question about a class In-Reply-To: <1187129117.868507.151980@d55g2000hsg.googlegroups.com> References: <mailman.1887.1186955369.22759.python-list@python.org> <TqSdnWYzVdWvGCLbnZ2dnUVZ_saknZ2d@comcast.com> <mailman.1888.1186957809.22759.python-list@python.org> <euCdnYM4sfSHFiLbnZ2dnUVZ_gadnZ2d@comcast.com> <mailman.1891.1186963290.22759.python-list@python.org> <tvKdnY5tf7bSXyLbnZ2dnUVZ_rCtnZ2d@comcast.com> <1187129117.868507.151980@d55g2000hsg.googlegroups.com> Message-ID: <h6KdnWbvz_MZsl_bnZ2dnUVZ_hKdnZ2d@comcast.com> thattommyhallll at gmail.com wrote: > Also, does anyone know if there is some magic that makes > i in some_set > loads faster than > i in some_list It's not magic, per se. It's really part of the definition of the data type. Lists are ordered, and are slow when checking containment. Sets are unordered and are quick when checking containment. When you execute ``i in some_list``, Python searches through the list starting at index 0, and stopping when it sees ``i`` or hits the end. In computational terms, this is O(n), meaning that for a list of length n, you'll take an amount of time proportional to n. When you execute ``i in some_set``, Python hashes ``i``, and checks the set to see if it contains anything with the same hash value. On the average (given the Python implementation) it is probably checking at most one or two values. In computational terms, this is O(1), meaning that on the average it only takes a constant amount of time. So if you have code doing ``if foo in bar`` more than once, you *really* should be using a set for ``bar``. STeVe From markacy at gmail.com Thu Aug 16 03:53:59 2007 From: markacy at gmail.com (markacy) Date: Thu, 16 Aug 2007 07:53:59 -0000 Subject: python socket usage In-Reply-To: <mailman.2046.1187250159.22759.python-list@python.org> References: <mailman.2046.1187250159.22759.python-list@python.org> Message-ID: <1187250839.541105.60900@r29g2000hsg.googlegroups.com> On 16 Sie, 09:42, O uz Yar mtepe <comp.... at gmail.com> wrote: > Is it possible to send a data object like a tuple or a list in socket > programming? If so how? It seems with socket module it is only possible to > send strings. > > -- > O uz Yar mtepehttp://www.yarimtepe.com/en Hi Oguz, why don't you make a string out of your tuple, or list, send it via socket and make a tuple/list again? >>> x = (1,2,3,4,5,6,7,) >>> type(x) <type 'tuple'> >>> y = str(x) >>> type(y) <type 'str'> >>> print y (1, 2, 3, 4, 5, 6, 7) >>> z = tuple(y) >>> type(z) <type 'tuple'> >>> Cheers, Marek From bdesth.quelquechose at free.quelquepart.fr Wed Aug 22 01:30:50 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 22 Aug 2007 07:30:50 +0200 Subject: How to replace a method in an instance. In-Reply-To: <mailman.258.1187971369.32294.python-list@python.org> References: <mailman.258.1187971369.32294.python-list@python.org> Message-ID: <46cf2789$0$423$426a74cc@news.free.fr> Steven W. Orr a ?crit : > In the program below, I want this instance to end up calling repmeth > whenever inst.m1 is called. As it is now, I get this error: > > Hello from init > inst = <__main__.CC instance at 0x402105ec> > Traceback (most recent call last): > File "./foo9.py", line 17, in ? > inst.m1() > TypeError: repmeth() takes exactly 1 argument (0 given) > > > #! /usr/bin/python > def repmeth( self ): > print "repmeth" > > class CC: > def __init__( self ): > self.m1 = repmeth > print 'Hello from init' > > def m1 ( self ): > print "m1" > > inst = CC() > inst.m1() > > TIA # using old-style classes: import new def repmeth( self ): print "repmeth" class CC: def __init__( self ): self.m1 = new.instancemethod(repmeth, self, type(self)) print 'Hello from init' def m1 ( self ): print "m1" inst = CC() inst.m1() # using newstyle classes: def repmeth( self ): print "repmeth" class CC(object): def __init__( self ): self.m1 = repmeth.__get__(self, type(self)) print 'Hello from init' def m1 ( self ): print "m1" inst = CC() inst.m1() HTH From jstroud at mbi.ucla.edu Thu Aug 16 22:20:04 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 16 Aug 2007 19:20:04 -0700 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: <1187311999.880853.135780@j4g2000prf.googlegroups.com> References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> <fa2m4s$k1g$1@daisy.noc.ucla.edu> <1187311999.880853.135780@j4g2000prf.googlegroups.com> Message-ID: <fa30kk$f8n$1@zinnia.noc.ucla.edu> beginner wrote: > On Aug 16, 6:21 pm, James Stroud <jstr... at mbi.ucla.edu> wrote: >>I'm afraid you've asked a non sequiter: >> >>euler 40% cat test.pl >> >>$a=$b->{"A"} ||={} ; >>print "$a\n" ; >> >>$b->{"B"} = 0 ; >>$a=$b->{"B"} ||={} ; >>print "$a\n" ; >> >>$b->{"X"} = 15 ; >>$a=$b->{"X"} ||={} ; >>print "$a\n" ; >> >>euler 41% perl test.pl >>HASH(0x92662a0) >>HASH(0x926609c) >>15 > > It is not supposed to be used this way. > $b is supposed to be a hash-table of hash-table. If a key exists in > $b, it points to another hash table. The $a=$b->{"A"} ||={} pattern is > useful when you want to add records to the double hash table. > > For example, if you have a series of records in the format of (K1, K2, > V), and you want to add them to the double hash-table, you can do > $a=$b->{K1} || ={} > $a->{K2}=V That's great, but the perl code you provided does not behave identically to the python code you provided, so your requirments were not well stated. (Does my annoyance with perl and its ugly syntax show here?) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From http Fri Aug 31 03:37:20 2007 From: http (Paul Rubin) Date: 31 Aug 2007 00:37:20 -0700 Subject: Creating a multi-tier client/server application References: <1188360460.838635.186930@w3g2000hsg.googlegroups.com> <7xbqcqhqbw.fsf@ruckus.brouhaha.com> <46d54ed8$0$429$426a34cc@news.free.fr> <1188393925.007952.313110@r29g2000hsg.googlegroups.com> <7xy7ft4fqg.fsf@ruckus.brouhaha.com> <1188479584.073309.297770@x40g2000prg.googlegroups.com> <1188498543.184255.213940@i13g2000prf.googlegroups.com> Message-ID: <7xejhkkvdb.fsf@ruckus.brouhaha.com> Jeff <jeff.fw at gmail.com> writes: > Granted. But what I will be writing really will take a lot of extra > work to get even close to the level of usability needed on the web vs. > a desktop app. And I'll try not to write a crappy GUI ;-) OK. In the discussion with Chris, one factor that came up is how much time users will spend in front of the app and the amount of data they'll physically enter. If it's a lot, that weighs in favor of a desktop app. If it's not much, then maybe some gain in UI responsiveness isn't worth the downside of a client installation. > Sorting certainly doesn't have to be done on the server side--in fact, > in most cases I can think of where it would be useful for this app, it > wouldn't have to be--in which case it's more responsive. Certainly > exporting, importing and printing can all be done through the web-- > I've done this plenty of times. But there is a huge amount of > flexibility (and, in the case of printing, guaranteed style/quality/ > layout) to be gained on the desktop. This I don't understand at all. How is the least bit of flexibility or style or quality guarantees gained by a desktop app? If you want fancy formatting, just use Reportlab to generate a pdf on the server and send it to the browser. > All that said, I am most likely going to go with a desktop > application. In reality, I will have to do whatever my client wants. > Thank you *very* much for all of your input--one of the first things I > have to do is make them a list of the pros and cons of web vs. desktop > apps--and this will help a lot. Yes, that sounds like a good idea. > vanrpeter-whatever: Thanks for the support :-) What did you use for > networking? What ORMs did you try (or did you skip them altogether?) Have you ever written a serious GUI app before? I've never done any really fancy ones, but even the relatively simple ones I've done have turned out to be far more time consuming than I expected. Have you done much concurrent programming, either with threads or something like twisted? You're going to have to do that to keep your gui responsive, so you might put that on your list of things to study (in addition to networking and databases). From nospam at invalid.com Sat Aug 18 18:22:45 2007 From: nospam at invalid.com (Jack) Date: Sat, 18 Aug 2007 15:22:45 -0700 Subject: Parser Generator? Message-ID: <abKdnVoQMu2o7FrbnZ2dnUVZ_gqdnZ2d@comcast.com> Hi all, I need to do syntax parsing of simple naturual languages, for example, "weather of London" or "what is the time", simple things like these, with Unicode support in the syntax. In Java, there are JavaCC, Antlr, etc. I wonder what people use in Python? Antlr also has Python support but I'm not sure how good it is. Comments/hints are welcome. From beema.shafreen at gmail.com Sat Aug 18 01:58:23 2007 From: beema.shafreen at gmail.com (Beema shafreen) Date: Sat, 18 Aug 2007 11:28:23 +0530 Subject: swapping Message-ID: <aa405c1f0708172258k7402e9b2ld44e24b093b5ea7b@mail.gmail.com> hi everbody, i have a file with data: fhl1 fkh2 dfp1 chk1 mal3 alp14 mal3 moe1 mal3 spi1 mal3 bub1 mal3 bub3 mal3 mph1 mal3 mad3 hob1 nak1 i have written code to check the redudant pairs my code: data = [] data1 = [] fh = open('sheet1','r') for line in fh: if line not in data: data.append(line) else: print line fh.close() fh1 = open('sheet2','r') for line1 in fh1: if line1 not in data1: data1.append(line1) else: print line1 fh1.close() result: klp5 bub1 apn1 apn2 but i have do the same for the revere ,to check the result like this for eg: apn2 apn1 what is the concept to do this regards shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070818/c85e2d57/attachment.html> From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Aug 29 09:45:49 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 29 Aug 2007 15:45:49 +0200 Subject: Creating a multi-tier client/server application In-Reply-To: <1188393925.007952.313110@r29g2000hsg.googlegroups.com> References: <1188360460.838635.186930@w3g2000hsg.googlegroups.com> <7xbqcqhqbw.fsf@ruckus.brouhaha.com> <46d54ed8$0$429$426a34cc@news.free.fr> <1188393925.007952.313110@r29g2000hsg.googlegroups.com> Message-ID: <46d57888$0$295$426a74cc@news.free.fr> Jeff a ?crit : > Thanks for the quick responses. > > I was really hoping to avoid an entirely web-based app, for a few > reasons, not the least of which is that I've been working almost > entirely on web apps for the past few years, and I am getting mighty > sick of it. A lot of that is due to the language (PHP, which I have > since grown to hate) I had to use. I've worked on a site for my self > in Python (using Pylons, actually--which is excellent) which was > vastly easier and more fun. But I'd really like to try something > different. > > Now, of course, that's not enough reason to force such a thing onto my > clients (when I say clients, I mean the ones that are paying for this, > but they're really within my same department, so they actually have > working technical knowledge.) Some reasons for them would be (in no > particular order): 1) More responsive and user-friendly interfaces, You could explore something like a custom-made GUI client app communicating thru the http protocol with a web-server app. http is just a protocol, and it doesn't necessarily imply using html and a browser... IIRC, some GUI toolkits uses XML description files for the UI. (snip) > 3) Easier to "lock down" who's using the program by only > installing it on certain machines. Not a very reliable security scheme IMHO !-) (snip) > Which leads me to the discussion of planning: (snip) > This system will be used, often, to figure out how much people should > be paid (and then interface directly with the University's payroll > system), and store lovely things like SSNs, and will also have to have > somewhat crazy business logic to track when hourly workers are > eligible for raises, if they took enough training classes, etc. There > are a lot of people with a stake in this system, and I will need to > work with them very closely on how this should work, and they sure as > hell don't want any surprises. My manager even wants use cases (if > you've never had to deal with use cases, consider yourself a lucky, > lucky person) which I am going to attempt to argue as that is even > going *too* far. > > So, long story short (too late), no Extreme Programming for me. Extreme Programming doesn't mean "no preparation", and makes heavy use of use cases. Of course you need to have some - hopefully accurate - functional specs. The point was mostly along the lines of "don't try to have full-featured detailed design before you start coding, because chances are it will be wrong". > Hopefully, the amount of planning will be somewhere in between that > and the bureaucratic nightmare of documenting up front what each > module, class and function will do. Which would be totally non-sensical. I don't believe anyone on earth could come up with such a thing - done right - *before* the application is written. From ehsan.khoddam at gmail.com Fri Aug 3 17:41:52 2007 From: ehsan.khoddam at gmail.com (Ehsan) Date: Fri, 03 Aug 2007 14:41:52 -0700 Subject: regexp problem in Python Message-ID: <1186177312.117581.129910@d55g2000hsg.googlegroups.com> I want to find "http://www.2shared.com/download/1716611/e2000f22/ Jadeed_Mlak14.wmv?tsid=20070803-164051-9d637d11" or 3gp instead of wmv in the text file like this : <html> ""some code"" function reportAbuse() { var windowname="abuse"; var url="/abuse.jsp?link=" + "http://www.2shared.com/file/1716611/ e2000f22/Jadeed_Mlak14.html"; OpenWindow = window.open(url,windowname,'toolbar=no,scrollbars=no,resizable=no,width=500,height=500,left=50,top=50'); OpenWindow.focus(); } function startDownload(){ window.location = "http://www.2shared.com/download/1716611/ e2000f22/Jadeed_Mlak14.wmv?tsid=20070803-164051-9d637d11"; //document.downloadForm.submit(); } </script> </head> </html>http://www.2shared.com/download/1716611/e2000f22/ Jadeed_Mlak14.3gp?tsid=20070803-164051-9d637d11"sfgsfgsfgv I use this pattern : "http.*?\.(wmv|3gp).*"" but it returns only 'wmv' and '3gp' instead of "http://www.2shared.com/ download/1716611/e2000f22/Jadeed_Mlak14.wmv? tsid=20070803-164051-9d637d11" what can I do? what's wrong whit this pattern? thanx for your comments From Shawn at Milochik.com Mon Aug 20 10:58:39 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Mon, 20 Aug 2007 10:58:39 -0400 Subject: Newbee Question In-Reply-To: <1187621470.484615.7010@i13g2000prf.googlegroups.com> References: <mailman.15.1187620149.26576.python-list@python.org> <1187621470.484615.7010@i13g2000prf.googlegroups.com> Message-ID: <2dc0c81b0708200758h498ae58cu5915b4865a2112c5@mail.gmail.com> On 8/20/07, kyosohma at gmail.com <kyosohma at gmail.com> wrote: > On Aug 20, 9:23 am, "HD1956" <hd7... at hotmail.com> wrote: > > This is probably a simple code. I am a truck driver who gets paid by > > stops and cases. I am trying to figure out how to code my stop pay. I > > get 40 cents per stop up to 22 stops, and $1.40 per stops after that. > > def calc(num): > if num < 23: > return 0.4 * num > else: > overtime = num - 22 > x = 0.4 * 22 > x += overtime * 1.4 > return x > > # Use your own brain next time > > Mike > > -- > http://mail.python.org/mailman/listinfo/python-list > Mike, I wonder if we were both just duped into helping someone with their homework... Shawn From carsten at uniqsys.com Fri Aug 3 13:08:31 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 03 Aug 2007 13:08:31 -0400 Subject: Using cursor.callproc with zxJDBC In-Reply-To: <104F88F15D1E430B96FF79E35FE6B84D@VVA> References: <104F88F15D1E430B96FF79E35FE6B84D@VVA> Message-ID: <1186160911.3382.27.camel@dot.uniqsys.com> On Fri, 2007-08-03 at 17:31 +0100, Vaughan V Ashe wrote: > Hi > > We would like to use the store proc. We are using a postgreql > database. what we have working so far is: > > params = [4,4,2] > > curs.callproc("update_job_status",params) > > db.commit() > > #print db > > #print curs.description > > result = curs.fetchall() > > if result == 1: > > print "good one" > > else: > > print "shite" > > > > we are using the beta version of jython. Would be very happy to get a > response from you You haven't asked a question, and you're not describing what your problem is. I'm going to guess what your problem is: You're always getting the result "shite" regardless of whether the procedure worked or not. curs.fetchall() returns a list, which is never going to be equal to 1. If this doesn't help you, please describe what exactly your problem is. -- Carsten Haese http://informixdb.sourceforge.net From kmcneillie at softwarespecialists.com Thu Aug 30 12:06:40 2007 From: kmcneillie at softwarespecialists.com (Kelley McNeillie) Date: Thu, 30 Aug 2007 12:06:40 -0400 Subject: Please assist- Python Consultant needed for 3-6 month project Message-ID: <s6d6b2f3.092@server1.softwarespecialist.com> I am contacting you from a company called Software Specialists, an IT Placement Firm based in Pittsburgh, PA. We are prepared to make a donation to your organization if you could please help us out with a referral. We are looking for a python developer with web-based application experience. If you know of anyone, or if you would be able to post this opportunity on your site, I would greatly appreciate it. I am finding this skill pretty much impossible to identify locally, and I really would like to be able to assist my client with this position. I am just trying to be creative in my search, I hope I am reaching the right person with this request. If not, I apologize. Thank you in advance for any assistance you may be able to provide. Best Regards, Kelley McNeillie Software Specialists, Inc. 357 Northgate Drive Suite 10 Warrendale, PA 15086 724 933 6100 x 1105 724 933 6106 (F) kmcneillie at softwarespecialists.com www.softwarespecialists.com From van.lindberg at gmail.com Fri Aug 3 11:25:17 2007 From: van.lindberg at gmail.com (VanL) Date: Fri, 03 Aug 2007 10:25:17 -0500 Subject: Trying to find zip codes/rest example Message-ID: <f8vhct$3g6$1@sea.gmane.org> Hello, A couple months ago there was an example posted in a blog of a rest interface for validating zip codes. If I recall correctly, the backend validator was written in python. The validator demo page had a single text input; next to the text input would appear either a green check or a red X depending on whether the zip code was valid. On the backend, the explanation of the demo included a discussion of using HTTP status codes (200 for a valid zip, 406? for invalid) so that the service could be used from a console as well. I now cannot find this demo and the associated discussion. Does anybody remember this demo and where I might be able to find it? Thanks, VanL From zyzhu2000 at gmail.com Wed Aug 1 11:37:23 2007 From: zyzhu2000 at gmail.com (beginner) Date: Wed, 01 Aug 2007 15:37:23 -0000 Subject: Assertion in list comprehension Message-ID: <1185982643.001546.138180@e16g2000pri.googlegroups.com> Hi, Does anyone know how to put an assertion in list comprehension? I have the following list comprehension, but I want to use an assertion to check the contents of rec_stdl. I ended up using another loop which essentially duplicates the functions of list comprehension. It just look like a waste of coding and computer time to me. I just wish I could put the assertions into list comprehensions. x=[(rec_stdl[0].st/10000.0, rec_stdl[0].cl, rec_stdl[0].bb, rec_stdl[0].bo, rec_stdl[1].bb, rec_stdl[1].bo, rec_stdl[0].ex ) for rec_stdl in rec_by_ex if len(rec_stdl)==2 ] #duplicated loop if __debug__: for rec_stdl in rec_by_ex: l=len(rec_stdl) assert(l<=2 and l>0) if l==2: assert(rec_stdl[0].c=="C" and rec_stdl[1].c=="P") assert(rec_stdl[0].ex==rec_stdl[1].ex) assert(rec_stdl[0].st==rec_stdl[1].st) assert(rec_stdl[0].cp==rec_stdl[1].cp) Thanks, Geoffrey From sturlamolden at yahoo.no Thu Aug 2 19:46:54 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 02 Aug 2007 16:46:54 -0700 Subject: python 3.0, pywin32 and scipy In-Reply-To: <1186088014.008755.318660@e9g2000prf.googlegroups.com> References: <1186070475.659511.24130@q3g2000prf.googlegroups.com> <1186086609.231563.224090@x35g2000prf.googlegroups.com> <1186088014.008755.318660@e9g2000prf.googlegroups.com> Message-ID: <1186098414.116069.149000@z24g2000prh.googlegroups.com> On Aug 2, 10:53 pm, vml <victor.leb... at gmail.com> wrote: > I hope it will be possible to switch easily to python 3. But I need to > produce something as cheap as possible and I have no means ... Python 3k is not released yet. Why do you worry about compatibility in advance? Well, you are not the only one. I've heard this argument before, that's why I bother to write this response. Python 2.x will continue to work even after Python 3k is released. There will also be future releases of Python 2.x. Visual Basic .NET is not backwards compatible with VB6. But that does not stop you form using VB6 even today. VB6 is soon 10 years old, it was released in 1998. "Mainstream support" for VB6 ended on March 31, 2005. Extended support will end in March 2008. With Python 2.x this even less troublesome as the source code is available - it can be recompiled when needed! You cannot recompile VB6, still it lasted 10 years. If you can use VB6 ten years, you can use Python 2.x at least twice that long. That will give you twenty years to port your application to a newer version of Python. But then you probably don't care. I am sure the packages you mentioned will be ready for Python 3k by then. NumPy, SciPy, Matplotlib, etc. will be ported to Python 3k in due time. The Pywin32 code is autogenerated with SWIG. When support for Python 3k is added to SWIG (yes it will happen), there will be a Pywin32 for Python 3k as well. You don't have to fix something that works. Python 2.5.1 is what we have today, use it as much as you can. From bdesth.quelquechose at free.quelquepart.fr Thu Aug 2 10:05:43 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 02 Aug 2007 16:05:43 +0200 Subject: Case study: library class inheritance with property declarations In-Reply-To: <1186065365.546545.184840@i13g2000prf.googlegroups.com> References: <1186062582.975223.230270@g12g2000prg.googlegroups.com> <1186063694.311416.133390@i13g2000prf.googlegroups.com> <1186065365.546545.184840@i13g2000prf.googlegroups.com> Message-ID: <46b23c19$0$13518$426a74cc@news.free.fr> cdleary at gmail.com a ?crit : (snip) > Last post -- I swear. > > I failed to realize that it's all part of an extremely well defined > attribute resolution protocol, and handled via the descriptor > specification. Discussing descriptors was on the TODO list for the > type/class unification document, but there's a very fulfilling > explanation by Raymond Hettinger: http://users.rcn.com/python/download/Descriptor.htm > Also, the official doc is here: http://docs.python.org/ref/descriptors.html > > Maybe the documentation for the property builtin should make reference > to the descriptor specification? If nobody thinks this is silly, I'll > submit a documentation patch in a few days. What to say ? As an old-time pyton user (well... 7+ years now) and meta-programming addict, it's nothing new to me, but the fact that you didn't realize it is certainly a clear indication that documentation is not really up to date, so yes, submitting a patch is certainly a pretty good idea. > Sorry for the spam -- hope someone besides me learns from it! What's to be learned is mostly that we (the whole community) should take more care of the doc (which I never contributed FWIW, so I'm the first one that should feel in guilt here). From paul.faulstich at gmail.com Sun Aug 26 16:03:01 2007 From: paul.faulstich at gmail.com (paul) Date: Sun, 26 Aug 2007 13:03:01 -0700 Subject: pySerial in a daemon process Message-ID: <1188158581.316824.89360@k79g2000hse.googlegroups.com> I am writing a daemon process that reads data from the serial port / dev/ttyS0. I am using pyserial & the method for setting up a daemon described in "Chris' Python Page" (http://homepage.hispeed.ch/py430/ python/) on an Ubuntu linux pc. Everything works great EXCEPT... in the daemon script, there are two lines to change the uid & gid that the script runs as: os.setegid(10) os.seteuid(1000) If I comment these out, so that the daemon runs as root, then everything works fine. I can also manually run the script that the daemon process kicks off from my own id just fine. If I put these back in and try to run the daemon, the script fails when I try to connect to the serial port, with this error: serial.serialutil.SerialException: Could not open port: [Errno 13] Permission denied: '/dev/ttyS0' In my debugging I have tried setting the uid to my own uid, and the gid to a variety of different groups that I belong to. None of them work. I could certainly run the daemon as root, but I would rather not. What really confuses me is that if I manually run the script as myself (without using the daemon script), it connects fine, but when root uses os.seteuid() to my uid, it fails. What do I need to do to get this to work? Many thanks, Paul From max at alcyone.com Thu Aug 9 23:57:49 2007 From: max at alcyone.com (Erik Max Francis) Date: Thu, 09 Aug 2007 20:57:49 -0700 Subject: Puzzled by "is" In-Reply-To: <87zm1042f0.fsf@benfinney.id.au> References: <20070809194105.39BD11E400A@bag.python.org> <f9frbl$dps$1@sea.gmane.org> <mailman.1814.1186692638.22759.python-list@python.org> <87zm1042f0.fsf@benfinney.id.au> Message-ID: <3IOdndVSErSgfybbnZ2dnUVZ_sPinZ2d@speakeasy.net> Ben Finney wrote: > It's important to also realise that the language is *deliberately* > non-committal on whether any given value will have this behaviour; > that is, it's entirely left to the language implementation which > optimisation trade-offs to make, and the language user (that's you and > I) should *not* expect any particular behaviour to hold between > different implementations. Right. In the terminology of language standards, it is implementation defined. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis Only love is worth the risk -- Oleta Adams From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Aug 6 03:44:59 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 06 Aug 2007 09:44:59 +0200 Subject: (no) fast boolean evaluation ? In-Reply-To: <mailman.1575.1186158943.22759.python-list@python.org> References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> <cfb58d850708021619s298f69b9p3af86905d1695939@mail.gmail.com> <mailman.1551.1186099243.22759.python-list@python.org> <46b2e56b$0$18879$426a74cc@news.free.fr> <pan.2007.08.03.14.24.23.227662@REMOVE.THIS.cybersource.com.au> <46b35069$0$17822$426a74cc@news.free.fr> <mailman.1575.1186158943.22759.python-list@python.org> Message-ID: <46b6d16a$0$29273$426a74cc@news.free.fr> Ed Leafe a ?crit : > On Aug 3, 2007, at 11:57 AM, Bruno Desthuilliers wrote: > >> Sorry, I forgot to mention the language did not allow to have else & if >> in the same statement. IOW : >> >> if some_condition then >> do_sometehing >> else >> if some_other_condition then >> do_something_else >> else >> if yet_another_condition then >> do_yet_another_thing >> else >> if your_still_here then >> give_up('this language is definitively brain dead') >> end if >> end if >> end if >> end if > > Usually that's because the language provides a switch/case statement > construct. Err... You may have forgotten from lack of practice, but there are complex conditions that may not always be expressed using a switch/case... > If it does and you try to write the above code, it isn't the > language that's brain-dead! ;-) Lats time I checked, my brain was still alive. From garyjefferson123 at gmail.com Sat Aug 18 00:53:34 2007 From: garyjefferson123 at gmail.com (garyjefferson123 at gmail.com) Date: Sat, 18 Aug 2007 04:53:34 -0000 Subject: customizing a logging logger Message-ID: <1187412814.493872.325190@j4g2000prf.googlegroups.com> Suppose I have some sort of context variable that I want to appear in log messages. E.g.: logger = logging.getLogger("somelogger") class SomeOp: def __init__(self, ctx): self.ctx = ctx def method1(self): logger.info("%s: here's a message", self.ctx) What's the idiomatic way to abstract away the inclusion of self.ctx from the calls in logger.info() et al? Is there some way I can declare a @property def info(self): return logger.info but have it insert the '"%s: " % self.ctx' bit for me in one place instead of the dozens of places I currently do it in the class? Thanks, Gary From ldo at geek-central.gen.new_zealand Fri Aug 31 01:22:33 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 31 Aug 2007 17:22:33 +1200 Subject: Error handling in file generation (Pythonic way: with / decorators?) References: <1188377932.955314.104570@r29g2000hsg.googlegroups.com> <1188378461.388224.164030@50g2000hsm.googlegroups.com> Message-ID: <fb88e4$ev8$2@lust.ihug.co.nz> In message <1188378461.388224.164030 at 50g2000hsm.googlegroups.com>, xavim wrote: > This should read:: > > try: > (...) > except: > os.remove(dictpath) > raise Perhaps: try : (...) except : try : os.remove(dictpath) except : pass #end try raise #end try (Just in case.) From bj_666 at gmx.net Sat Aug 11 12:48:38 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Aug 2007 16:48:38 GMT Subject: How to change a PyObject passed to the C extension References: <1186850599.738739.195410@b79g2000hse.googlegroups.com> Message-ID: <5i67j5F3ml00gU3@mid.uni-berlin.de> On Sat, 11 Aug 2007 09:43:19 -0700, MD wrote: > I have a Python C extension which is passed a PyObject containing > an integer value. Is it possible to change this same PyObject so that > now the integer is of a different value? No it is not. Even if you poke around in the object ``struct`` this would have severe consequences for cached/shared objects. Just imagine: from your_module import bzzzt def f(): print 2 + 2 bzzzt(2) # This changes the value of 2 to 3. f() # This prints '6'! Ciao, Marc 'BlackJack' Rintsch From lisajones22 at gmail.com Tue Aug 14 02:32:40 2007 From: lisajones22 at gmail.com (Lisa Jones) Date: Mon, 13 Aug 2007 23:32:40 -0700 Subject: =?utf-8?B?4pa6RU5KT1kgZnJlZSBzYXRlbGxpdGUgdHYgb24geW91ciBwY+KXhA==?= Message-ID: <1187073160.240558.181780@x40g2000prg.googlegroups.com> The New Way To Enjoy Satellite TV on your PC! ? Watch all your favorite shows on your Computer from anywhere in the World! ? Save 1000's of $$$ over many years on cable and satellite bills ? Plus Get FREE Unlimited Downloads Movies, MP3s Music, etc !!! ? INSTANT DOWNLOAD For More Details: http://tvonpc.freeweb7.com From comedian.watchman at gmail.com Tue Aug 7 16:57:16 2007 From: comedian.watchman at gmail.com (Edward Blake) Date: Tue, 7 Aug 2007 16:57:16 -0400 Subject: Python FNV Hash Message-ID: <eae776d40708071357j416f666fj909b0e1a6c5f3af6@mail.gmail.com> Before I go through the work of wrapping the FNV hash source found on http://isthe.com/chongo/tech/comp/fnv/ I thought I would ask here to see if anyone already has an implementation of it available. I'm particularly interested in hash_64, the 64 bit Fowler/Noll/Vo-0 FNV-1a hash code. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070807/62fc470d/attachment.html> From sjoerd at intercue.nl Wed Aug 8 16:11:52 2007 From: sjoerd at intercue.nl (Sjoerd Op 't Land) Date: Wed, 08 Aug 2007 22:11:52 +0200 Subject: Stop a thread on deletion In-Reply-To: <mailman.1746.1186585827.22759.python-list@python.org> References: <f9ckqg$ghi$1@netlx020.civ.utwente.nl> <mailman.1746.1186585827.22759.python-list@python.org> Message-ID: <f9d82b$29t$1@netlx020.civ.utwente.nl> Dear Cris, Thanks a lot. This works! (What you didn't know, there was already such a 'proxy' object in the design, so it isn't the hack it looks ;).) Thanks again, Sjoerd Op 't Land Chris Mellon schreef: > On 8/8/07, Sjoerd Op 't Land <sjoerd at intercue.nl> wrote: >> Hello all, >> >> I'm using threading for generating video content. The trouble is how to >> kill the thread, because there are multiple (simultaneous) owners of a >> thread. Ideally, a flag would be set when the reference count of the >> thread becomes zero, causing the run() loop to quit. Example: >> >> import threading >> import time >> import gc >> >> class myThread(threading.Thread): >> def __init__(self): >> self.passedOut = threading.Event() >> threading.Thread.__init__(self) >> def __del__(self): >> self.passedOut.set() >> def run(self): >> i = 0 >> while not self.passedOut.isSet(): >> i += 1 >> print "Hi %d" % i >> time.sleep(0.25) >> >> >> a = myThread() >> a.start() >> time.sleep(2.5) >> a = None >> time.sleep(2.5) >> >> Unfortunately, this doesn't work. When I remove the while-loop, __del__ >> is called, actually. Appearantly there is still some reference to the >> thread while it is running. >> >> I tried gc.get_referrers(self), but it seems to need some parsing. I'm >> not sure how to implement that and I'm not sure whether it will work >> always or not. >> > > gc.get_referrers returns a list of object instances that hold a > reference to the object. The important one in this case is, of course, > the thread itself. The thread holds a reference to the run method > which (of course) requires a reference to the object. In other words, > a running thread cannot be refcounted to zero. You are going to need a > better method of handling your resources. > > Perhaps instead of holding a reference to the thread, they could hold > a reference to a proxy object: > > import threading > import time > import gc > import pprint > > class myThread(threading.Thread): > def __init__(self): > self.passedOut = threading.Event() > threading.Thread.__init__(self) > def run(self): > i = 0 > while not self.passedOut.isSet(): > i += 1 > print "Hi %d" % i > time.sleep(1) > print "stopped" > > > class ThreadProxy(object): > def __init__(self, proxy_for): > self.proxy_for = proxy_for > def __del__(self): > self.proxy_for.passedOut.set() > def start(self): > self.proxy_for.start() From hniksic at xemacs.org Sun Aug 12 14:50:33 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 12 Aug 2007 20:50:33 +0200 Subject: Fatest standard way to sum bytes (and their squares)? References: <NPmdnVwqHa74TyPbnZ2dnUVZ_uKpnZ2d@speakeasy.net> Message-ID: <87r6m8egee.fsf@mulj.homelinux.net> Erik Max Francis <max at alcyone.com> writes: > So far the fastest way I've found is using the `sum` builtin and > generators:: > > ordinalSum = sum(ord(x) for x in data) > ordinalSumSquared = sum(ord(x)**2 for x in data) For ordinalSum, using imap is almost twice as fast: $ python -m timeit -s 'data=[chr(x) for x in xrange(256)]' 'sum(ord(x) for x in data)' 10000 loops, best of 3: 92.4 usec per loop $ python -m timeit -s 'data=[chr(x) for x in xrange(256)]; from itertools import imap' 'sum(imap(ord, data))' 10000 loops, best of 3: 55.4 usec per loop Of course, that optimization doesn't work for the squared sum; using a lambda only pessimizes it. From zentraders at gmail.com Tue Aug 14 18:46:23 2007 From: zentraders at gmail.com (Zentrader) Date: Tue, 14 Aug 2007 15:46:23 -0700 Subject: What order does info get returned in by os.listdir() In-Reply-To: <gemini.jms7ay00fafcf00k8@jernic.by.invalid> References: <gemini.jms7ay00fafcf00k8@jernic.by.invalid> Message-ID: <1187131583.114731.279180@g12g2000prg.googlegroups.com> On Aug 14, 1:52 pm, Jeremy C B Nicoll <jer... at blueyonder.co.uk> wrote: > What order does info get returned in by os.listdir() ? > > I'm just starting to write python code, on an Win XP Pro machine. I've got > various directories which, when I look at them in Win XP, sorted by name, I > see in order, eg: > > ~prefixed file .txt > A.txt > B.txt > ... > Z.txt > > ie, XP seems to think that files with a "~" as their first character are > sorted ahead of A. > > When I use os.listdir() to return that list of leaf values, I do seem to get > them in alphabetical order, A before B before C etc, but the ~-prefixed ones > are returned after the Z-prefixed files rather than before the A-ones. > > I was wondering why... > > -- > Jeremy C B Nicoll - my opinions are my own. I think that os.listdir() returns file names in chronological order, that is in the order they were created on disk. If there is any sorting done it will be in ASCII order. All data is stored as a number so it is sorted that way. ord("~")= 126, and ord("Z")=90 so it makes sense that "~" is after "Z". From steve at holdenweb.com Wed Aug 8 11:59:54 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 08 Aug 2007 11:59:54 -0400 Subject: This bit of code hangs Python Indefinitely In-Reply-To: <f9ci85$1t3$2@solaris.cc.vt.edu> References: <f9ch45$ku$1@solaris.cc.vt.edu> <5htvm3F3md0abU3@mid.uni-berlin.de> <f9ci85$1t3$2@solaris.cc.vt.edu> Message-ID: <f9cp9o$sq3$1@sea.gmane.org> brad wrote: > Marc 'BlackJack' Rintsch wrote: > >> Why did you put an upper bound to the queue? > > For clarity. Explicit is better than implicit, right? In our design, the > queue should only have x number of things, so why not show that? Other > than that, the limit is arbitrary and is not needed. Yes, but you are asking a bit more of Queue.Queue than its design is intended to provide. Normally a limit on the input side is used to allow the scheduling of a consumer thread that will remove items, thus allowing the producer to restart. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From jocago at gmail.com Wed Aug 8 14:11:19 2007 From: jocago at gmail.com (jocago) Date: Wed, 08 Aug 2007 11:11:19 -0700 Subject: Launch file from Python In-Reply-To: <1186594611.490723.251870@m37g2000prh.googlegroups.com> References: <1186594137.971393.128780@57g2000hsv.googlegroups.com> <1186594611.490723.251870@m37g2000prh.googlegroups.com> Message-ID: <1186596679.600526.172640@r34g2000hsd.googlegroups.com> On Aug 8, 1:36 pm, kyoso... at gmail.com wrote: > On Aug 8, 12:28 pm, joc... at gmail.com wrote: > > > Good afternoon from someone who is trying to learn Python. > > > I would like to launch an app from within a Python script. From the > > examples I have found, I should be able to do this with os.system. > > > I use this: > > os.system("xplanet-1.2.0/xplanet.exe -fontsize 24 -label -target earth > > -lat 33.65 -lon -84.42 -radius 40 -num_times 1 -tmpdir .") > > This is copied directly from the .bat file that launches the xplanet > > app. It works there. > > > and get this: > > 1 > > > Can someone fill me in? Thanks. > > That's just the exit status or run status, if I recall correctly. I > think 0 (i.e. False) means it didn't run properly and anything else is > True, or ok. Something like that. Technically speaking, you should > probably switch to using the subprocess module as it is replacing that > os module's functionality:http://www.python.org/doc/2.4/lib/module-subprocess.html > > This thread also discusses it somewhat:http://www.velocityreviews.com/forums/t348777-python-doc-problem-exam... > > Mike The application, however, never runs. I'll give the sub-process a shot. Thanks. From greg at cosc.canterbury.ac.nz Tue Aug 7 22:33:01 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 08 Aug 2007 14:33:01 +1200 Subject: Something in the function tutorial confused me. In-Reply-To: <mailman.1726.1186537161.22759.python-list@python.org> References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <slrnfbe1fd.n4.horpner@FIAD06.norwich.edu> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <slrnfbeofu.20s.horpner@FIAD06.norwich.edu> <1186424693.529497.217040@w3g2000hsg.googlegroups.com> <46B8626A.2070303@bigfoot.com> <mailman.1726.1186537161.22759.python-list@python.org> Message-ID: <5hsoi3F3mlni2U1@mid.individual.net> Steve Holden wrote: > OK. The difference is that [] is a mutable value, while None is > immutable. No, it's not. It has nothing to do with mutability vs immutability. The difference is that in the first version the expression [] is evaluated only *once*, when the function is defined. Therefore there is just one list object getting re-used. In the second version, the expression [] gets evaluated *each* time the function is called, creating a new list object each time. > When the function starts out with None as y's value any assignment to y > causes it to reference a different value (since None is immutable). You're confused. Assigning to y simply causes it to reference whatever object is being assigned. This is always true, regardless of what y was referencing before. To see that the immutability of None has nothing to do with it, try the following version: def f(x, y = []): y = [] y.append(x) print y f(17) f(42) Try to work out what it will do, then try it, and see if you understand why it does what it does. -- Greg From aleax at mac.com Wed Aug 15 11:55:11 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 15 Aug 2007 08:55:11 -0700 Subject: closing StringIO objects References: <slrnfc67ml.27o.horpner@FIAD06.norwich.edu> Message-ID: <1i2vpnc.wv6c3n1r76qzvN%aleax@mac.com> Neil Cerutti <horpner at yahoo.com> wrote: > The documentation says the following about StringIO.close: > > close( ) > Free the memory buffer. > > Or else... what? Or else the memory buffer sticks around, so you can keep calling getvalue as needed. I believe the freeing will happen anyway, eventually, if and when the StringIO instance is garbage collected (just like, say, a file object's underlying fd gets closed when the file object is garbage collected), but relying on such behavior is often considered a dubious practice nowadays (given the existence of many Python implementations whose GC strategies differ). Alex From musiccomposition at gmail.com Sun Aug 19 22:18:07 2007 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 20 Aug 2007 02:18:07 -0000 Subject: Python question (PyNoob) In-Reply-To: <3uOdnbA4Bc27fFXbnZ2dnUVZ8vidnZ2d@bt.com> References: <3uOdnbA4Bc27fFXbnZ2dnUVZ8vidnZ2d@bt.com> Message-ID: <1187576287.194843.266600@q3g2000prf.googlegroups.com> On Aug 19, 7:33 pm, Anonymous <no.re... at here.com> wrote: > I have exp with C/C++ (and a few other langs). I want to use Python to > start doing the ff: > > 1). Data Munging (text processing) - instead of Perl > 2). Automating my build process > 3). (Possibly) some web data retrieval jobs > > Can anyone point me to resurces/possibly scripts that can get me up to > speed (to do these 3 things) ASAP, without having to learn the basics of > programming? I think if you've chosen Python as a language to use for these things, you could invest some time in learning the language. It is after all very easy to learn and you just have to do it once and many of your programming task will be taken care of. From Jameson.Quinn at gmail.com Tue Aug 28 19:51:16 2007 From: Jameson.Quinn at gmail.com (Jameson.Quinn at gmail.com) Date: Tue, 28 Aug 2007 16:51:16 -0700 Subject: "Try:" which only encompasses head of compound statement In-Reply-To: <87fy24fdgf.fsf@benfinney.id.au> References: <1188250535.607963.42540@22g2000hsm.googlegroups.com> <87wsvgfszm.fsf@benfinney.id.au> <13d7898odj2g19b@corp.supernews.com> <87fy24fdgf.fsf@benfinney.id.au> Message-ID: <1188345076.396437.111160@w3g2000hsg.googlegroups.com> Those are some good responses, but I think they focused a little too much on the specifics of my example - especially the 'print' statement. In real life, I want to set some return values to sensible defaults if the file doesn't exist, but I want the errors from inside the block to trickle up as normal. And yes, I can easily use a temporary variable for the open file, but it really seems to me that this defeats the purpose of the 'with' statement - if this were something more dangerous than a file, I'd feel mighty leery of having it in a temporary variable outside a 'with' for even a moment. So, the options are: -temporary variable - could this EVER be more dangerous than the with statement (KeyboardInterrupt which is later caught and handled?) -'tunnel' internal exceptions past the try by wrapping them in a TunnelException and then unwrapping them with a containing try block. The second looks like a hack to me, and the first still feels dangerous. So I still think that some syntax here would be a bit more than just sugar. From robert.rawlins at thinkbluemedia.co.uk Fri Aug 3 09:56:43 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 3 Aug 2007 14:56:43 +0100 Subject: Replacing _xmlplus.dom.minidom with xml.dom.minidom In-Reply-To: <1186148352.647143.68890@l70g2000hse.googlegroups.com> References: <1186148352.647143.68890@l70g2000hse.googlegroups.com> Message-ID: <00e701c7d5d6$20069b50$6013d1f0$@rawlins@thinkbluemedia.co.uk> Just as a heads up, minidom is pretty inefficient and difficult to work with too. On someone else's advice I switched over to ElementTree and have been really pleased with the results, its much simpler to work with and more efficient too. Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of aine_canby at yahoo.com Sent: 03 August 2007 14:39 To: python-list at python.org Subject: Replacing _xmlplus.dom.minidom with xml.dom.minidom Hi, I'm working with a number of scripts which were written years ago for my company for Python 2.2, and I'd like to update for Python 2.5. I have written a script to add # -*- coding: cp1252 -*- to the beginning of all my scripts, and that has fixed the encoding issues. Another issue was the use of - from _xmlplus.dom import minidom http://sourceforge.net/project/showfiles.php?group_id=6473 I couldn't get a version of this module for 2.5, so I changed the above to - from xml.dom import minidom The scripts I work with are all working now correctly for 2.5. But I haven't been able to test the whole system as not all of it concerns me. Anyway, my colleges are interested in updating also if it will be reasonably hassle free. So my main concern now is the use of _xmlplus.dom.minidom. Why was it used and what differences should I look out for with regard to xml.dom.mididom Thanks very much for your help, Barry. -- http://mail.python.org/mailman/listinfo/python-list From orsenthil at users.sourceforge.net Sun Aug 19 23:40:41 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Mon, 20 Aug 2007 09:10:41 +0530 Subject: passing arguments with ampersands In-Reply-To: <f6be0af40708180524n8d11a68xfcbee5c7f268bdea@mail.gmail.com> References: <f6be0af40708180354u719f5c71p2be27e0ee8317f9b@mail.gmail.com> <20070818112913.GA3632@gmail.com> <f6be0af40708180524n8d11a68xfcbee5c7f268bdea@mail.gmail.com> Message-ID: <20070820034041.GA4616@gmail.com> Sorry for ignoring the thread. > the problem is that when i associate a file extension to my application and > i open it, the filename is not quoted before passed as an arguement. i dont If it is not quoted by default, you can quote it explicit. If this be the case where the filename is obtained from the OS. newname = '"' + filename + '"' If you are passing the filename, then just pass it as "filename". > args = None > > if len(sys.argv) > 1: > > args = sys.argv[1:] > > > print args Yes, '&' character is being interpreted by the SHELL command interpreter and python is not receiving it. Thats why it is failing. You need to escape the special character or quote the entire arg. > how can i make the params get quoted before send as arguments? How are you getting the params? 1) Like I said, if you are passing it, escape the special characters or quote the entire thing. 2) If you getting it from a python function like os.listdir(), I assume it should be readily usable. [ors at goofy ~]$ cat 1.py import sys arg = None if len(sys.argv) > 1: args = sys.argv[1:] print args [ors at goofy ~]$ python 1.py something anotherthing \& yetanother ['something', 'anotherthing', '&', 'yetanother'] [ors at goofy ~]$ python 1.py "something anotherthing & yetanother" ['something anotherthing & yetanother'] [ors at goofy ~]$ If filenames are obtained as os.listdir(), then quote each other > > > > > > > 2007/8/18, O.R.Senthil Kumaran <orsenthil at users.sourceforge.net>: > > > Quote:D:\ftp\Music\Mixes & Compilations\Above & Beyond - Essential > > > Mix\001_Essential_Mix_2004-06-06_-_Above_and_Beyond.txt > > > > > when i put 'print sys.argv[1:]' at the very beginning of the script, all > > i > > > get is this: > > > > > > Quote:['D:\\ftp\\Music\\Mixes'] > > > > > Can you share the portion of the code? > > Are you quoting the argument that you are passing? > > for e.g: > > > > #cat 1.py > > import sys > > print sys.argv[1] > > > > #python 1.py "I am able to print the spaces and & characters" > > I am able to print the spaces and & characters > > > > -- > > O.R.Senthil Kumaran > > http://uthcode.sarovar.org > > -- O.R.Senthil Kumaran http://uthcode.sarovar.org From arkanes at gmail.com Thu Aug 30 19:48:28 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 30 Aug 2007 18:48:28 -0500 Subject: list index() In-Reply-To: <1188517370.998114.119940@q4g2000prc.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <mailman.135.1188474634.28954.python-list@python.org> <1188495863.242815.236900@o80g2000hse.googlegroups.com> <87bqcod2gq.fsf@benfinney.id.au> <1188517370.998114.119940@q4g2000prc.googlegroups.com> Message-ID: <4866bea60708301648w898c6fdia1fc08107edc1568@mail.gmail.com> On 8/30/07, zzbbaadd at aol.com <zzbbaadd at aol.com> wrote: > On Aug 30, 4:31 pm, Ben Finney <bignose+hates-s... at benfinney.id.au> > wrote: > > zzbba... at aol.com writes: > > > In my case of have done os.listdir() on two directories. I want to see > > > what files are in directory A that are not in directory B. > > > > You get that information unambiguously. It's an exceptional case, > > since there's no index to return, so it throws an exception. > > > > > I have used exceptions in other languages and only do so on logic > > > that should never happen. > > > > You're confusing "assert" ("this should always be true") with > > "exception" ("this is an exception to the the normal flow of this > > process"). > > > > An exception isn't "something that should never happen", it's > > something that is entirely possible and needs to be handled somehow. > > I don't think that is the definition used across computer science. > how its defined in Python is what is important in this context. > It suddenly dawned on me that what would be best would be a contains() > (or IN syntax for those who can't afford to wait) for lists. > > if mylist.contains("hello): > Genius. Why didn't anyone think of that before? From uymqlp502 at sneakemail.com Thu Aug 30 19:54:14 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Thu, 30 Aug 2007 16:54:14 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <46d75191$0$401$426a74cc@news.free.fr> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> Message-ID: <1188518054.298017.90610@x35g2000prf.googlegroups.com> Bruno Desthuilliers wrote: > Russ a ?crit : > > On Aug 28, 10:58 pm, Michele Simionato <michele.simion... at gmail.com> > > wrote: > > > > > >>Why do you think that would ad a strong positive capability? > >>To me at least it seems a big fat lot of over-engineering, not > >>needed in 99% of programs. In the remaining 1%, it would still not > >>be needed since Python provides out of the box very powerful > >>metaprogramming capabilities so that you can implement > >>yourself the checks you need, if you really need them. > > > > > > I get the strong impression you don't really understand what > > programming by contract is. > > I get the strong impression you don't really understand how > condescending you are. When someone writes something as ignorant as that, they need to be called on it. So you can implement everything you need already in Python? Yes, of course, and you can do it in machine language too -- if you have the time to waste. > > I have not yet personally used it, > > You have no working experience with the concept, but you think it should > make it into Python's core ??? I don't need to use it to understand the concept. That has been explained brilliantly by the Eiffel and SPARK Ada folks. I am also smart enough to figure out that it can greatly enhance unit testing, and it can also be used as an integral part of unit testing. Once you have the conditions in place, all you need to do in your unit tests is to send inputs to the unit and wait to see if exceptions are thrown. In fact, I would even propose a new name for "programming by contract." I would call it "self-testing code" because the code essentially tests itself every time it is run with the checks activated. From sjmachin at lexicon.net Thu Aug 2 20:01:34 2007 From: sjmachin at lexicon.net (John Machin) Date: Thu, 02 Aug 2007 17:01:34 -0700 Subject: frequency analysis of a DB column In-Reply-To: <1186021313.413443.184060@i38g2000prf.googlegroups.com> References: <1186021313.413443.184060@i38g2000prf.googlegroups.com> Message-ID: <1186099294.343121.50240@d30g2000prg.googlegroups.com> On Aug 2, 12:21 pm, goldtech <goldt... at worldpost.com> wrote: > In Python 2.1 are there any tools to take a column from a DB and do a > frequency analysis - a breakdown of the values for this column? > > Possibly a histogram or a table saying out of 500 records I have one > hundred and two "301" ninety-eight "212" values and three-hundred > "410"? > > Is SQL the way to for this? Umm yes, screamingly obviously, I would have thought, given that you have to use SQL anyway to get the data out of the database .... something like this, with easy embellishment with where, having and order by clauses: select col_name, count(*) from table_name where yadda yadda etc if necessary/desired group by col_name having count(*) >= some_threshold order by count(*) desc Apart from ease of writing, this puts the load on the server, not the client, and saves network traffic -- why transmit thousands/millions of data items around the building or across town when you don't have to? All you have to do in Python is add up the frequencies -- better than doing a "select count(*) from table_name". If you want to do something smart in Python, package the above SQL up so that table_name and col_name are parameters ... you could then have a handy little command-line gadget ready for those moments when you need to find out things like how many different mis-spellings of "developer" there are in the HR database :-) > > Of course there'd be 1000's of values.... > > I'm not asking about connecting to the DB, just tools to collate and > tally this sort of thing. > > Thanks, > Lee G. From brown at esteem.com Fri Aug 31 13:14:29 2007 From: brown at esteem.com (Tom Brown) Date: Fri, 31 Aug 2007 10:14:29 -0700 Subject: low level ethernet device access in linux Message-ID: <200708311014.31047.brown@esteem.com> Hi, I have a windows application, written in delphi, that communicates to our devices using raw ethernet frames. I am trying to port this application to linux using python. However, when I try to open a socket, I get this error: File "/home/tbrown/projects/discovery/trunk/comm.py", line 9, in __init__ self.s = socket(AF_PACKET, SOCK_RAW, proto) File "/usr/local/lib/python2.5/socket.py", line 156, in __init__ _sock = _realsocket(family, type, proto) socket.error: (1, 'Operation not permitted') I understand that I am getting this error because I am running the application as a user and not as root. I would like to be able to run this app. as a user. Is there a way to create a socket without running the app. as root or sudo? When I run the app. as root I get this error: discovery.py: cannot connect to X server Thanks, Tom From jstroud at mbi.ucla.edu Fri Aug 24 01:55:52 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 23 Aug 2007 22:55:52 -0700 Subject: unifying many packages under one name In-Reply-To: <mailman.231.1187929096.32294.python-list@python.org> References: <mailman.231.1187929096.32294.python-list@python.org> Message-ID: <gkuzi.4656$LL7.3867@nlpi069.nbdc.sbc.com> Eric S. Johansson wrote: > I have a collection of packages and I want to put them under single > unifying name. my goal is to reduce namespace pollution and make all > these packages accessible as 'import vvv.aaa'. In more detail, if I have > packages 'aaa' and 'bbb', what do I do to put those packages under > unifying name such as 'vvv'? the only way I can see to do it is to > create 'vvv' as a directory with its own __init__.py but I'm not sure > that were work right either. > > > thanks. > I don't see why it would be a problem: py> import os py> for afile in os.listdir('pypack'): ... if not afile.endswith('pyc'): ... print '# %s' % afile ... print open(os.path.join('pypack', afile)).read().strip() ... print '# end of file\n\n' ... # __init__.py from mod1 import x from mod2 import y # end of file # mod1.py x = 14 # end of file # mod2.py y = 42 # end of file py> import pypack py> dir(pypack) ['__builtins__', '__doc__', '__file__', '__name__', '__path__', 'mod1', 'mod2', 'x', 'y'] py> pypack.mod1 <module 'pypack.mod1' from 'pypack/mod1.py'> James From lac at openend.se Sat Aug 4 20:40:52 2007 From: lac at openend.se (Laura Creighton) Date: Sun, 05 Aug 2007 02:40:52 +0200 Subject: [pygame] pyweek is happening august 02 - august 09 In-Reply-To: Message from Luke Paireepinart <rabidpoobear@gmail.com> of "Sat, 04 Aug 2007 14:25:29 CDT." <46B4D2A9.1010405@gmail.com> References: <200708041832.l74IWkRY027388@theraft.openend.se> <46B4D2A9.1010405@gmail.com> Message-ID: <200708050040.l750eqFQ025279@theraft.openend.se> In a message of Sat, 04 Aug 2007 14:25:29 CDT, Luke Paireepinart writes: >Laura Creighton wrote: >> 00:00 UTC 2007-09-02 to 00:00 UTC 2007-09-09 exactly. See >> www.pyweek.org >> >> PyconUK is happening. http://www.pyconuk.org/ 8th and 9th September. >> >> This means that those of us who generally do not see each other but are >> going to PyconUK could put together an entry and then sprint together >> on it before PyCon UK. There would be this terrible torment -- do >> I attend the con or get my game to work -- but it is still the >> best chance some of us have to work together yet. >> >> Talk to me if you are interested in maybe making a PyconUK pygame >> team. I think that this could be a lot of fun. Sign up on >> www.pyweek.org if you think so, as well. But mail me. >> >> John -- assuming we want to meet up _before_ PyConUK -- can that >> work? Can you point us at a cheap hostel for a few days? >> >> Laura Creighton >> >Laura - Pyweek is happening the first week in September, not august. >Thanks for giving me a good scare, thinking i missed the first half alrea >dy! You are welcome to the scare, but pyconUK is happening first week of Sept too! So my plan of a 'would not meet but for pyconUK team' is still very alive. Laura From toto at titi.de Sat Aug 25 04:10:44 2007 From: toto at titi.de (asrenzo) Date: Sat, 25 Aug 2007 10:10:44 +0200 Subject: Running daemon with zdaemon ... example help? In-Reply-To: <1188011052.347321.211890@r23g2000prd.googlegroups.com> References: <1188011052.347321.211890@r23g2000prd.googlegroups.com> Message-ID: <46cfe403$0$21147$7a628cd7@news.club-internet.fr> Hi, This could also be a good starting point: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 Regards, Laurent Genie T a ?crit : > Hi all, > > I'm looking at zdaemon to run my python scripts as a daemon but it > seems to have few example that guide me how to follow. It would be > great if you can give me a simple example of how to use. I'm newbie > here :) > > Thanks > From db3l.net at gmail.com Thu Aug 30 15:25:25 2007 From: db3l.net at gmail.com (David Bolen) Date: Thu, 30 Aug 2007 15:25:25 -0400 Subject: Unzip: Memory Error References: <1188413939.834662.193180@y42g2000hsy.googlegroups.com> <m21wdmgkmh.fsf@valheru.db3l.homeip.net> <1188472431.290871.103720@o80g2000hse.googlegroups.com> Message-ID: <m2642wg6ze.fsf@valheru.db3l.homeip.net> mcl <mcl.office at googlemail.com> writes: > pseudo code > > zfhdl = zopen(zip,filename) # Open File in Zip Archive for > Reading > > while True: > ln = zfhdl.readline() # Get nextline of file > if not ln: # if EOF file > break > dealwithline(ln) # do whatever is necessary with > file > zfhdl.close > > That is probably over simplified, and probably wrong but you may get > the idea of what I am trying to achieve. Do you have to process the file as a textual line-by-line file? Your original post showed code that just dumped the file to the filesystem. If you could back up one step further and describe the final operation you need to perform it might be helpful. If you are going to read the file data incrementally from the zip file (which is what my other post provided) you'll prevent the huge memory allocations and risk of running out of resource, but would have to implement your own line ending support if you then needed to process that data in a line-by-line mode. Not terribly hard, but more complicated than my prior sample which just returned raw data chunks. Depending on your application need, it may still be simpler to just perform an extraction of the file to temporary filesystem space (using my prior code for example) and then open it normally. -- David From kyosohma at gmail.com Tue Aug 21 12:10:14 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 21 Aug 2007 09:10:14 -0700 Subject: The folder a script is executed in In-Reply-To: <1187709831.722991.99490@l22g2000prc.googlegroups.com> References: <1187687436.476773.276550@22g2000hsm.googlegroups.com> <1187709831.722991.99490@l22g2000prc.googlegroups.com> Message-ID: <1187712614.901337.220830@x35g2000prf.googlegroups.com> On Aug 21, 10:23 am, Benjamin <musiccomposit... at gmail.com> wrote: > On Aug 21, 4:10 am, aine_ca... at yahoo.com wrote:> Hi, > > > How do I find out what folder a script is in while it is executing? > > > For example, for the file "C:/folder/script.py" contain the following > > two lines of code - > > > myLocation = GetMyLocation() > > print myLocation > > def GetMyLocation(): > runningFile = sys.argv[0] if __name__ == "__main__" else __file__ > return os.path.dirname(runningFile) > > > > > >> C:/folder > > > Thanks, > > > Aine. As I understand it, this is one portable way to do it: path = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '.')) Mike From aleax at mac.com Mon Aug 27 10:46:29 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 27 Aug 2007 07:46:29 -0700 Subject: How to free memory ( ie garbage collect) at run time with Python 2.5.1(windows) References: <1188224306.863247.127890@50g2000hsm.googlegroups.com> Message-ID: <1i3hujk.ulsjt32wqtq0N%aleax@mac.com> rfv-370 <robert.vergnes at yahoo.fr> wrote: > have made the following small test: > > Before starting my test my UsedPhysicalMemory(PF): 555Mb > > >>>tf=range(0,10000000) PF: 710Mb ( so 155Mb for my List) > >>>tf=[0,1,2,3,4,5] PF: 672Mb (Why? Why the remaining 117Mb is > >>>not freed?) del tf PF: 672Mb (unused memory > >>>not freed) Integer objects that are once generated are kept around in a "free list" against the probability that they might be needed again in the future (a few other types of objects similarly keep a per-type free-list, but I think int is the only one that keeps an unbounded amount of memory there). Like any other kind of "cache", this free-list (in normal cases) hoards a bit more memory than needed, but results in better runtime performance; anomalous cases like your example can however easily "bust" this too-simple heuristic. > So how can I force Python to clean the memory and free the memory that > is not used? On Windows, with Python 2.5, I don't know of a good approach (on Linux and other Unix-like systems I've used a strategy based on forking, doing the bit that needs a bazillion ints in the child process, ending the child process; but that wouldn't work on Win -- no fork). I suggest you enter a feature request to let gc grow a way to ask every type object to prune its cache, on explicit request from the Python program; this will not solve the problem in Python 2.5, but work on 3.0 is underway and this is just the right time for such requests. Alex From duncan.booth at invalid.invalid Wed Aug 1 03:35:30 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Aug 2007 07:35:30 GMT Subject: Iteration over strings References: <46AF9F55.20105@gmx.net> <46AFA1D9.1010707@gmx.net> <mailman.1403.1185926092.22759.python-list@python.org> Message-ID: <Xns997F576915189duncanbooth@127.0.0.1> Jay Loden <python at jayloden.com> wrote: > This isn't just a problem with the socket module, so please don't > think I'm picking on it or singling it out, it's something I've seen a > number of places. e.g. from os.stat: > > os.stat = stat(...) > stat(path) -> stat result > > Perform a stat system call on the given path. > > Ok...and what is the return value? a list? tuple? string? some type of > stat object? dictionary? The only way to find out is to read the os > module's source code or try it to find out. If you were really lucky > you might find the related documentation from class statvfs_result and > put two and two together to figure it out. Or if you were really, really lucky you might try reading the documentation (http://docs.python.org/lib/os-file-dir.html): stat( path) Perform a stat() system call on the given path. The return value is an object whose attributes correspond to the members of the stat structure, namely: st_mode (protection bits), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid (user ID of owner), st_gid (group ID of owner), st_size (size of file, in bytes), st_atime (time of most recent access), st_mtime (time of most recent content modification), st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows): >>> import os >>> statinfo = os.stat('somefile.txt') >>> statinfo (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732) >>> statinfo.st_size 926L >>> Changed in version 2.3: If stat_float_times returns true, the time values are floats, measuring seconds. Fractions of a second may be reported if the system supports that. On Mac OS, the times are always floats. See stat_float_times for further discussion. On some Unix systems (such as Linux), the following attributes may also be available: st_blocks (number of blocks allocated for file), st_blksize (filesystem blocksize), st_rdev (type of device if an inode device). st_flags (user defined flags for file). On other Unix systems (such as FreeBSD), the following attributes may be available (but may be only filled out if root tries to use them): st_gen (file generation number), st_birthtime (time of file creation). On Mac OS systems, the following attributes may also be available: st_rsize, st_creator, st_type. On RISCOS systems, the following attributes are also available: st_ftype (file type), st_attrs (attributes), st_obtype (object type). For backward compatibility, the return value of stat() is also accessible as a tuple of at least 10 integers giving the most important (and portable) members of the stat structure, in the order st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime. More items may be added at the end by some implementations. The standard module stat defines functions and constants that are useful for extracting information from a stat structure. (On Windows, some items are filled with dummy values.) Note: The exact meaning and resolution of the st_atime, st_mtime, and st_ctime members depends on the operating system and the file system. For example, on Windows systems using the FAT or FAT32 file systems, st_mtime has 2-second resolution, and st_atime has only 1-day resolution. See your operating system documentation for details. Availability: Macintosh, Unix, Windows. Changed in version 2.2: Added access to values as attributes of the returned object. Changed in version 2.5: Added st_gen, st_birthtime. From steve at holdenweb.com Fri Aug 31 21:50:34 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 31 Aug 2007 21:50:34 -0400 Subject: Parameter Passing - String Variable Truncated ? In-Reply-To: <fbag04$ugc$2@sea.gmane.org> References: <1188604442.700651.94530@19g2000hsx.googlegroups.com> <fbag04$ugc$2@sea.gmane.org> Message-ID: <46D8C56A.8020402@holdenweb.com> Steve Holden wrote: [...] >> in_featclass = sys.argv[1] > > Try > > in_featclass = sys.argv[1:] > Sorry, that should have been in_featclass = " ".join(sys.argv[1:])+"\n" regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From inmmike at gmail.com Sun Aug 19 12:39:43 2007 From: inmmike at gmail.com (inmmike at gmail.com) Date: Sun, 19 Aug 2007 09:39:43 -0700 Subject: "Variable variable name" or "variable lvalue" In-Reply-To: <1187199722.618893.281170@r29g2000hsg.googlegroups.com> References: <1187199722.618893.281170@r29g2000hsg.googlegroups.com> Message-ID: <1187541583.607550.107230@57g2000hsv.googlegroups.com> On Aug 15, 1:42 pm, mfglinux <mfgli... at gmail.com> wrote: > Hello to everybody > > I would like to know how to declare in python a "variable name" that > it is in turn a variable > In bash shell I would wrote sthg like: > > for x in `seq 1 3` > do > M$i=Material(x) #Material is a python class > done > > Why I need this? Cause I have a python module that obliges me to build > a variable called Period, which should have a variable name of > summands (depends on the value of x) > > #Let's say x=3, then Period definition is > Period=Slab(Material1(12.5)+Material2(25)+Material3(12.5)) #Slab is a > python class > > I dont know how to automatize last piece of code for any x > > thank you > > Marcos Regardless of whether or not this is a "best practice" sometimes it is necessary. For example, I am looping through a dictionary to set some class properties. Anyway, here is what I finally came up with: exec "self.%s = '%s'" % (item, plist[item]) A more simple example for setting a variable outside of a class... exec '%s = '%s'" % ('variableName', 'variable value') Cheers! Mike From max at alcyone.com Mon Aug 13 13:58:27 2007 From: max at alcyone.com (Erik Max Francis) Date: Mon, 13 Aug 2007 10:58:27 -0700 Subject: negative polar axis In-Reply-To: <mailman.1918.1187013003.22759.python-list@python.org> References: <1186999666.642856.16820@19g2000hsx.googlegroups.com> <mailman.1918.1187013003.22759.python-list@python.org> Message-ID: <puednd-H8IReBl3bnZ2dnUVZ_s7inZ2d@speakeasy.net> Steve Holden wrote: > About the best interpretation I can think of is to add 180 degrees to > the angle and reverse the sign of the magnitude, but this would be a > hack. Where are those coordinates coming from? Well, sometimes in polar coordinates (r, theta), r is allowed to be negative. The usual translation from polar to Cartesian coordinates makes this meaningful, albeit weird, so in effect the resulting positions are just reflections around the origin. Which I suppose is what the original poster was asking about, but it's still not clear. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis The conviction of wisdom is the plague of man. -- Montaigne From evan at yelp.com Thu Aug 9 00:51:21 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 8 Aug 2007 21:51:21 -0700 Subject: Misleading wikipedia article on Python 3? In-Reply-To: <5hv7jeF3m75aqU1@mid.individual.net> References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <mailman.1660.1186380664.22759.python-list@python.org> <7xzm15q8fy.fsf@ruckus.brouhaha.com> <1186583168.447608.114040@d55g2000hsg.googlegroups.com> <5hv7jeF3m75aqU1@mid.individual.net> Message-ID: <cfb58d850708082151u7196d854o140e6acf5df04e2c@mail.gmail.com> On 8/8/07, greg <greg at cosc.canterbury.ac.nz> wrote: > Istvan Albert wrote: > > A solution would be writing the code with a logging function to begin > > with, alas many times that is out of one's hand. > > If the code has been written with calls to a builtin > print function, the situation isn't much better. You > could monkeypatch the print function, but that's > probably worse than swapping sys.stdout. You can easily modify print in a safe way. Here's an example, that will work in any recent version of Python: import sys def print_(s): print s def logger(method): def wrapper(s): sys.stderr.write('Logging: %s\n' % s) method(s) return wrapper print_ = logger(print_) print_('hello') Running this code will do a regular print of 'hello', as well as "logging" it to stderr. As a function, you can convert print wholesale to another logging function, or wrap it transparently like this to provide additional logging functionality. What do you find wrong with this sort of "monkeypatching"? -- Evan Klitzke <evan at yelp.com> From pyth0nc0d3r at gmail.com Fri Aug 24 14:49:55 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Fri, 24 Aug 2007 13:49:55 -0500 Subject: Fwd: I can't get value of entry box, Tinker In-Reply-To: <1187980089.367178.81060@e9g2000prf.googlegroups.com> References: <eb79828c0708240816o182b1e75o67fc9b27b6475051@mail.gmail.com> <mailman.268.1187975584.32294.python-list@python.org> <1187980089.367178.81060@e9g2000prf.googlegroups.com> Message-ID: <eb79828c0708241149g1e31ed98g9f764f12a40b7888@mail.gmail.com> yes, I already fixed the problem. ---------- Forwarded message ---------- From: 7stud <bbxx789_05ss at yahoo.com> Date: Aug 24, 2007 1:28 PM Subject: Re: I can't get value of entry box, Tinker To: python-list at python.org Matt McCredie wrote: > > What/should I, can I do? > > Fix your code? > > > def login(): > > global e2,e1 > > print e2.get() > > print e1.get() > > That should work. > > Matt Try something like this: import Tkinter as tk root = tk.Tk() entry = tk.Entry(root) button = tk.Button(root, text="print text in textbox") def on_button_click(event): print entry.get() button.bind("<Button-1>", on_button_click) entry.pack() button.pack() root.mainloop() -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070824/fac715f9/attachment.html> From rrs at researchut.com Tue Aug 14 10:24:07 2007 From: rrs at researchut.com (Ritesh Raj Sarraf) Date: Tue, 14 Aug 2007 19:54:07 +0530 Subject: Module imports during object instantiation References: <4c3vo4-u7k.ln1@learner.hq.netapp.com> <f9pcuj$6n4$1@sea.gmane.org> <mailman.1931.1187030415.22759.python-list@python.org> <46c16ec9$0$405$426a34cc@news.free.fr> <mailman.1956.1187091452.22759.python-list@python.org> <slrnfc36p9.21o.horpner@FIAD06.norwich.edu> Message-ID: <7hq8p4-hll.ln1@learner.hq.netapp.com> Neil Cerutti wrote: > If you want an import inside an __init__ to run, you must call > the __init__ function that contains it. Doesn't __init__ get called automatically ? I thought __init__ was required to be called explicitly only when you were doing inheritance and wanted to pass separate values to the base class. Ritesh -- If possible, Please CC me when replying. I'm not subscribed to the list. From chernevik at gmail.com Sat Aug 4 17:30:07 2007 From: chernevik at gmail.com (chernevik at gmail.com) Date: Sat, 04 Aug 2007 14:30:07 -0700 Subject: Question -- Running Programming Python Examples Message-ID: <1186263007.587499.305340@57g2000hsv.googlegroups.com> Here is a newbie question: how do I get the server examples in the Preview chapter of "Progamming Python" (Lutz) to run? The code is supposed to be a little webserver on which to run examples, but when I run it it I get "permission denied". Running it as root gets "address already in use". Here is the code (it's example 2.32); comments are from Lutz, not me: webdir = '.' # where your html files and cgi-bin script directory live port = 80 # default http://localhost/, else use http://localhost:xxxx/ import os, sys from BaseHTTPServer import HTTPServer from CGIHTTPServer import CGIHTTPRequestHandler # hack for Windows: os.environ not propogated [deleted, I'm running linux] . . . os.chdir(webdir) # run in html root dir srvraddr = ("", port) # my hostname, portnumber srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler) srvrobj.serve_forever() # run as perpetual demon END CODE My other python scripts run fine. I'm running linux (debian). I'm not running an webserver (that I know of anyway). I've fiddled with adding the subdirectory with the code to the python path, but this doesn't seem to help either. I'm new to all this, but I've been able to make the other stuff work, and I can't even find the beginning of what I'm supposed to research to fix this. Any help would be greatly appreciated, and thanks for your time and patience. From larry.bates at websafe.com Mon Aug 13 10:31:20 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 13 Aug 2007 09:31:20 -0500 Subject: Drawing a graph In-Reply-To: <mailman.1917.1187012829.22759.python-list@python.org> References: <mailman.1917.1187012829.22759.python-list@python.org> Message-ID: <46C06B38.2070507@websafe.com> Ghirai wrote: > Hello list, > > I need to draw a graph, 2 axes, 2D, nothing fancy. > One of the axes is time, the other one is a series of integers. > > I don't care much about the output format. > > Are there any specialized libraries for this, or should i use PIL? > > Thanks. > ReportLab graphics works for me. www.reportlab.org -Larry From tn.pablo at gmail.com Sun Aug 19 19:53:52 2007 From: tn.pablo at gmail.com (Pablo Torres) Date: Sun, 19 Aug 2007 23:53:52 -0000 Subject: Syntax Question - list multiplication In-Reply-To: <4L3yi.61391$W21.1628190@phobos.telenet-ops.be> References: <1187560273.146491.90530@r29g2000hsg.googlegroups.com> <4L3yi.61391$W21.1628190@phobos.telenet-ops.be> Message-ID: <1187567632.967080.78400@r29g2000hsg.googlegroups.com> Thanks everyone. Now I see why every row in my grid were actually the same object. Pablo From knipknap at gmail.com Fri Aug 3 16:58:53 2007 From: knipknap at gmail.com (Samuel) Date: Fri, 03 Aug 2007 13:58:53 -0700 Subject: ANNOUNCE: Spiff Workflow 0.0.1 (Initial Release) Message-ID: <1186174733.838817.247450@g4g2000hsf.googlegroups.com> Introduction ------------ Spiff Workflow is a library implementing a framework for workflows. It is based on http://www.workflowpatterns.com and implemented in pure Python. Supported workflow patterns include (at least) the following: 1. Sequence 2. Parallel Split 3. Synchronization 4. Exclusive Choice 5. Simple Merge 6. Multi-Choice 7. Structured Synchronizing Merge 8. Multi-Merge 9. Structured Discriminator 10. Arbitrary Cycles Spiff Workflow is part of the Spiff platform, which aims to produce a number of generic libraries generally needed in enterprise applications. This release is the initial release and SHOULD NOT BE USED IN PRODUCTION ENVIRONMENTS - this release is meant for development only. Spiff Workflow is free software and distributed under the GNU LGPLv2.1. Dependencies ------------- Python >= 2.4 Download --------- The release page is here: http://pypi.python.org/pypi/Spiff%20Workflow/0.0.1 You can also check the code out of SVN: svn checkout http://spiff.googlecode.com/svn/trunk/libs/Workflow/ Links: ------- Spiff project page: http://code.google.com/p/spiff/ Mailing list: http://groups.google.com/group/spiff-devel Bug tracker: http://code.google.com/p/spiff/issues/list Documentation: http://spiff.googlecode.com/svn/trunk/libs/Workflow/README Browse the source: http://spiff.googlecode.com/svn/trunk/libs/Workflow/ If you have any questions, please do not hesitate to ask. -Samuel From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Aug 9 12:07:09 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 09 Aug 2007 18:07:09 +0200 Subject: Help with Dictionaries and Classes requested please. In-Reply-To: <46bb19e2$0$9835$7b0f0fd3@mistral.news.newnet.co.uk> References: <46bacae3$0$89254$7b0f0fd3@mistral.news.newnet.co.uk> <46bacf1b$0$54289$7b0f0fd3@mistral.news.newnet.co.uk> <87ejic6dkw.fsf@benfinney.id.au> <46bb19e2$0$9835$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <46bb3ba5$0$423$426a34cc@news.free.fr> special_dragonfly a ?crit : > "Ben Finney" <bignose+hates-spam at benfinney.id.au> wrote in message > news:87ejic6dkw.fsf at benfinney.id.au... >> "special_dragonfly" <Dominic at PLEASEASK.co.uk> writes: >> >>> I've managed to solve the problem, I really was just being a >>> dunce. >> Doubtful; but at this stage we can't tell, because we still don't know >> what it is you're actually trying to *do*. >> >>> Here's how incase anyone is wondering: >>> >>> class MyClass: >>> def __init__(self): >>> name="" >>> dict={} >>> dict[0]=[] >>> dict[0].append(MyClass()) >>> dict[0][0].name="Hello" >>> print dict[0][0].name >> It's not clear why you are using the value 0 for a dictionary key >> here; nor why you're assigning an attribute to an object after >> creating the object. Neither of them are errors, but without context >> it's hard to know what advice to give. >> > The 0 for a key is just an example. The code I actually have would be just > as meaningful at the end of the day. I could have changed MyClass for > class Animals(object): > def __init__(self, name="", type="", age=""): > self.name=name > self.type=type > self.age=age > > dict={'Mouse':[Animals('George','long eared',20)]} > dict['Mouse'].append(Animals('Benny','hairy',30)) > dict['Cat']=[Animals('Inigo Montoya','spanish',10)] > > and Neil, Bruno has the right idea of what I was trying to do. However, your > code came in handy still as I used your code elsewhere.see below. > > def EnterDictionary(FieldsDictionary,key,data): > for i in range(0,int(data[6:])): > line=myfile.readline() > line=line.strip() > line=line[6:-1] > if key in FieldsDictionary: > FieldsDictionary[key].append(FieldClass(*line.split(","))) > else: > FieldsDictionary[key]=[FieldClass(*line.split(","))] May I suggest a couple possible improvements ? First : you're of course free to use any naming convention you like, and it's obviously better to stay consistent, but the canonical Python convention is to use all_lower for vars, functions (and methods) and modules, and MixedCase for classes. About the code now: def EnterDictionary(FieldsDictionary,key,data): for i in range(0,int(data[6:])): 1/ Golden rule : avoid the use of "magic numbers". This one stands true for any languages !-). The usual solution is to use symbolic constants. While Python doesn't have real symbolic constant, the convention is to write them ALL_UPPER. 2/ range() can be used with only one argument, which then will be use as the upper bound. IOW, range(0, X) is the same as range(X) line=myfile.readline() 3/ where does this 'myfile' comes from ? (hint : don't use globals when you can avoid them) line=line.strip() line=line[6:-1] 4/ magic numbers again, cf /1. Question : does this 6 has anything to do with the other one ? What will happen when the file format will change ? 5/ you can do all this in a single line, adding the split() too: args = myfile.readline().strip()[XXX:-1].split(",") > if key in FieldsDictionary: > FieldsDictionary[key].append(FieldClass(*line.split(","))) > else: > FieldsDictionary[key]=[FieldClass(*line.split(","))] If you expect key to most of the times be already in FieldsDictionnary, then a try/except block might be a bit faster. If you expect key to not be here most of the times, then your solution is right. Note that you can also use dict.setdefault(key, default): # probably bad names but I don't have a clue what they should be DATA_INDEX_OFFSET = 6 LINE_START = 6 LINE_END = -1 def update_fields_dict(fields_dict, key, data, datafile): for i in range(int(data[DATA_INDEX_OFFSET:])): args =datafile.readline().strip()[LINE_START:LINE_END].split(",") fields_dict.setdefault(key, []).append(FieldClass(*args)) Feel free to take or leave what you consider appropriate here. But by all means avoid magic numbers, except possibly for Q&D throw-away scripts (and even then...). HTH > In future I would ask however, if it's a really stupid question and you feel > that the answer can be found either by searching google (because in some > cases I don't know what to search for), or in one of the O'reilly books, > just say. In either case, if you could refer me to the search term to use or > the book to read I'd be grateful. That's usually what happens then, don't worry. From DustanGroups at gmail.com Sat Aug 11 17:11:45 2007 From: DustanGroups at gmail.com (Dustan) Date: Sat, 11 Aug 2007 21:11:45 -0000 Subject: Metaclass v.s. Property function. In-Reply-To: <1186835613.178733.81210@q75g2000hsh.googlegroups.com> References: <1186835613.178733.81210@q75g2000hsh.googlegroups.com> Message-ID: <1186866705.316748.68980@22g2000hsm.googlegroups.com> On Aug 11, 7:33 am, Jens Thiede <jensthi... at gmail.com> wrote: > I don't like the property function, usable in the new-style classes, > because having to remember to manage a list of "foo = property(...)" > assignments just plain sucks, so I wrote a metaclass that does things > a little differently. Please have a look and tell me whether this is > useful or impractical. The metaclass is here:http://pastebin.com/m5b06b571 > and some simple testcode is here:http://pastebin.com/m382f2ae9. > Notice the first line though. Are you overusing property, by any chance? In your example, bar seems to be an unneeded property; it could just be a normal attribute. From mugi at pinesalad.net Tue Aug 21 05:29:14 2007 From: mugi at pinesalad.net (Signal) Date: Tue, 21 Aug 2007 02:29:14 -0700 Subject: File Read Cache - How to purge? In-Reply-To: <5ivl9fF3rafecU1@mid.uni-berlin.de> References: <1187669203.698637.81990@i38g2000prf.googlegroups.com> <5ivl9fF3rafecU1@mid.uni-berlin.de> Message-ID: <1187688554.043448.212260@l22g2000prc.googlegroups.com> > What do you mean by so little memory. It (the whole file) is cached by the > operating system totally independent of your program. Please note I already stated it was more than likely by the OS and noted the tests to confirm that. > It (the whole file) is cached by the operating system totally independent > of your program, so the memory used does of course not show up in the memory > stats of your program... <snip> In this case the OS is Windows and monitoring the memory usage in Task Manager, not through the script. The entire 759MB file is not being cached in memory and only 2MB of memory is used when the script runs. You can see in the example script that I'm not storing the file in memory (buf is "overwritten" at each read(size)) and no memory stats are being kept there. Not sure where I might have eluded otherwise, but hope this clears that up. > > 2. Is there anyway to somehow to take advantage of this "caching" by > > initializing it without reading through the entire file first? > > You mean reading the file without actually reading it!? :-) > Think you misunderstood. What the "tests" are eluding to is: a. The whole file itself is NOT being cached in memory. b. If there is mechanism to which it is "caching" something (which obviously isn't the whole file itself), why not possibly take advantage of it? And sometimes there can be "tricks" to "initializing" before actually read/writing a file to help improve some performance (and not necessarily via a cache). From jstroud at mbi.ucla.edu Mon Aug 20 00:51:06 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 20 Aug 2007 04:51:06 GMT Subject: yet another indentation proposal In-Reply-To: <13ci0oesdtlh871@corp.supernews.com> References: <fEZxi.8855$9W6.6492@fe103.usenetserver.com> <13ci0oesdtlh871@corp.supernews.com> Message-ID: <_49yi.9351$3x.6614@newssvr25.news.prodigy.net> Dennis Lee Bieber wrote: > On Sat, 18 Aug 2007 13:22:54 -0500, "Aaron" > <cajnnjonaj at fjireanjtjprodjuctijons.com> declaimed the following in > comp.lang.python: > > >> column to make sure that everything lines up. I, on the other hand, >> generally find my self counting a lot of spaces. >> > Forgive me, but that sounds like a valid excuse for me to suggest > near heresy... and that TABS should be the standard indent mechanism, > not spaces... > > I'd much rather hear: tab tab tab print > than: space space space space space space space space space space space > space space space space space space space space space space space space > space print > (that many as the Python definition of a tab is eight spaces) What's wrong with just saying the current indent level? I'd much rather hear "indent 4" than "tab tab tab tab". James From jomorcsi at gmail.com Mon Aug 6 14:30:02 2007 From: jomorcsi at gmail.com (jomorcsi at gmail.com) Date: Mon, 06 Aug 2007 18:30:02 -0000 Subject: automatically setting platform-dependent location for Distutils "install-scripts"? Message-ID: <1186425002.316751.171530@l70g2000hse.googlegroups.com> Hello all, I am developing a Python-based tool that will be deployed both in a Windows and in a Linux environment, and I have a question concerning the use of the Distutils module to manage the installation of the tool in a transparent manner. A bit of background info: 1. (I am using Python version 2.5) 2. Let's assume that the tool is named "xyz" 3. It is internally partitioned into two parts: xyzScript.py -- the front-end script that the users actually invoke, and xyzPackage -- a package containing the "guts" of the tool 4. Users do not really care where the "xyzPackage" part is installed -- and thus by default it will be installed into Python's standard "site-packages" directory. 5. However, users *do* care where the "xyzScript.py" part is installed Now, I have created a Distutils-based "setup.py" script that looks like this: from distutils.core import setup > > setup(name='xyz', > version="1.0", > # provide other metadata, such as 'description', 'author', 'author_email', 'url', ... etc. > > packages=['xyzPackage'], > > scripts=['xyzScript.py']) > ... that takes care of the above concerns, and also accepts a "setup.cfg" configuration file that allows the user to control into which directory to install the "xyzScript.py" part, as follows: > > [install] > install-scripts=C:\xyzScriptDirectory > And thus, here is my problem: [1] At any given moment, the directory name specified in the above "setup.cfg" file can be either a "Windows-style" directory (as is shown above) or a "Linux-style" directory (say "/opt/xyzScriptDirectory"), but not both! [2] I would like to have a *single* "setup.cfg" file that can nevertheless be used for *both* Windows and Linux, *without* having to be edited by the user. For example, it would be really nice if I can have a customized "setup.cfg" file that looks like: > > [install] > install-scripts-Windows=C:\xyzScriptDirectory > install-scripts-Linux=/opt/xyzScriptDirectory > ... and then some part of Distutils can query "os.name" and set the "real" 'install-scripts' option to the appropriate one of these two choices. I assume this can be done by "overriding" and customizing part of Distutils. Indeed, I have already done something similar by overriding "distutils.command.build_scripts" to use a customized "copy_scripts()" method. However, it is not clear to me in what manner I can/should override "distutils.command.install_scripts" to achieve the effect that I desire. Is this at all the way to go, or might there be a totally obvious way to do this that I am currently overlooking? If anyone has similar experience in tweaking Distutils, I would be most appreciative of any advice that you can offer. Thanks in advance! From gerard.blais at gmail.com Fri Aug 17 11:49:49 2007 From: gerard.blais at gmail.com (Gerry) Date: Fri, 17 Aug 2007 15:49:49 -0000 Subject: Question on SPE and pwintypes.dll In-Reply-To: <1187360049.391743.9980@l22g2000prc.googlegroups.com> References: <1187357898.740425.33170@r29g2000hsg.googlegroups.com> <1187360049.391743.9980@l22g2000prc.googlegroups.com> Message-ID: <1187365789.251660.286300@22g2000hsm.googlegroups.com> On Aug 17, 10:14 am, kyoso... at gmail.com wrote: > On Aug 17, 8:38 am, Gerry <gerard.bl... at gmail.com> wrote: > > > I'm running SPE 8.3.c under XP, on a new PC. > > > The files for SPE and Python were copied to the new machine, but > > the OS wasn't migrated, so the registry didn't know about either. > > > I reinstalled Python 2.5.1, and Python seems fine. > > > I made a shortcut to SPE.pyw. Clicking on the shortcut gives an > > error pop-up, application failed to start cannot find pwintypes.dll. > > When I click "OK", SPE seems to start normally. > > > Any idea what's up? Googling for pwintypes.dll didn't give me any > > hits. > > > Gerry > > Probably just need to do a search in the registry of the old PC for > SPE or that dll file and then make the appropriate changes on your new > PC. Or just reinstall SPE. > > Mike Thanks -- I'll give that a try. Gerry From conra2004 at yahoo.com Fri Aug 17 11:43:15 2007 From: conra2004 at yahoo.com (yadin) Date: Fri, 17 Aug 2007 08:43:15 -0700 Subject: help to make program better Message-ID: <1187365395.441992.198880@k79g2000hse.googlegroups.com> hi! Can any one tell me why is it that i can't see my second frame and why is the value of freq not Appended in the First frame ...thanks I know it is wx python but it has to do with passing variables.thanks import wx def create(parent): return Frame1(parent) [wxID_FRAME1, wxID_FRAME1FREQ, wxID_FRAME1FREQDISP, wxID_FRAME1STATICTEXT1, ] = [wx.NewId() for _init_ctrls in range(4)] class Frame1(wx.Frame): def _init_ctrls(self, prnt): # generated method, don't edit wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt, pos=wx.Point(380, 179), size=wx.Size(241, 133), style=wx.DEFAULT_FRAME_STYLE, title='Frame1') self.SetClientSize(wx.Size(233, 99)) self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1, label='frequency disp', name='staticText1', parent=self, pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) self.freqdisp = wx.TextCtrl(id=wxID_FRAME1FREQDISP, name='freqdisp', parent=self, pos=wx.Point(104, 24), size=wx.Size(100, 21), style=0, value='') self.freq = wx.Button(id=wxID_FRAME1FREQ, label='get freq', name='freq', parent=self, pos=wx.Point(24, 56), size=wx.Size(184, 23), style=0) self.freq.Bind(wx.EVT_BUTTON, self.OnButton1Button, id=wxID_FRAME1FREQ) def __init__(self, parent): self._init_ctrls(parent) def OnButton1Button(self, event): def create(parent): return Frame2(parent) [wxID_FRAME2, wxID_FRAME2FREQ, wxID_FRAME2FREQDISP, wxID_FRAME2STATICTEXT1,] = [wx.NewId() for _init_ctrls in range(4)] class Frame2: def __init__(self): # wx.Frame.__init__(self, id=wxID_FRAME2, name='', parent=prt, pos=wx.Point(400, 179), size=wx.Size(300, 133), style=wx.DEFAULT_FRAME_STYLE, title='Frame2') self.SetClientSize(wx.Size(233, 99)) self.staticText1 = wx.StaticText(id=wxID_FRAME2STATICTEXT1, label='frequency goes here first', name='staticText2', parent=self, pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) self.freqdisp2 = wx.TextCtrl(id=wxID_FRAME2FREQDISP, name='freqdisp2', parent=self, pos=wx.Point(104, 24), size=wx.Size(100, 21), style=0, value=' ') self.freq = wx.Button(id=wxID_FRAME2FREQ, label='get freq', name='freq', parent=self, pos=wx.Point(24, 56), size=wx.Size(184, 23), style=0) self.freq.Bind(wx.EVT_BUTTON, self.OnButton2Button, id=wxID_FRAME2FREQ) def __init__(self, parent): self._init_ctrls(parent) def OnButton2Button(self, event): freqdisp.Append('this is it 24HZ!') if __name__ == '__main__': app = wx.PySimpleApp() frame = create(None) frame.Show() app.MainLoop() From bbxx789_05ss at yahoo.com Thu Aug 30 14:13:14 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 30 Aug 2007 11:13:14 -0700 Subject: gc.garbage In-Reply-To: <46D692FC.4030805@v.loewis.de> References: <1188467173.708043.44800@w3g2000hsg.googlegroups.com> <46D692FC.4030805@v.loewis.de> Message-ID: <1188497594.577267.34690@q4g2000prc.googlegroups.com> On Aug 30, 3:50 am, "Martin v. L?wis" <mar... at v.loewis.de> wrote: > > gc.set_debug(gc.DEBUG_LEAK) > > print gc.garbage > > > --output:-- > > [] > > gc: uncollectable <Dog 0x56e10> > > gc: uncollectable <Cat 0x56e30> > > gc: uncollectable <dict 0x58270> > > gc: uncollectable <dict 0x43e40> > > gc.garbage is filled only after these messages > are printed, not before. You need to add an explicit > call to gc.collect() if you want to see what > uncollectable garbage you have. > > Regards, > Martin Hi, Thanks for the response. Now, when I run the code: ------------ import gc class Cat(object): pass class Dog(object): pass def some_func(): the_dog = Dog() the_cat = Cat() the_dog.cat = the_cat the_cat.dog = the_dog some_func() gc.set_debug(gc.DEBUG_LEAK) gc.collect() print gc.garbage ---------------- I get this output: ------------- gc: uncollectable <Dog 0x56e10> gc: uncollectable <Cat 0x56e30> gc: uncollectable <dict 0x58300> gc: uncollectable <dict 0x43e40> [<__main__.Dog object at 0x56e10>, <__main__.Cat object at 0x56e30>, {'cat': <__main__.Cat object at 0x56e30>}, {'dog': <__main__.Dog object at 0x56e10>}] --------------- Why are there two entries in the list for each uncollectable object? Also, I haven't bound the names "cat" or "dog" anywhere in my program. What do those names mean in the list? Doing some more testing, if I remove the __del__ methods: --------------- class Cat(object): pass class Dog(object): pass def some_func(): the_dog = Dog() the_cat = Cat() the_dog.cat = the_cat the_cat.dog = the_dog some_func() gc.set_debug(gc.DEBUG_LEAK) gc.collect() print gc.garbage ----------- I get this output: ----------------- gc: collectable <Dog 0x56e10> gc: collectable <Cat 0x56e30> gc: collectable <dict 0x58270> gc: collectable <dict 0x43e40> [<__main__.Dog object at 0x56e10>, <__main__.Cat object at 0x56e30>, {'cat': <__main__.Cat object at 0x56e30>}, {'dog': <__main__.Dog object at 0x56e10>}] ---------------- Now the objects are marked as collectable. The docs say: ---- garbage A list of objects which the collector found to be unreachable but could not be freed (uncollectable objects). ---- So, I expected gc.garbage to be empty. The docs also say: ---- garbage ...By default, this list contains only objects with __del__() methods. ---- From kay.schluehr at gmx.net Sun Aug 12 00:06:49 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 11 Aug 2007 21:06:49 -0700 Subject: Destruction of generator objects In-Reply-To: <20070811145033.18c70c0c@cube.tz.axivion.com> References: <20070808002852.6228ae91@cube.tz.axivion.com> <1186613044.494852.306970@q75g2000hsh.googlegroups.com> <20070809011441.05d7dfb6@cube.tz.axivion.com> <1186819365.988117.232230@g4g2000hsf.googlegroups.com> <20070811121630.1b010eab@cube.tz.axivion.com> <1186831173.814193.235420@o61g2000hsh.googlegroups.com> <20070811140017.22a11f82@cube.tz.axivion.com> <1186834823.389706.137980@r34g2000hsd.googlegroups.com> <20070811145033.18c70c0c@cube.tz.axivion.com> Message-ID: <1186891609.803641.185700@k79g2000hse.googlegroups.com> On Aug 11, 2:50 pm, Stefan Bellon <sbel... at sbellon.de> wrote: > So why is the destructor not called when the generator is even > explicitly 'del'ed? Does somebody else still hold a reference on it? You ( we ) have produced a reference cycle. In that case __del__ doesn't work properly ( according to the docs ). The cycle is caused by the following assignment in your code: self.gen = self._value() So we have to refactor the solution to eliminate the cycle. I spent some time to create a generic decorator solution and a protocol for handling / releasing the resources. 1) Create a FinalizerGenerator class that is cycle free ( of course you can find a trick to shoot yourself in your foot ). Pass a generator function together with its arguments into the constructor. An additional callable attribute close is used together with __del__. class FinalizerGenerator(object): def __init__(self, gen, *args, **kwd): print "gen init" self._gen = gen # no cycle when passing the _value function self.close = lambda: sys.stdout.write("gen del") # assign cleanup function def __del__(self): self.close() def __iter__(self): print "gen iter" return self def next(self): print "gen next" return self.gen.next() 2) Define generators s.t. they yield the resource to be destroyed as their first value. def producer(resource): print "gen value" yield resource # yield resource before start iteration for item in resource: yield item 3) Define the destructor for the resource. The resource must be passed as a first argument. The return value is a callable without arguments that serves as a close() function within FinalizerGenerator.__del__ method. def close_resource(resource): return lambda: sys.stdout.write("close resource: %s"%resource) 4) The finalize_with decorator def finalize_with(close_resource): def closing(func_gen): def fn(*args, **kwd): # fg serves as a replacement for the original generator func_def fg = FinalizerGenerator(func_gen)(*args, **kwd) # apply the closing protocol resource = fg.next() fg.close = close_resource(resource) return fg fn.__name__ = func_gen.__name__ return fn return closing 5) decorate the generator and check it out @finalize_with(close_resource) def producer(resource): print "gen value" yield resource for item in resource: yield item def test(): pg = producer([1,2,3]) pg.next() >>> test() gen init gen next # request for resource in finalize_with gen value gen next close resource: [1, 2, 3] # yep From gnewsg3 at gmail.com Thu Aug 9 15:47:10 2007 From: gnewsg3 at gmail.com (billiejoex) Date: Thu, 09 Aug 2007 12:47:10 -0700 Subject: tempfile behavior In-Reply-To: <1186684291.629191.185070@z24g2000prh.googlegroups.com> References: <1186683707.869668.316360@g4g2000hsf.googlegroups.com> <1186684291.629191.185070@z24g2000prh.googlegroups.com> Message-ID: <1186688830.051531.13560@z24g2000prh.googlegroups.com> On 9 Ago, 20:31, half.ital... at gmail.com wrote: > On Aug 9, 11:21 am, billiejoex <gnew... at gmail.com> wrote: > > > Hi all, > > I would like to use tempfile module to generate files having unique > > names excepting that I don't want them to be removed after closing. > > Does it is possible? > > Looks like tempfile.mkstemp() will do what you want. > > '''Unlike TemporaryFile(), the user of mkstemp() is responsible for > deleting the temporary file when done with it.''' > > ~Sean Thank you, it seems good. Just another question: >>> fd, filename = tempfile.mkstemp() >>> type(fd) <type 'int'> I would expect a file descriptor, not and integer. How do I have to use it? From fabiofz at gmail.com Fri Aug 3 17:25:01 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Fri, 3 Aug 2007 18:25:01 -0300 Subject: Eclipse/PyDev question. In-Reply-To: <1186153119.391091.275860@r34g2000hsd.googlegroups.com> References: <1186153119.391091.275860@r34g2000hsd.googlegroups.com> Message-ID: <cfb578b20708031425p7e3213d2v36733bb868813fff@mail.gmail.com> On 8/3/07, king kikapu <aboudouvas at panafonet.gr> wrote: > > Hi, > this is actually a question to those of us who use Eclipse and Pydev > as their main Python developing environment. As i use Eclipse (3.3 > Europa) only for Python and i have nothing to do with Java, is there a > way to disable/uninstall some Java-specific stuff and make the > environment actually more snappy ?? > > thanks for any help > > You can actually just get the Eclipse 'runtime' distribution (without java stuff) and install pydev with it (latest version -- previous versions had a dependency on some java stuff). Reference: http://pydev.blogspot.com/2007/06/pydev-and-jdt-sdk-not-required-anymore.html Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070803/457e0cad/attachment.html> From gherron at islandtraining.com Sat Aug 4 17:47:49 2007 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 04 Aug 2007 14:47:49 -0700 Subject: Question -- Running Programming Python Examples In-Reply-To: <1186263007.587499.305340@57g2000hsv.googlegroups.com> References: <1186263007.587499.305340@57g2000hsv.googlegroups.com> Message-ID: <46B4F405.10302@islandtraining.com> chernevik at gmail.com wrote: > Here is a newbie question: how do I get the server examples in the > Preview chapter of "Progamming Python" (Lutz) to run? The code is > supposed to be a little webserver on which to run examples, but when I > run it it I get "permission denied". Running it as root gets "address > already in use". > > Here is the code (it's example 2.32); comments are from Lutz, not me: > > webdir = '.' # where your html files and cgi-bin script directory > live > > port = 80 # default http://localhost/, else use http://localhost:xxxx/ > There's the trouble. You need special permission to open any of the ports up through 1023. As root, you have permission, but apparently some process already has that port opened, almost certainly a web server you start up at boot time, probably apache. So either kill off the web server that has port 80 opened, or better yet, just change the port to something else. A common choice is port 8080. This does not require superuser permission, and is probably free. port = 8080 If you do that, then you access the server on port 8080 with url's that look like this: http://localhost:8080/what/ever/..., or http://machine-name:8080/what/ever/..., Gary Herron > > > import os, sys > > from BaseHTTPServer import HTTPServer > > from CGIHTTPServer import CGIHTTPRequestHandler > > > > # hack for Windows: os.environ not propogated > > [deleted, I'm running linux] > . . . > > os.chdir(webdir) # run in html > root dir > > srvraddr = ("", port) # my hostname, > portnumber > > srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler) > > srvrobj.serve_forever() # run as > perpetual demon > > > END CODE > > > My other python scripts run fine. > > I'm running linux (debian). I'm not running an webserver (that I know > of anyway). > > I've fiddled with adding the subdirectory with the code to the python > path, but this doesn't seem to help either. I'm new to all this, but > I've been able to make the other stuff work, and I can't even find the > beginning of what I'm supposed to research to fix this. > > Any help would be greatly appreciated, and thanks for your time and > patience. > > From gnewsg at gmail.com Thu Aug 23 06:48:24 2007 From: gnewsg at gmail.com (billiejoex) Date: Thu, 23 Aug 2007 03:48:24 -0700 Subject: Impersonate another user temporarily (Unix and Windows) In-Reply-To: <mailman.161.1187858227.32294.python-list@python.org> References: <1187809798.274511.230240@z24g2000prh.googlegroups.com> <mailman.161.1187858227.32294.python-list@python.org> Message-ID: <1187866104.967297.324650@j4g2000prf.googlegroups.com> On 23 Ago, 10:38, Tim Golden <m... at timgolden.me.uk> wrote: > billiejoex wrote: > > Hi there. I'm writing a modification for a FTP server library I'm > > maintaining. > > Depending on the system I'd want to temporarily impersonate the logged > > user to perform actions on filesystem. > > Something like: > > > try: > > change_user('user', 'password') > > os.rmdir('dir') > > except: > > print "some error" > > finally: > > change_user('old_user', 'password') > > > On Unix I took at look at os.seteuid() and os.setegid() functions and > > I noticed they could be useful for my purpose. > > On Windows I have no idea about how could I emulate a similar > > behaviour. > > Could someone please point me in the right direction? > > (Warning: not tried, but at least gives you the things to Google for!) > > You need the win32security module from the pywin32 extensions. [1] > In particular, you want to look at the LogonUser and > ImpersonateLoggedOnUser functions. > > TJG > > [1]http://pywin32.sf.net- Nascondi testo tra virgolette - > > - Mostra testo tra virgolette - Thanks for suggestion. I made it. From david at asdf.asdf Sun Aug 26 21:58:35 2007 From: david at asdf.asdf (bambam) Date: Mon, 27 Aug 2007 11:58:35 +1000 Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com> <1187898049.734696.9500@l22g2000prc.googlegroups.com> <13csoronscqp7d2@corp.supernews.com> <1188090322.663217.102750@22g2000hsm.googlegroups.com> Message-ID: <13d4bucfm4m1lc4@corp.supernews.com> Ok, many environments are capable of cached evaluation of functions without variable parameters so range(5) is cached, but range(v) is re-evaluated every time. Is this defined behaviour? That is, is it defined what Python does for for i in f() I'm sure it must be, but I haven't seen it yet. If I have a user defined function returning a range, is it defined that the range function is called on every loop? If I have a function returning a range taking a parameter, for i in f(v) is it defined that the variable is evaluated for every loop? Steve. "Paul McGuire" <ptmcg at austin.rr.com> wrote in message news:1188090322.663217.102750 at 22g2000hsm.googlegroups.com... > On Aug 23, 11:50 pm, "bambam" <da... at asdf.asdf> wrote: >> Thank you, so generallizing: >> >> (1) Python re-evaluates the loop range on every loop, and >> (2) Python does short-circuit evaluation of conditions, in predictable >> order. >> >> Sorry about the bad question. >> > > A beginner would do well to work through the Python Tutorial (http:// > docs.python.org/tut/tut.html). I think your first "insight" is > actually incorrect, if I understand your wording. If I wrote: > > for i in range(1000000000): > # do something with i > > I'm quite certain that range(1000000000) is not evaluated on every > loop iteration. In fact, the range call generates a list containing > the values [0, 1, 2, ..., 999999999], and then for iterates over this > list. You can read this at > http://docs.python.org/tut/node6.html#SECTION006300000000000000000. > > On the other hand, if you are talking about a while loop, of course > the condition is evaluated on every loop - otherwise such a loop, once > entered, would never exit. > > Your second generalization is stated pretty plainly in > http://docs.python.org/tut/node7.html#SECTION007700000000000000000. > In fact, conditional short-circuiting is a consistent theme in most > Python functions and structures. The new any() and all() built-ins in > Python 2.5 for example, evaluate a list of values for their boolean > True/False-ness, any() returning True if any list entry is True, > otherwise False; and all() returning True if all entries are True, > otherwise False. Both short-circuit their evaluation, so that if the > first element of a billion element list gives a True value for any() > (or a False value for all()), then the evaluation of the remaining > billion-1 items is skipped. > > Best of luck in your new Python learning process, > -- Paul > From victor.lebrun at gmail.com Wed Aug 22 05:57:25 2007 From: victor.lebrun at gmail.com (vml) Date: Wed, 22 Aug 2007 09:57:25 -0000 Subject: ActiveX control in python vs ActiveX control in vb 6 (piece of code) Message-ID: <1187776645.947080.81730@x35g2000prf.googlegroups.com> Hello, I am trying to mograte from vb 6 to python. I have a very usefull AX control. It can be : -just a bitmap -an active picture where you can plot data and put cursors -a data explorer Those 3 behavior are driven by one property in visual studio when you insert the AX control in a form: the property ModuleName: -'default' for bitmap -'Picture' for a picture I try to insert this AX control in a wxpython based application (I used one of the example delivered with wx) but when I try to change the property to get an active picture it does not work and display me the default bitmap :( Here is the pice of code #################################################################################### import wx if wx.Platform == '__WXMSW__': from wx.lib.activexwrapper import MakeActiveXClass import win32com.client try: ocx = win32com.client.gencache.EnsureModule('{33924602- C29E-4915-91B1-767CA3D675C2}',0x0,1,0) except: raise ImportError("Can't load ocx") #---------------------------------------------------------------------- class TestPanel(wx.Panel): def __init__(self, parent, log): wx.Panel.__init__(self, parent, -1) self.pdf = None sizer = wx.BoxSizer(wx.VERTICAL) btnSizer = wx.BoxSizer(wx.HORIZONTAL) # this function creates a new class that can be used as # a wxWindow, but contains the given ActiveX control. coclass=ocx.ActiveXModuleLoader print coclass coclass.ModuleName='picture' ActiveXWrapper = MakeActiveXClass(coclass) # create an instance of the new class self.pdf = ActiveXWrapper(self) #self.pdf.ModuleName='PictureManager' sizer.Add(self.pdf, 1, wx.EXPAND) btn = wx.Button(self, wx.NewId(), "Open PDF File") wx.EVT_BUTTON(self, btn.GetId(), self.OnOpenButton) btnSizer.Add(btn, 1, wx.EXPAND|wx.ALL, 5) btn = wx.Button(self, wx.NewId(), "<-- Previous Page") wx.EVT_BUTTON(self, btn.GetId(), self.OnPrevPageButton) btnSizer.Add(btn, 1, wx.EXPAND|wx.ALL, 5) btn = wx.Button(self, wx.NewId(), "Next Page -->") wx.EVT_BUTTON(self, btn.GetId(), self.OnNextPageButton) btnSizer.Add(btn, 1, wx.EXPAND|wx.ALL, 5) btnSizer.Add((50, -1), 2, wx.EXPAND) sizer.Add(btnSizer, 0, wx.EXPAND) self.SetSizer(sizer) self.SetAutoLayout(True) wx.EVT_WINDOW_DESTROY(self, self.OnDestroy) def OnDestroy(self, evt): if self.pdf: self.pdf.Cleanup() self.pdf = None def OnOpenButton(self, event): print 'open' def OnPrevPageButton(self, event): print 'button' def OnNextPageButton(self, event): print self.pdf.ModuleName #---------------------------------------------------------------------- def runTest(frame, nb, log): if wxPlatform == '__WXMSW__': win = TestPanel(nb, log) return win else: dlg = wx.MessageDialog(frame, 'This demo only works on MSW.', 'Sorry', wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() overview = __doc__ #---------------------------------------------------------------------- if __name__ == '__main__': import sys class TestFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "ActiveX test", size=(640, 480), style=wx.DEFAULT_FRAME_STYLE| wx.NO_FULL_REPAINT_ON_RESIZE) self.tp = TestPanel(self, sys.stdout) app = wx.PySimpleApp() frame = TestFrame() frame.Show(True) app.MainLoop() ############################################################################# I suspect that the activex control is bugged .... but how to know that since it is working perfectly under visual studio vb 6 but not with python ?:( please help me ! From steve at holdenweb.com Sun Aug 12 13:49:18 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 12 Aug 2007 13:49:18 -0400 Subject: who is simpler? try/except/else or try/except In-Reply-To: <46bf4074$0$10626$4fafbaef@reader2.news.tin.it> References: <46bf4074$0$10626$4fafbaef@reader2.news.tin.it> Message-ID: <f9nh6r$fhe$1@sea.gmane.org> Fabio Z Tessitore wrote: > Hi all, > > reading Dive Into Python, on Chapter 6 (exception), I've found: > > "This code comes from the getpass module, a wrapper module for getting a > password from the user" > > try: > import termios, TERMIOS > except ImportError: > try: > import msvcrt > except ImportError: > try: > from EasyDialogs import AskPassword > except ImportError: > getpass = default_getpass > else: > getpass = AskPassword > else: > getpass = win_getpass > else: > getpass = unix_getpass > > Knowing that this code is very simple, my question is about simplicity. I > think it is simpler the following code. I haven't a long experience on > Python, so I'd like to know your opinions about. > > try: > import termios, TERMIOS > getpass = unix_getpass > > except ImportError: > try: > import msvcrt > getpass = win_getpass > > except ImportError: > try: > from EasyDialogs import AskPassword > getpass = AskPassword > > except ImportError: > getpass = default_getpass > In matters of style such as this there *are* only opinions. I don't think there are definite grounds for preferring either one. If you were to propose such a patch on the python-dev list, it would almost certainly be rejected - not because it is necessarily worse, but because it would represent a change of style only. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From tleeuwenburg at gmail.com Thu Aug 30 15:34:16 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: Thu, 30 Aug 2007 19:34:16 -0000 Subject: Trouble using sys.settrace In-Reply-To: <1188502289.484027.322520@z24g2000prh.googlegroups.com> References: <1188502289.484027.322520@z24g2000prh.googlegroups.com> Message-ID: <1188502456.936992.315800@e9g2000prf.googlegroups.com> On Aug 31, 5:31 am, "tleeuwenb... at gmail.com" <tleeuwenb... at gmail.com> wrote: > The code below produces no output. I would expect to see: > > tracing... > tracing... > tracing... > tracing... > tracing... > > I was wondering if anyone had any experience with this. Never mind, now it works. > > ================================= > import sys > > def mytrace(frame, event, arg): > print "tracing..." > > sys.settrace(mytrace) > > def foo(): > for i in range(5): > print i > > foo() From vedrandekovic at v-programs.com Wed Aug 8 04:19:25 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Wed, 08 Aug 2007 01:19:25 -0700 Subject: setuptools Message-ID: <1186561165.946173.54590@19g2000hsx.googlegroups.com> Hello, If anybody have experiences with setuptools, I was download bbfreeze-0.95.2-py2.4-win32.egg and when I run installation with cmd: $ easy_install bbfreeze-0.95.2-py2.4-win32.egg Processing bbfreeze-0.95.2-py2.4-win32.egg Removing c:\Python24\lib\site-packages\bbfreeze-0.95.2-py2.4-win32.egg creating c:\Python24\lib\site-packages\bbfreeze-0.95.2-py2.4-win32.egg Extracting bbfreeze-0.95.2-py2.4-win32.egg to c:\Python24\lib\site- packages Adding bbfreeze 0.95.2 to easy_install.pth file Installed c:\Python24\lib\site-packages\bbfreeze-0.95.2-py2.4- win32.egg Processing dependencies for bbfreeze==0.95.2 error: None If this installation is successfully then where is installed module? Regards, Vedran From indu_shreenath at yahoo.co.in Thu Aug 9 03:08:38 2007 From: indu_shreenath at yahoo.co.in (Indu Shreenath) Date: Thu, 9 Aug 2007 08:08:38 +0100 (BST) Subject: how to get command output using python Message-ID: <915532.68360.qm@web8605.mail.in.yahoo.com> Hey, I want to get the output of DIR /AD /B to a variable using python. How to do this? Thanks, Indu --------------------------------- Download prohibited? No problem. CHAT from any browser, without download. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070809/79440625/attachment.html> From __peter__ at web.de Thu Aug 9 04:38:51 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 09 Aug 2007 10:38:51 +0200 Subject: Help with Dictionaries and Classes requested please. References: <46bacae3$0$89254$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <f9ejqr$e9q$00$1@news.t-online.com> special_dragonfly wrote: > I'm new to this group, I've read through the subject of a lot of the group > but can't find anything relevant. Perhaps my question is too basic but I'm > still stuck. > Classes and Dictionaries. > If I have a dictionary, how do I instantiate many instances of a class per > dictionary key? Either at run-time or dynamically. > Can anyone help me please? No, your question is too vague rather than too basic. What are you trying to do? Please give a concrete example and perhaps some code that you already have. Peter From omari at smileystation.com Thu Aug 23 12:27:39 2007 From: omari at smileystation.com (Omari Norman) Date: Thu, 23 Aug 2007 12:27:39 -0400 Subject: optparse - required options In-Reply-To: <46CA0814.6050200@jayloden.com> References: <496954360708201251r137dfaedqe632361891eae343@mail.gmail.com> <46C9F7D1.9040506@jayloden.com> <496954360708201353v19ea266cr50f144d1d71d5912@mail.gmail.com> <46CA0814.6050200@jayloden.com> Message-ID: <20070823162739.GA28165@cameron> On Mon, Aug 20, 2007 at 05:31:00PM -0400, Jay Loden wrote: > Robert Dailey wrote: > > Well, I don't know what is wrong with people then. I don't see how > > required arguments are of bad design. Some command-line applications are > > built around performing tasks based on information received. Compilers, > > for example. A compiler can't do much of anything unless you give it at > > the very least a filename. So, a --file command would most definitely be > > one required argument. Anyway, I'm not trying to start a debate on this > > issue. I have my own implementation for required arguments at the > > moment, I am just a little bit surprised that this module doesn't make > > it convenient. It would definitely help on code duplication. > > > > Thanks for your response. > > I tend to agree...while "required option" may be an oxymoron in > English, I can think of quite a few scripts I've written myself (in > various languages) that needed at least some kind of user input to > operate. At least the documentation points to some examples for > helpful hints, example code is a lot better than nothing ;) The idea with optparse is not that programs should not require certain information on the command line; rather, the idea is that this information should be positional arguments, not 'options'. That is, to use the compiler example: compiler file is preferred if a file argument is necessary. compiler --file file is not preferred. -- Due to some violent content, viewer discretion is advised. From theokok2000 at gmail.com Tue Aug 14 19:34:46 2007 From: theokok2000 at gmail.com (theokok2000 at gmail.com) Date: Tue, 14 Aug 2007 23:34:46 -0000 Subject: ooh-yes Message-ID: <1187134486.195058.77030@22g2000hsm.googlegroups.com> http://Theologos.kokkonis.googlepages.com/ http://kokonis.aygoystinos.googlepages.com/ From ptmcg at austin.rr.com Wed Aug 15 09:10:59 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 15 Aug 2007 06:10:59 -0700 Subject: Retry: Question about FutureWarning In-Reply-To: <ubKdnTirKeU6xl_bnZ2dnUVZ_rzinZ2d@speakeasy.net> References: <mailman.1994.1187142273.22759.python-list@python.org> <ubKdnTirKeU6xl_bnZ2dnUVZ_rzinZ2d@speakeasy.net> Message-ID: <1187183459.675090.194800@w3g2000hsg.googlegroups.com> On Aug 14, 8:49 pm, Erik Max Francis <m... at alcyone.com> wrote: > Steven W. Orr wrote: > > M1.py:268: FutureWarning: hex/oct constants > sys.maxint will > > return positive values in Python 2.4 and up > > StartTime = safe_dict_get ( dic, 'starttime', 0xFFFFFFFF ) > ... > > import warnings > > warnings.filterwarnings('ignore', category=FutureWarning) > > > My question is this: Why can the warning not be shut off by putting the > > two lines in M1 where the reference exists to 0xFFFFFFFF ? > > You really don't want to shut off the warning; it means just what it says: > > Python 2.3.5 (#1, Feb 8 2005, 23:36:23) > [GCC 3.2.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> 0xffffffff > <stdin>:1: FutureWarning: hex/oct constants > sys.maxint will return > positive values in Python 2.4 and up > -1 > > Python 2.4.3 (#1, Mar 29 2006, 17:16:11) > [GCC 3.2.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> 0xffffffff > 4294967295L > > -- > Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/ > San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis > Black vinyl man with black plasticized imagination > -- Nik Kershaw So if by '0xFFFFFFFF' you meant -1, then change this line to use -1. Otherwise, if you really meant 4294967295L, leave it at 0xFFFFFFFF and move on. -- Paul From arkanes at gmail.com Wed Aug 1 12:31:53 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 1 Aug 2007 11:31:53 -0500 Subject: Awkward format string In-Reply-To: <1185984697.605529.157110@g12g2000prg.googlegroups.com> References: <1185984697.605529.157110@g12g2000prg.googlegroups.com> Message-ID: <4866bea60708010931x438e2e76p2a3d2e83f20e9689@mail.gmail.com> On 8/1/07, beginner <zyzhu2000 at gmail.com> wrote: > Hi, > > In order to print out the contents of a list, sometimes I have to use > very awkward constructions. For example, I have to convert the > datetime.datetime type to string first, construct a new list, and then > send it to print. The following is an example. > > x=(e[0].strftime("%Y-%m-%d"), e[1].strftime("%Y-%m-%d"))+e[2:] > print >>f, "%s\t%s\t%d\t%f\t%f\t%f\t%d" % x > > e is a tuple. x is my new tuple. > > Does anyone know better ways of handling this? > You seem to be doing quite complicated things with your magical e tuple. Do you have some specific aversion to classes? From cai.haibin at gmail.com Mon Aug 6 22:09:56 2007 From: cai.haibin at gmail.com (james_027) Date: Tue, 07 Aug 2007 02:09:56 -0000 Subject: help with flexible decorators Message-ID: <1186452596.052963.136840@e9g2000prf.googlegroups.com> Hi, I want to write a flexible decorators to edit a function that may have 1 or more arguments... def enhance(func): def new(x): #do something ... return func(x) return new @enhance def method_a(x): #do something ... While the enhance decorator work with functions of 1 argument, how do I make it to work with more than one arguments. Thanks james From redtiger84 at googlemail.com Tue Aug 7 13:28:24 2007 From: redtiger84 at googlemail.com (Christoph Krammer) Date: Tue, 07 Aug 2007 10:28:24 -0700 Subject: re.sub does not replace all occurences Message-ID: <1186507704.440408.20630@57g2000hsv.googlegroups.com> Hello everybody, I wanted to use re.sub to strip all HTML tags out of a given string. I learned that there are better ways to do this without the re module, but I would like to know why my code is not working. I use the following: def stripHtml(source): source = re.sub("[\n\r\f]", " ", source) source = re.sub("<.*?>", "", source, re.S | re.I | re.M) source = re.sub("&(#[0-9]{1,3}|[a-z]{3,6});", "", source, re.I) return source But the result still has some tags in it. When I call the second line multiple times, all tags disappear, but since HTML tags cannot be overlapping, I do not understand this behavior. There is even a difference when I omit the re.I (IGNORECASE) option. Without this option, some tags containing only capital letters (like </FONT>) were kept in the string when doing one processing run but removed when doing multiple runs. Perhaps anyone can tell me why this regex is behaving like this. Thanks and regards, Christoph From bdesth.quelquechose at free.quelquepart.fr Thu Aug 30 06:48:08 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 30 Aug 2007 12:48:08 +0200 Subject: Creating a multi-tier client/server application In-Reply-To: <1188479584.073309.297770@x40g2000prg.googlegroups.com> References: <1188360460.838635.186930@w3g2000hsg.googlegroups.com> <7xbqcqhqbw.fsf@ruckus.brouhaha.com> <46d54ed8$0$429$426a34cc@news.free.fr> <1188393925.007952.313110@r29g2000hsg.googlegroups.com> <7xy7ft4fqg.fsf@ruckus.brouhaha.com> <1188479584.073309.297770@x40g2000prg.googlegroups.com> Message-ID: <46d73e73$0$10724$426a34cc@news.free.fr> vanrpeterson at gmail.com a ?crit : (snip) > We have found the object-relationship managers Actually, ORM stands for "object-relational mapper" > to be bloated > and unruly. Which ones ? From steve at holdenweb.com Wed Aug 29 06:49:02 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 29 Aug 2007 06:49:02 -0400 Subject: Gmane's been quiet ... In-Reply-To: <1i3lsqu.10ti61g1fs47osN%raims@dot.com> References: <mailman.88.1188343014.28954.python-list@python.org> <1i3l2k9.1j3tdgr1iz19yeN%raims@dot.com> <13d9l0f1i2erdc6@corp.supernews.com> <1i3lsqu.10ti61g1fs47osN%raims@dot.com> Message-ID: <fb3iur$o05$1@sea.gmane.org> Lawrence Oluyede wrote: > Grant Edwards <grante at visi.com> wrote: >> Posting that were made to mailing lists via gmane? > > That, I do not know > Given that I have now read a reply to my post-via-gmane on gmane before seeing the original post appear there I shall assume they've been having some sort of issue. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From python at lindin.eu Tue Aug 28 06:37:08 2007 From: python at lindin.eu (Python list) Date: Tue, 28 Aug 2007 12:37:08 +0200 Subject: Dead lock in pymat after using threading? Message-ID: <5caec3a20708280337h6a230100ma7b14c4523770f5a@mail.gmail.com> "Hi, I'm having problems using the package pymat after using threading, e.g. the line: # h = pymat.open() # is not possible to fully execute after the lines: # import threading from time import sleep def SlpFcn(): sleep(5) print "end of sleep" trd = threading.Thread(target=SlpFcn) trd.start() # MATLAB is started as it should, but the python interpreter does not answer and has to be shut down using CTRL+ALT+DEL. After restarting the interpreter it is possible to use pymat again without problems (seems to be some kind of memory issue). What differences between before and after threading are there, that could cause these problems? ("del trd" or "gc.collect" after the threading, does not solve my problem.) I'm using Python 2.2 in ControlDesk, Windows XP. Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070828/9bb9232c/attachment.html> From grante at visi.com Fri Aug 24 16:55:23 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 24 Aug 2007 20:55:23 -0000 Subject: py2exe/distutils: how to include a tree of files? Message-ID: <13cuhdr58m5one7@corp.supernews.com> I'm packaging up a python program and need to include an entire directory tree in the distribution. the data_files=[] option to setup() is fine for individual files, but what do I do when I need to include an entire directory tree? On a more general note, I'm having trouble finding much documentation on py2exe at all. There's a wiki page at py2exe.org, but it's pretty superficial. It mentions looking at the distutils documentation for details, but I've no idea how distutils relates to py2exe or where in the distutils documentation to look for py2exe stuff (I don't see anything that looks familiar in the distutils docs). There must be some py2exe documentation somewhere... [http://sourceforge.net/projects/py2exe/ hasn't been updated in 5 years, is there any reason why it's still around?] -- Grant Edwards grante Yow! LBJ, LBJ, how many at JOKES did you tell today??! visi.com From bscrivener42 at gmail.com Wed Aug 15 12:01:56 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Wed, 15 Aug 2007 16:01:56 -0000 Subject: Simple python iteration question In-Reply-To: <mailman.1974.1187110840.22759.python-list@python.org> References: <bFkwi.675$Oo.563@newssvr17.news.prodigy.net> <20070814163430.GJ22017@lass.lfod.us> <mailman.1974.1187110840.22759.python-list@python.org> Message-ID: <1187193716.041459.232490@e9g2000prf.googlegroups.com> On Aug 14, 11:59 am, "Shawn Milochik" <Sh... at Milochik.com> wrote: > Just for my own sanity: Isn't this the third response advocating the > use of enumerate()? Did the other responses not get through, or was > this a time-delay thing? > > Thanks, > Shawn Look at the timestamps. All within ten minutes. And those ten minutes are spent keyboarding your response in and posting, plus it takes several minutes for the posts to appear on Google Groups. rd From bronger at physik.rwth-aachen.de Sun Aug 26 18:47:19 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 27 Aug 2007 00:47:19 +0200 Subject: my parser.py isn't imported References: <874pimqpei.fsf@wilson.homeunix.com> <1188166462.066732.123620@i13g2000prf.googlegroups.com> Message-ID: <87ps19q5fs.fsf@wilson.homeunix.com> Hall?chen! John Machin writes: > On Aug 27, 1:36 am, Torsten Bronger <bron... at physik.rwth-aachen.de> > wrote: > >> I have a module parser.py in the same directory as the main >> module. In the main module, I import "parser". On Linux, this >> works as expected, however on Windows, it imports the stdlib >> parser module. sys.path[0] points to the directory of my >> parser.py in both cases. What went wrong here? > > Ask a literal question, get a literal answer :-) > > 1. Failure to consider that problems can happen [and therefore > will happen [1]] when there are multiple entities with the same > name. So I'd like to know a means to tell *explicitly* what I want to import. Maybe I could use the imp module but that's ugly. I mean, there are hundreds of modules on my harddisk, so trying to avoid nameclashs should not be the solution, and given ... > 2. Failure to RTFabulousM: > """ > Details of the module searching and loading process are > implementation and platform specific. It generally involves > searching for a ``built- in'' module with the given name and then > searching a list of locations given as sys.path. > """ ... the whole systems seems largely arbitrary, which I don't believe. ;-) "parser" is built-in on Windows but not on Linux. What's the list of modules that *may* be built-in on some platform or implementation? Or should I avoid the whole standard lib for names of my modules? Or even everything which is shipped e.g. with Enthought Python? I find this quite irritating. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From carsten at uniqsys.com Fri Aug 31 14:39:51 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 31 Aug 2007 14:39:51 -0400 Subject: So what exactly is a complex number? In-Reply-To: <eb79828c0708311013j3fadb9ejda3c63ca6e8d7165@mail.gmail.com> References: <eb79828c0708301811r38c836cdqf29382c31923c220@mail.gmail.com> <1188576174.3479.9.camel@dot.uniqsys.com> <mailman.215.1188576767.28954.python-list@python.org> <1188579019.141544.292210@50g2000hsm.googlegroups.com> <eb79828c0708311013j3fadb9ejda3c63ca6e8d7165@mail.gmail.com> Message-ID: <1188585591.3479.34.camel@dot.uniqsys.com> On Fri, 2007-08-31 at 11:13 -0600, Lamonte Harris wrote: > >Is English your native language? I'm having a hard time decoding your > question. > dont be an ass.... I'm sorry you took it this way. I was only trying to help. It won't happen again. -- Carsten Haese http://informixdb.sourceforge.net From larry.bates at websafe.com Thu Aug 2 10:05:35 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 02 Aug 2007 09:05:35 -0500 Subject: Directory In-Reply-To: <1185831827.206641.163630@x40g2000prg.googlegroups.com> References: <1185831827.206641.163630@x40g2000prg.googlegroups.com> Message-ID: <46B1E4AF.909@websafe.com> Rohan wrote: > I would like to get a list of sub directories in a directory. > If I use os.listdir i get a list of directories and files in that . > i only want the list of directories in a directory and not the files > in it. > anyone has an idea regarding this. > import os listofdirs=[d for d in os.listdir(mydir) if os.pathisdir(d)] -Larry From gtcopeland at gmail.com Tue Aug 21 15:51:11 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: Tue, 21 Aug 2007 12:51:11 -0700 Subject: Problem with Thread.join() In-Reply-To: <mailman.29.1187626375.26576.python-list@python.org> References: <496954360708131610i62c0a63aneb7c39d23a052ac0@mail.gmail.com> <op.txcl3yoox6zn5v@a98gizw.cpe.telecentro.net.ar> <8a6b8e350708200758w640fd7c4w5bd19fb53decde71@mail.gmail.com> <mailman.29.1187626375.26576.python-list@python.org> Message-ID: <1187725871.271309.64830@22g2000hsm.googlegroups.com> On Aug 20, 11:12 am, "Robert Dailey" <rcdai... at gmail.com> wrote: > Hey guys, > > Sorry for taking so long to respond. I had actually figured out what > this issue is over on the wxPython mailing list. The issue was that I > was attempting to configure wxPython controls from a remote thread, > which is apparently illegal due to some state persistance issues. > As a rule of thumb, only one thread *ever* controls the GUI. Greg From bignose+hates-spam at benfinney.id.au Tue Aug 28 19:22:02 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 29 Aug 2007 09:22:02 +1000 Subject: Check for dict key existence, and modify it in one step. References: <1188311810.226363.295500@w3g2000hsg.googlegroups.com> <87bqcrfeku.fsf@benfinney.id.au> Message-ID: <877inffdnp.fsf@benfinney.id.au> Ben Finney <bignose+hates-spam at benfinney.id.au> writes: > foo.setdefault(whatever, {}) > foo[whatever].setdefault(someother, 0) > foo[whatever] += delta Should, of course, be: foo.setdefault(whatever, {}) foo[whatever].setdefault(someother, 0) foo[whatever][someother] += delta -- \ "My house is made out of balsa wood, so when I want to scare | `\ the neighborhood kids I lift it over my head and tell them to | _o__) get out of my yard or I'll throw it at them." -- Steven Wright | Ben Finney From daniels at dsl-only.net Sat Aug 25 06:20:09 2007 From: daniels at dsl-only.net (Scott David Daniels) Date: Sat, 25 Aug 2007 03:20:09 -0700 Subject: beginner, idiomatic python In-Reply-To: <13ct7v3qn2v5206@corp.supernews.com> References: <13cqlqbbpn0dmea@corp.supernews.com><1187898049.734696.9500@l22g2000prc.googlegroups.com><13csi2tn49esmc3@corp.supernews.com> <mailman.230.1187928865.32294.python-list@python.org> <13csqk47j0c56b0@corp.supernews.com> <CqSdnRl2x8928FPbnZ2dnUVZ_jSdnZ2d@speakeasy.net> <13ct7v3qn2v5206@corp.supernews.com> Message-ID: <13d00hu2mflt01b@corp.supernews.com> bambam wrote: >> The reason that lists don't have set-like methods is because >> lists aren't sets -- lists can contain duplicate elements and they are ordered. I'd have used sets if I was sure you meant [1,2,3] to mean the same thing as [3,1,2] and no duplicates. > Interesting point -- if that's all there is in it, then lists should > have difference and intersection methods. Not because they > are the same as sets -- because they are slightly different than > sets. In this case it doesn't matter - my lists don't contain > duplicate elements this time - but I have worked with lists in > money market and in inventory, and finding the intersection > and difference for matching off and netting out are standard > operations. Here you seem to be talking about multisets (also called bags). They have more fully defined algebraic properties analogous to sets. bag([1,2,3,3,4]) == bag([3,1,2,4,3]) != bag([1,2,3,4]) bag([1,2,2,3]) - bag([1,2]) == bag([2,3]) bag([1,2,3]) - bag([3,4]) == bag([1]) >>> Excellent. By symmetry, I see that "list" casts the set back into a list. Some will say 'sorted' is a better conversion of a set to list, since the result is well-defined. --Scott David Daniels Scott.Daniels at Acm.Org From ldo at geek-central.gen.new_zealand Tue Aug 28 01:05:01 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 28 Aug 2007 17:05:01 +1200 Subject: "Try:" which only encompasses head of compound statement References: <1188250535.607963.42540@22g2000hsm.googlegroups.com> <1188256903.075011.173820@k79g2000hse.googlegroups.com> Message-ID: <fb0a99$hgr$2@lust.ihug.co.nz> In message <1188256903.075011.173820 at k79g2000hse.googlegroups.com>, Carl Banks wrote: > Consider this: is there any other code in your program that has to do > something different based on whether you successfully opened this file > or not? If so, how will you notify it whether the call has succeeded > or not? Very often, the caller itself needs to know. You could, say, > set a flag to indicate it's failed, but why do that when you could > simply let the caller detect and handle the error itself? I am generally wary of exceptions, and like to contain them as much as possible. So my answer to your point is something like try : f = open(TheFile, "r") except IOError, (ErrNo, Msg) : if ErrNo != errno.ENOENT : raise #end if f = None #end try (Note how I check for the specific error code I want to handle.) Then later on I can determine if the file was successfully opened by if f != None : ... further processing on f ... #end if From zyzhu2000 at gmail.com Thu Aug 16 23:16:32 2007 From: zyzhu2000 at gmail.com (beginner) Date: Fri, 17 Aug 2007 03:16:32 -0000 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: <1187303750.590497.208060@x40g2000prg.googlegroups.com> References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> Message-ID: <1187320592.942822.318630@z24g2000prh.googlegroups.com> On Aug 16, 5:35 pm, beginner <zyzhu2... at gmail.com> wrote: > Hi All. > > I'd like to do the following in more succint code: > > if k in b: > a=b[k] > else: > a={} > b[k]=a > > a['A']=1 > > In perl it is just one line: $a=$b->{"A"} ||={}. > > Thanks, > Geoffrey It looks like defaultdict is the solution for this kind of thing. Thanks all for your help. From laurent.pointal at limsi.fr Thu Aug 2 03:09:49 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Thu, 02 Aug 2007 09:09:49 +0200 Subject: Equivalent to gzinflate() function in PHP. In-Reply-To: <pan.2007.08.02.06.27.03.891918@artcom.pl> References: <pan.2007.08.01.13.44.47.273887@artcom.pl> <1185976461.491418.20230@i38g2000prf.googlegroups.com> <pan.2007.08.02.06.17.09.653367@artcom.pl> <pan.2007.08.02.06.27.03.891918@artcom.pl> Message-ID: <f8rvvt$rjd$1@news2.u-psud.fr> Adam Kubica a ?crit : > After some king of brain fucked tries, I found: > > zlib.decompress( data ) #equivalent gzdecompress() > zlib.decompress( data, -zlib.MAX_WBITS ) #equivalent gzdeflate() Note: you can also use encode() and decode() methods on the string containing your data, specifying 'zip' as encoding. Example: >>> s="Hello"*100 >>> s1 = s.encode('zip') >>> len(s1) 18 >>> s1 'x\x9c\xf3H\xcd\xc9\xc9\xf7\x18%F\x12\x01\x00\t\xb9\xc3Q' >>> s2 = s1.decode('zip') >>> len(s2) 500 >>> s2 'HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHell oHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHell oHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHell oHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHell oHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHell oHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHell oHelloHelloHelloHello' >>> IMHO this is mode understandable than zlib.decompress( data, -zlib.MAX_WBITS ). A+ Laurent. PS. There may be other compression encodings... look at encodings.aliases.aliases, where I can see 'zip' and 'zlib' (same), but also 'bz2'. - you can also found encoders for hexadecimal, quoted printable, and other formats. From smbaker at gmail.com Wed Aug 15 15:36:23 2007 From: smbaker at gmail.com (Scott) Date: Wed, 15 Aug 2007 12:36:23 -0700 Subject: threads, mutual exclusion, and lists Message-ID: <1187206583.255588.57920@e9g2000prf.googlegroups.com> I have two threads that share a python list. One thread adds to the list with append(), the other thread removes items with pop(). My question is -- are python list operations atomic? If they are not, then I assume I need to put some mutual exclusion around the append() and pop() calls ? Thanks, Scott From aleax at mac.com Thu Aug 2 11:45:13 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 2 Aug 2007 08:45:13 -0700 Subject: Pythonic way for missing dict keys References: <mailman.938.1184958565.22759.python-list@python.org> <pan.2007.07.21.00.20.54.768439@REMOVE.THIS.cybersource.com.au> <mailman.954.1184989959.22759.python-list@python.org> <Xns99748CC2DB4AAduncanbooth@127.0.0.1> <1185041243.323915.161230@x40g2000prg.googlegroups.com> <mailman.984.1185101740.22759.python-list@python.org> <87lkd0eprj.fsf@pobox.com> <mailman.1279.1185623588.22759.python-list@python.org> <pan.2007.07.29.04.10.19.329342@REMOVE.THIS.cybersource.com.au> <46b0ed0b$0$2257$426a74cc@news.free.fr> <mailman.1493.1186042809.22759.python-list@python.org> <46b1b0ba$0$25340$426a74cc@news.free.fr> Message-ID: <1i27mku.1sc8l3x1dda3crN%aleax@mac.com> Bruno Desthuilliers <bruno.42.desthuilliers at wtf.websiteburo.oops.com> wrote: > Alex Popescu a ?crit : > > Bruno Desthuilliers <bdesth.quelquechose at free.quelquepart.fr> wrote in > > news:46b0ed0b$0$2257$426a74cc at news.free.fr: > (snip) > >> if hasattr(obj, '__call__'): > >> # it's a callable > >> > >> but I don't find it so Pythonic to have to check for a __magic__ > >> method. > > > > It looks like Python devs have decided it is Pythonic, because it is > > already in the PEP. > > I do know, and I disagree with this decision. > > FWIW, repr(obj) is mostly syntactic sugar for obj.__repr__(), > getattr(obj, name) for obj.__getattr__(name), type(obj) for > obj.__class__ etc... IOW, we do have a lot of builtin functions that > mostly encapsulate calls to __magic__ methods, and I definitively don't > understand why this specific one (=> callable(obj)) should disappear. I Maybe because it DOESN'T "encapsulate a call" to a magic method, but rather the mere check for the presence of one? > usually have lot of respect for Guido's talent as a language designer > (obviously since Python is still MFL), but I have to say I find this > particular decision just plain stupid. Sorry. The mere check of whether an object possesses some important special method is best accomplished through the abstract-base-classes machinery (new in Python 3.0: see <http://www.python.org/dev/peps/pep-3119/>). At this time there is no Callable ABC, but you're welcome to argue for it on the python-3000 mailing list (please do check the archives and/or check privately with the PEP owner first to avoid duplication). Alex From SMERSH009X at gmail.com Fri Aug 3 23:18:43 2007 From: SMERSH009X at gmail.com (SMERSH009) Date: Sat, 04 Aug 2007 03:18:43 -0000 Subject: Website data-mining. In-Reply-To: <mailman.1603.1186196436.22759.python-list@python.org> References: <mailman.1603.1186196436.22759.python-list@python.org> Message-ID: <1186197523.939667.262620@e16g2000pri.googlegroups.com> On Aug 3, 7:50 pm, Coogan <pcb2... at columbia.edu> wrote: > Hi-- > > I'm using Python for the first time to make a plug-in for Firefox. > The goal of this plug-in is to take the source code from a website > and use the metadata and body text for different kinds of analysis. > My question is: How can I retrieve data from a website? I'm not even > sure if this is possible through Python. Any help? > > nieu How about this? it will fetch the HTML source of the page. import datetime, time, re, os, sys, traceback, smtplib, string,\ urllib2, urllib, inspect from urllib2 import build_opener, HTTPCookieProcessor, Request opener = build_opener(HTTPCookieProcessor) from urllib import urlencode def urlopen2(url, data=None, user_agent='urlopen2'): """Opens Our URLS """ if hasattr(data, "__iter__"): data = urlencode(data) headers = {'User-Agent' : user_agent} return opener.open(Request(url, data, headers)) ###TESTCASES START HERE### def publishedNotes(): page = urlopen2("http://www.yourURL.com", ()) pageRead = page.read() print pageRead if __name__ == '__main__': publishedNotes() sys.exit() From ldo at geek-central.gen.new_zealand Fri Aug 31 22:13:30 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 01 Sep 2007 14:13:30 +1200 Subject: strings (dollar.cents) into floats References: <mailman.140.1188483282.28954.python-list@python.org> <877incd20i.fsf@benfinney.id.au> <46d75cf3$0$7698$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <fbahnl$jeh$1@lust.ihug.co.nz> In message <46d75cf3$0$7698$9b4e6d93 at newsspool2.arcor-online.net>, Wildemar Wildenburger wrote: > But what use is there for floats, then? When is it OK to use > them? Floating-point numbers are useful when you have to deal with very large and very small amounts at the same time. In using them, you must understand something about how rounding errors work, e.g. 1) Addition of a lot of very precise quantities together will produce a less-precise quantity: >>> x = 0.1 >>> x 0.10000000000000001 >>> for i in range(0, 1000000) : x += 0.1 ... >>> x 100000.10000133289 (Note the original quantity was precise to over 16 figures, the accumulated total to less than 7.) 2) Subtraction of two nearly-equal quantities will also reduce precision: >>> 1.0 / 1000 0.001 >>> 1.0 / 1001 0.000999000999000999 >>> 1.0 / 1000 - 1.0 / 1001 9.9900099900102068e-07 (Again, note the drop from about 15 figures of precision down to about 12.) In terms of currency amounts, if you're only doing additions and subtractions, then usual practice would be to work in integer cents/pence, and format as dollars/euros/pounds/whatever and cents/pence only for display and user input. That way you avoid the above rounding problems. But if you're doing multiplications and divisions (e.g. currency conversions, taxation, interest computations, futures, derivatives etc), then it doesn't really matter. You're going to get rounding errors anyway, and floating point will probably let you manage them better than integers will. From jeff_barish at earthlink.net Fri Aug 31 11:18:34 2007 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Fri, 31 Aug 2007 09:18:34 -0600 Subject: Biased random? References: <favd0c$fcu$1@ss408.t-com.hr> <mailman.80.1188332647.28954.python-list@python.org> <fb77bq$jtk$1@ss408.t-com.hr> <fb7a3d$phj$1@sea.gmane.org> Message-ID: <fb9bg9$ibi$1@sea.gmane.org> Robert Kern wrote: > Ivan Voras wrote: >> Jeffrey Barish wrote: >> >>> If you take the difference between two uniformly distributed random >>> variables, the probability density function forms an isosceles triangle >>> centered at 0. Take the absolute value of that variable and the pdf is >>> a >>> straight line with maximum value at 0 tapering to 0 at max. Thus, >>> >>> z = abs(randint(0, max) - randint(0, max)) >>> >>> ought to do the trick. >> >> It's elegant :) >> >> I've noticed something interesting in my test: the value 0 appears less >> often than other values (which behave as they should). > > The distribution of the difference (before the abs()) looks like this > (max=4): > > # > ### > ##### > ####### > ---0+++ > 321 123 > > Taking the absolute value doubles up the non-zero masses, but there's no > "negative 0" to add to the 0s stack. > > # > # > ### > ### > #### > #### > 0123 > > The method does not work because of that. > The math says that it works, so we must not be implementing it correctly. I suspect that our mistake is quantizing the random variable first and then taking the difference and absolute value. What result do you get when you quantize once? That is, obtain two random values (floats) with uniform pdf. Take the difference. Abs. Round to int. This way, everything in the band from (-0.5, +0.5) goes to 0, and that's the highest part of the triangle. -- Jeffrey Barish From jonas.esp at googlemail.com Fri Aug 17 15:07:10 2007 From: jonas.esp at googlemail.com (Kless) Date: Fri, 17 Aug 2007 19:07:10 -0000 Subject: Encryption and hashing Message-ID: <1187377630.017794.36510@50g2000hsm.googlegroups.com> Since that I'm working to let encrypt/hash data in the data base of my projects I have been looking for libraries and/or wrappers. So I want give my feedback about it. In the first I found PyCrypto [1] but I see any problems: * I think that isn't been maintained because the last modification of its web was on 30 Sep 2006 * Since that has not been uploaded to SourceForge [2] we cann't know when was released the last version * There algorithms more secure and modern that it hasn't. Then, I found 2 great C libraries that are being maintained and updated with many algorithms. They're MCrypt [3] and MHash [4], and both have released the last version on this year. For who knows any of criptography I comment that you can use algorithms as secure as Rijndael, Twofish, or Serpent with the CFB cipher mode. And for hash you can use RIPEMD, SHA-2 or WHIRLPOOL. And the best is that there are wrappers for Python [5] [6]. For if anybody is interested on playing with them: In the first you need the headers. In Debian/Ubuntu: $ sudo apt-cache install libmcrypt-dev libmhash-dev $ wget http://labix.org/download/python-mcrypt/python-mcrypt-1.1.tar.gz $ wget http://labix.org/download/python-mhash/python-mhash-1.4.tar.gz $ tar xzf python-mcrypt*.tar.gz; tar xzf python-mhash*.tar.gz $ cd python-mhash*; sudo python setup.py install; cd .. $ cd python-mcrypt*; sudo python setup.py install; cd.. [1] http://www.amk.ca/python/code/crypto [2] http://sourceforge.net/projects/pycrypto [3] http://mcrypt.sourceforge.net/ [4] http://mhash.sourceforge.net/ [5] http://labix.org/python-mcrypt [6] http://labix.org/python-mhash From deets at nospam.web.de Tue Aug 21 09:46:33 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 21 Aug 2007 15:46:33 +0200 Subject: Module level descriptors or properties References: <1187700539.312552.89340@w3g2000hsg.googlegroups.com> Message-ID: <5j08lpF3qjmggU2@mid.uni-berlin.de> Floris Bruynooghe wrote: > Hi > > When in a new-style class you can easily transform attributes into > descriptors using the property() builtin. However there seems to be > no way to achieve something similar on the module level, i.e. if > there's a "version" attribute on the module, the only way to change > that to some computation later is by using a getter from the start as > your public API. This seems ugly to me. > > Does anyone know of a better way to handle this? Not really. All you can do is proxy all the calls through an actual object, most probably a singleton. Diez From bdesth.quelquechose at free.quelquepart.fr Mon Aug 6 01:56:32 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 06 Aug 2007 07:56:32 +0200 Subject: Heterogeneous lists In-Reply-To: <RPadnXFHmYYUIiXbnZ2dnUVZ_uKpnZ2d@comcast.com> References: <RPadnXFHmYYUIiXbnZ2dnUVZ_uKpnZ2d@comcast.com> Message-ID: <46b8cbdf$0$6956$426a74cc@news.free.fr> Gordon Airporte a ?crit : > This is one of those nice, permissive Python features but I was > wondering how often people actually use lists holding several different > types of objects. Depends on the definition of 'type'. I often have instances of different - possibly unrelated - classes in a same list. Fact is that these instances usually share a common (implied) interface, but, well, sometimes they don't... > It looks like whenever I need to group different objects I create a > class, if only so I can use more meaningful names than '[2]' for the items. You may not know, but Python has a builtin dict (ie : hashtable) type. It's very handy when you just want to "group different objects" while still using meaningful names. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Aug 31 08:10:35 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 31 Aug 2007 14:10:35 +0200 Subject: Pylons, SQLAlchemy, too many connections problem. In-Reply-To: <pan.2007.08.31.12.03.48.18688@artcom.pl> References: <pan.2007.08.31.12.03.48.18688@artcom.pl> Message-ID: <46d8052a$0$421$426a74cc@news.free.fr> Adam Kubica a ?crit : > Hello. > > I have pylons 0.96 (SVN) and current SQLAlchemy (0.3.10), and I have bug > that > doesn't exist earlier. > > My connection code: > <code> > import sqlalchemy.mods.threadlocal > from sqlalchemy import DynamicMetaData, objectstore > > metadata = DynamicMetaData( case_sensitive = False ) > > def db_connect( dsn ): > engine = create_engine( dsn, echo=False, echo_pool=False, > encoding='latin2', convert_unicode=True ) > metadata.connect( engine ) > </code> > > command "netstat -an|grep 5432|grep ESTABLISHED|wc -l" displays one > more connection after each refresh of page until I have exceptions > such as: > > sqlalchemy.exceptions.DBAPIError: (Connection failed) > (OperationalError) FATAL: sorry, too many clients already > > What is wrong? > I don't know for sure, but I guess you'd get better answers posting either on the Pylons or SQLAlchemy's google groups. From marc.girod at gmail.com Wed Aug 8 07:47:29 2007 From: marc.girod at gmail.com (Marc Girod) Date: Wed, 08 Aug 2007 11:47:29 -0000 Subject: KeyError: ... updated type, in planet Message-ID: <1186573649.525124.205890@22g2000hsm.googlegroups.com> Hello, I am using Planet 2.0 to generate RSS feeds from wiki pages. On some of my wikis, I get an error such as: ionawikis> sudo python2.5 /root/planet/planet.py -v ./tstconfig.ini DEBUG:planet.runner:Socket timeout set to 20 seconds INFO:planet.runner:Loading cached data Traceback (most recent call last): File "/root/planet/planet.py", line 211, in <module> main() File "/root/planet/planet.py", line 195, in main my_planet.run(planet_name, planet_link, template_files, offline) File "/root/planet/planet/__init__.py", line 300, in run channel = Channel(self, feed_url) File "/root/planet/planet/__init__.py", line 588, in __init__ self.cache_read_entries() File "/root/planet/planet/__init__.py", line 638, in cache_read_entries item = NewsItem(self, key) File "/root/planet/planet/__init__.py", line 933, in __init__ self.cache_read() File "/root/planet/planet/cache.py", line 74, in cache_read self._type[key] = self._cache[cache_key + " type"] File "/usr/lib/python2.5/bsddb/__init__.py", line 223, in __getitem__ return _DeadlockWrap(lambda: self.db[key]) # self.db[key] File "/usr/lib/python2.5/bsddb/dbutils.py", line 62, in DeadlockWrap return function(*_args, **_kwargs) File "/usr/lib/python2.5/bsddb/__init__.py", line 223, in <lambda> return _DeadlockWrap(lambda: self.db[key]) # self.db[key] KeyError: 'http://wiki.iona.com/icde-wiki/MarcLog/ June2007#20070611094814 updated type' I am not proficient in Python. I understand that a certain key is missing in some dictionary, but this is not sufficient for me to fix the problem. Could somebody put me on the trail? Thanks! Marc From tjreedy at udel.edu Sun Aug 19 23:45:46 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 19 Aug 2007 23:45:46 -0400 Subject: Python question (PyNoob) References: <3uOdnbA4Bc27fFXbnZ2dnUVZ8vidnZ2d@bt.com> Message-ID: <fab2qi$g83$1@sea.gmane.org> "Anonymous" <no.reply at here.com> wrote in message news:3uOdnbA4Bc27fFXbnZ2dnUVZ8vidnZ2d at bt.com... |I have exp with C/C++ (and a few other langs). I want to use Python to | start doing the ff: | | 1). Data Munging (text processing) - instead of Perl | 2). Automating my build process | 3). (Possibly) some web data retrieval jobs | | Can anyone point me to resurces/possibly scripts that can get me up to | speed (to do these 3 things) ASAP, without having to learn the basics of | programming? Your first sentence suggests that you already know the basics of programming, so perhaps you meant something a bit different? such as not figure out for yourself the basic idioms of Python, but learn them from code? In any case, item 1 seems too broad for specific help. As to item three, there are modules and indeed programs available. Check PyPI on the Python site, or search this newsgroup's archives (groups.google.com) or the web generally. tjr From MartinWuitz at yahoo.de Sun Aug 12 10:02:53 2007 From: MartinWuitz at yahoo.de (MartinWuitz at yahoo.de) Date: Sun, 12 Aug 2007 14:02:53 -0000 Subject: Bill Gates try to sell Microsoft @ ebay look here Message-ID: <1186927373.694975.244710@57g2000hsv.googlegroups.com> http://www.pennergame.de/ref.php?uid=4762 http://www.pennergame.de/ref.php?uid=5572 From rcdailey at gmail.com Sun Aug 12 11:03:11 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Sun, 12 Aug 2007 10:03:11 -0500 Subject: I am giving up perl because of assholes on clpm -- switching to Python In-Reply-To: <15e66e4e0708111526u541bccacoc834a1e51815f233@mail.gmail.com> References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> <Lc1186058698244350x8ae3b4c@earth.podro.com> <496954360708111500k6764d019p7cbf74b1df399b94@mail.gmail.com> <15e66e4e0708111526u541bccacoc834a1e51815f233@mail.gmail.com> Message-ID: <496954360708120803y45220af3pde442d841358c5dd@mail.gmail.com> That's a bit hard given the unpredictability of each person on that list. What seems like a simple question one minute suddenly turns into a flamewar because someone had a bad day at work and needed to vent at my expense. This is beyond phrasing your questions properly. It has to do with just pure stupidity. On 8/11/07, Greg Donald <gdonald at gmail.com> wrote: > > On 8/11/07, Robert Dailey <rcdailey at gmail.com> wrote: > > I had this very same problem with the doxygen mailing list... doxygen is > > such a great tool but full of assholes in their mailing list. > > I'm not defending any assholes you may have ran into, but I find the > thing to do is only ask questions in such a way that no one can > possibly have a reason to be an asshole. > > http://catb.org/~esr/faqs/smart-questions.html > > > -- > Greg Donald > http://destiney.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070812/ed726ab7/attachment.html> From aleax at mac.com Wed Aug 1 11:04:57 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 1 Aug 2007 08:04:57 -0700 Subject: Where do they tech Python officialy ? References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> <1185265091.276958.239910@r34g2000hsd.googlegroups.com> <1i23wyk.avc945i4dwsiN%aleax@mac.com> <mailman.1423.1185957645.22759.python-list@python.org> Message-ID: <1i25pjo.1mo5uqc1yxqsjkN%aleax@mac.com> Alex Popescu <nospam.themindstorm at gmail.com> wrote: ... > > and you will both learn a lot _and_ acquire "professional experience" > > that any enlightened employer will recognize as such. > > It depends :-). In my experience I met employers being concerned by my > implication in the oss world :-). Considering that even the King of Proprietary Software, Microsoft, now happily hires major Open Source figures such as Jim Hugunin (MS was also a top-tier sponsor at the recent OSCON, with both managerial and senior technical employees giving keynotes and tech talks), it boggles the mind to think about which kind of company would instead be "concerned" by a candidate's OS experience. > > That will take a > > while, but not as long as getting a college degree (and it will be far > > cheaper than the degree). > > I don't know much about the open community in Python world, but in Java > world becoming a project member may be more difficult than getting a > degree (or close to :-)) ). In a major project, you will of course have to supply useful contributions as well as proving to have a reasonable personality &c before being granted committer privileges; and a few projects (centered on a group of committers employed by a single firm or on an otherwise close-knit small clique) are not very open to the outside world at all. But (at least wrt projects using Python, C, C++ -- I have no experience of opensource projects focused on Java instead) that is the exception, not the rule. Alex From faulkner891 at gmail.com Wed Aug 8 23:23:26 2007 From: faulkner891 at gmail.com (faulkner) Date: Wed, 08 Aug 2007 20:23:26 -0700 Subject: How can I programmatically find the name of a method from within that method? In-Reply-To: <1186627400.727353.317750@d55g2000hsg.googlegroups.com> References: <1186548312.672360.259100@q3g2000prf.googlegroups.com> <1186627400.727353.317750@d55g2000hsg.googlegroups.com> Message-ID: <1186629806.424178.119810@19g2000hsx.googlegroups.com> On Aug 8, 10:43 pm, faulkner <faulkner... at gmail.com> wrote: > On Aug 8, 12:45 am, kj7ny <kj... at nakore.com> wrote: > > > Is there a way that I can programmatically find the name of a method I > > have created from within that method? I would like to be able to log > > a message from within that method (def) and I would like to include > > the name of the method from which it was written without having to > > hard-code that value in every message string. While we're at it, is > > there a way to programmatically get the name of the class and the > > module while I'm at it? > > > Thanks, > > def foo(): > print sys._getframe(0).f_code.co_name > > most of the darkest magic of python is in the frames returned by > sys._getframe. sorry for the double-post. i forgot to answer the rest of the question. class a: def b(self, *a): print sys._getframe(0).f_code.co_name print self.__class__.__name__ print getattr(self, sys._getframe(0).f_code.co_name).im_class.__name__ print self.__class__.__module__ def log(f): def newf(*a, **kw): if a and f.func_code.co_varnames[0] == 'self': print '%s.%s.%s %r %r' % (a[0].__class__.__module__, a[0].__class__.__name__, f.func_name, a, kw) else: print '%s.%s %r %r' % (f.func_globals['__name__'], f.func_name, a, kw) f(*a, **kw) newf.__name__ = f.__name__ newf.__doc__ = f.__doc__ return newf you can find more interesting attributes of frame and function objects using the builtin dir function. From __peter__ at web.de Mon Aug 27 13:17:16 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 27 Aug 2007 19:17:16 +0200 Subject: sorting a list of lists References: <1188233798.684136.263640@22g2000hsm.googlegroups.com> Message-ID: <fav0us$r05$00$1@news.t-online.com> nicksavill at googlemail.com wrote: > i would like to sort a list of lists. The list is first sorted on the > second item in the sub-lists (which I can do), then on the third item > (which I can't). > > eg. records = [['dog',1,2], ['chair',2,1], ['cat',1,3], ['horse',3,4], > ['table',3,2], ['window',3,5]] > > I want sorted to [['dog',1,2], ['cat',1,3], ['chair',2,1], ['table', > 3,2], ['horse',3,4], ['window',3,5]] > > To sort on the second item in the sub-lists I do the following > > pass1 = itemgetter(1) > sorted(records, key=pass1) > > How can I then sort on the third item in the sub-lists whilst keeping > the order on the second item? list.sort() is stable, so items = sorted(records, key=itemgetter(2)) # minor order first items.sort(key=itemgetter(1)) # major order should give the desired result (items with equal item[1] are sorted by item[2]. Python 2.5 also allows to pass multiple indices to itemgetter() sorted(records, key=itemgetter(1, 2)) IIRC for Python 2.4 you'd have to write your own key routine: def key(item): return item[1], item[2] sorted(records, key=key) Peter From aahz at pythoncraft.com Thu Aug 23 16:49:47 2007 From: aahz at pythoncraft.com (Aahz) Date: 23 Aug 2007 13:49:47 -0700 Subject: Co-developers wanted: document markup language References: <87odgyyx9u.fsf@wilson.homeunix.com> Message-ID: <fakrtb$2ts$1@panix3.panix.com> In article <87odgyyx9u.fsf at wilson.homeunix.com>, Torsten Bronger <bronger at physik.rwth-aachen.de> wrote: > >Some LaTeX users in Aachen thought about a general-use markup >language this spring. I wrote some code and a rough project >description, however, we could need some help. http://docutils.sourceforge.net/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From bayesianlogic at acm.org Fri Aug 3 16:57:35 2007 From: bayesianlogic at acm.org (ekzept) Date: Fri, 03 Aug 2007 13:57:35 -0700 Subject: libpq.dll for pgdb Message-ID: <1186174655.398009.117540@57g2000hsv.googlegroups.com> the module PGDB which gives Python access to PostgreSql currently wants for a copy of a properly located or proper libpq.dll library, on Windows. anyone know what the current story on this is? thanks, -- jt From vbr at email.cz Thu Aug 2 07:34:08 2007 From: vbr at email.cz (vbr at email.cz) Date: Thu, 02 Aug 2007 13:34:08 +0200 (CEST) Subject: =?us-ascii?Q?Re=3A=20Use=20variable=20in=20regular=20expression?= In-Reply-To: <1186051401.122847.114690@d55g2000hsg.googlegroups.com> Message-ID: <15924.18753-5774-380836898-1186054448@email.cz> ... > Yesterday's date is 20070731, and assigned to the variable > "yesterday_date". I want to loop thru a directory and find all of the > yesterday's data ONLY IF the feature class has the date at the > BEGINNING of the filename. ... > I can't figure out the > syntax of inserting the "^" into the regex. > ... e.g. yesterdayRE = re.compile("^"+yesterday_date) ... should work (assuming yesterday_date is a string), but for that simple tests you may also try e.g. filename.startswith(yesterday_date) (with both filename and yesterday_date being strings). Greetings, Vlasta From zyzhu2000 at gmail.com Thu Aug 16 18:52:18 2007 From: zyzhu2000 at gmail.com (beginner) Date: Thu, 16 Aug 2007 22:52:18 -0000 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: <1i2ysn4.7ue1uud53iygN%raims@dot.com> References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> <1i2ysn4.7ue1uud53iygN%raims@dot.com> Message-ID: <1187304738.181728.13820@q3g2000prf.googlegroups.com> On Aug 16, 5:43 pm, ra... at dot.com (Lawrence Oluyede) wrote: > beginner <zyzhu2... at gmail.com> wrote: > > I'd like to do the following in more succint code: > > > if k in b: > > a=b[k] > > else: > > a={} > > b[k]=a > > b.setdefault(k, a) > > -- > Lawrence, oluyede.org - neropercaso.it > "It is difficult to get a man to understand > something when his salary depends on not > understanding it" - Upton Sinclair I am afraid it is not the same. b.setdefault(k, {}) will always create an empty dict, even if k is in b, as demonstrated in the below code. b={} def f(i): print "I am evaluated %d" % i return i b.setdefault('A', f(1)) b.setdefault('A', f(2)) b From jstroud at mbi.ucla.edu Mon Aug 20 00:42:19 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 19 Aug 2007 21:42:19 -0700 Subject: popen4 not returning output In-Reply-To: <lJ8yi.6118$924.1308@newssvr23.news.prodigy.net> References: <1187582318.054450.76960@z24g2000prh.googlegroups.com> <lJ8yi.6118$924.1308@newssvr23.news.prodigy.net> Message-ID: <jT8yi.6121$924.3194@newssvr23.news.prodigy.net> James Stroud wrote: > hortitude at gmail.com wrote: >> I am trying to run the following script: >> >> >> #!/usr/bin/python >> >> import popen2 >> >> commandToRun = """scp scp_trial.py user at host:/targetDirectory""" >> #commandToRun = "ls" >> print commandToRun >> p_out, p_in = popen2.popen4 (commandToRun) >> >> theOut = p_out.readlines () >> print theOut >> >> >> When I run this command with the "ls" command I see the output. >> When I run this with the scp command I do not see the output of my >> command -- however the file is successfully transfered. How can I see >> the output? >> >> Thanks >> > > I'm not up on my scp, but look at popen3 and read from err. > > James Nevermind, I didn't notice that you were using popen4. From hniksic at xemacs.org Fri Aug 24 08:54:14 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 24 Aug 2007 14:54:14 +0200 Subject: Does shuffle() produce uniform result ? References: <tooru_honda-1F800B.15385124082007@wvnews01.netvigator.com> Message-ID: <878x81rt3d.fsf@mulj.homelinux.net> tooru honda <tooru_honda at fast-mail.org> writes: > I have read the source code of the built-in random module, > random.py. After also reading Wiki article on Knuth Shuffle > algorithm, I wonder if the shuffle method implemented in random.py > produces results with modulo bias. It doesn't have modulo bias because it doesn't use modulo to produce a random index; it multiplies the floating point value with the desired range. I'm not sure if that method produces any measurable bias. From deets at nospam.web.de Fri Aug 17 12:08:27 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 17 Aug 2007 18:08:27 +0200 Subject: Can python threads take advantage of use dual core ? In-Reply-To: <1187366443.621295.97020@e9g2000prf.googlegroups.com> References: <1187366443.621295.97020@e9g2000prf.googlegroups.com> Message-ID: <5ilvg4F3pqv6aU1@mid.uni-berlin.de> nikhilketkar schrieb: > What are the implications of the Global Interpreter Lock in Python ? > Does this mean that Python threads cannot exploit a dual core > processor and the only advantage of using threads is in that > computation and IO-bound operations can continue in parallel ? Essentially, yes. That is unless the computation is done in C-code which released the GIL beforehand. But a certain tradeoff is to expected nontheless. Diez From zzbbaadd at aol.com Thu Aug 30 23:06:38 2007 From: zzbbaadd at aol.com (zzbbaadd at aol.com) Date: Thu, 30 Aug 2007 20:06:38 -0700 Subject: list index() In-Reply-To: <mailman.174.1188517712.28954.python-list@python.org> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <mailman.135.1188474634.28954.python-list@python.org> <1188495863.242815.236900@o80g2000hse.googlegroups.com> <87bqcod2gq.fsf@benfinney.id.au> <1188517370.998114.119940@q4g2000prc.googlegroups.com> <mailman.174.1188517712.28954.python-list@python.org> Message-ID: <1188529598.134837.157530@x35g2000prf.googlegroups.com> On Aug 30, 4:48 pm, "Chris Mellon" <arka... at gmail.com> wrote: > On 8/30/07, zzbba... at aol.com <zzbba... at aol.com> wrote: > > > > > On Aug 30, 4:31 pm, Ben Finney <bignose+hates-s... at benfinney.id.au> > > wrote: > > > zzbba... at aol.com writes: > > > > In my case of have done os.listdir() on two directories. I want to see > > > > what files are in directory A that are not in directory B. > > > > You get that information unambiguously. It's an exceptional case, > > > since there's no index to return, so it throws an exception. > > > > > I have used exceptions in other languages and only do so on logic > > > > that should never happen. > > > > You're confusing "assert" ("this should always be true") with > > > "exception" ("this is an exception to the the normal flow of this > > > process"). > > > > An exception isn't "something that should never happen", it's > > > something that is entirely possible and needs to be handled somehow. > > > I don't think that is the definition used across computer science. > > how its defined in Python is what is important in this context. Is there a definition on python.org for an exception? > > > It suddenly dawned on me that what would be best would be a contains() > > (or IN syntax for those who can't afford to wait) for lists. > > > if mylist.contains("hello): > > Genius. Why didn't anyone think of that before? With an attitude like that Chris, don't expect to be getting an invite to beta test my Python 3 fork. From horpner at yahoo.com Wed Aug 29 13:54:01 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 29 Aug 2007 17:54:01 GMT Subject: general function for sorting a matrix References: <1188402447.290663.307640@z24g2000prh.googlegroups.com> Message-ID: <slrnfdbcbj.1cc.horpner@FIAD06.norwich.edu> On 2007-08-29, Xah Lee <xah at xahlee.org> wrote: > A couple years ago, i posted a programing problem, about > writing a function that will sort a arbitrarily dimentioned > matrix in any possible way to sort it. > > Such a function, is rather typical in functional programing > languages. I wrote a version in 1999 in perl for practical > purposes, since sorting a matrix (i.e. list of lists) is rather > common. With this function, i can have a single interface to > deal with any list (including list of lists). > > It is ideal, that a language's function for sort actually are > of this generality. > (See ?What is Expressiveness in a Computer Language?, Xah Lee, 2005. > http://xahlee.org/perl-python/what_is_expresiveness.html > ) > > The advantage of such a generality, is that a programer don't > need to write a sorting code every time she encounters a list. The advantage of such a richly implemented language as Python, is that a programmer don't need to write a general sorting algorithm at all. -- Neil Cerutti From oliver at obeattie.com Mon Aug 20 07:13:08 2007 From: oliver at obeattie.com (oliver at obeattie.com) Date: Mon, 20 Aug 2007 11:13:08 -0000 Subject: Sorting a list of Unicode strings? In-Reply-To: <1187542237.139346.6910@o80g2000hse.googlegroups.com> References: <1187542237.139346.6910@o80g2000hse.googlegroups.com> Message-ID: <1187608388.772541.251860@22g2000hsm.googlegroups.com> Thank you all for your very quick and informative replies. I was basing this assumption that ? was classed as a standard 'A' from a list of countries I was looking at (Wikipedia sorts it like this, too - though this isn't what I was using http://en.wikipedia.org/wiki/List_of_countries#A) I will leave it as it is, with ? at the bottom, if this is the correct ordering. Once again, thank you! Oliver From kyosohma at gmail.com Sat Aug 11 09:39:02 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Sat, 11 Aug 2007 13:39:02 -0000 Subject: deselect an iterm in ListBox wxPython In-Reply-To: <1186818810.685844.263700@w3g2000hsg.googlegroups.com> References: <1186818810.685844.263700@w3g2000hsg.googlegroups.com> Message-ID: <1186839542.246998.125430@g12g2000prg.googlegroups.com> On Aug 11, 2:53 am, Bailu <lingyun.y... at gmail.com> wrote: > Hi, > > I am a newbie in wxPython and doing a program with ListBox, > I want to select and deselect items in this box, > I have use > > self.devlist = wx.ListBox(self, style=wx.LB_MULTIPLE) > self.Bind(wx.EVT_LISTBOX, self.select_dev, self.devlist) > > to create this box, but don't know how to implement self.select_dev > to find out which one is clicked > > deselect it, if it was selected ( this is not working at default) > select it, if it was not (toggle) > > The default behavior is, the selection is increasing, I can't deselect > any of them. > > Thanks. > > Lingyun You should look at the wxPython demo's code for the wx.ListBox. It looks like they use the wx.EVT_LISTBOX event. See below: <code> # this writes to a multiline TextCtrl self.log.WriteText('EvtListBox: %s, %s, %s, %s\n' % (event.GetString(), event.IsSelection(), event.GetSelection(), event.GetClientData())) </code> I'm not sure, but I think it uses the SetSelection() method to select an item, which seems to deselect the previously selected item...at least, that's how I interpret the demo. The demo is here: http://wxpython.org/download.php If you need additional help, try posting to the wxPython User's group: http://wxpython.org/maillist.php Regards, Mike From mail at microcorp.co.za Wed Aug 8 03:20:55 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 8 Aug 2007 09:20:55 +0200 Subject: Heterogeneous lists References: <RPadnXFHmYYUIiXbnZ2dnUVZ_uKpnZ2d@comcast.com> Message-ID: <014001c7d992$b0f13980$03000080@hendrik> "Gordon Airporte" <J,,,,r at fbi.gov> > This is one of those nice, permissive Python features but I was > wondering how often people actually use lists holding several different > types of objects. I do it all the time - I only use tuples when I _have_ to. > It looks like whenever I need to group different objects I create a > class, if only so I can use more meaningful names than '[2]' for the items. You don't have to be so array-minded. You can write things like: address = 2 individual_list[address] this is easier to read and understand than: individual_list[2] and does the same thing. I have found that the most useful data structure is a dict, or a dict of dicts. - almost an instant database. - Hendrik From http Mon Aug 6 12:44:15 2007 From: http (Paul Rubin) Date: 06 Aug 2007 09:44:15 -0700 Subject: Tkinter or wxpython? References: <op.tv98rva4wepdt4@ericb.pragmadev> <mailman.1550.1186099225.22759.python-list@python.org> <1186410331.905174.21370@q3g2000prf.googlegroups.com> <7xps204tin.fsf@ruckus.brouhaha.com> <mailman.1677.1186412323.22759.python-list@python.org> <7xlkcopu4r.fsf@ruckus.brouhaha.com> <mailman.1680.1186416061.22759.python-list@python.org> Message-ID: <7x3aywr4tc.fsf@ruckus.brouhaha.com> "Chris Mellon" <arkanes at gmail.com> writes: > > Might or might not matter for the application, especially considering > > that tkinter is part of the discussion. > The point is that you have no option with the browser - even Tkinter > has platform theming support now. Hmm, I don't know anything about that. I'm taking the view that for a lot of apps, the requirement is to just put some functionality on the screen, with slick visual appearance having little value or even negative value. > ...Gmail uses ajax instead of a page load when you start > typing a reply, I see, the answer to what caused your problem is approximately "ajax is evil", or alternatively, the gmail app attempts slickness with a tool that doesn't support slickness that well. OK, I can accept that using browsers for slick interfaces has its problems, but the answer (a lot of the time, not always) is to just decide you don't need slickness. > > File i/o and file system browsing are available from javascript if the > > user grants permission. > Which they won't (I don't even know how, from Firefox), so you can't > rely on it working. The application javascript pops a dialog asking for permission and the user clicks yes or no. If you can get them to install a desktop app (gah!!) then you can certainly get them to click yes in a browser. The permission mechanism is admittedly browser dependent. > But not of anything else. I've often wanted to drag & drop a file onto > the file upload box in gmail, for example. Well, ok, that's a slick feature that your app might need. None of mine have needed it so far. > How about something as simple as context menus? Unnecessary slickness for many apps. I've never needed it. > > Multiple windows are evil most of the time, > Multiple windows are the common case on the mac. They're not rare on > other platforms as well. The fact that your windows are constrained to > the browser and can't be torn off is a large limitation. No toolbars, > no palettes, no modal dialogs (except on IE, or if you constrain them > to the browser). Lots of unnecessary chrome on your extra windows, too > (see below). You can get rid of the chrome with javascript, but the extra windows are still usually evil and unnecessary. Just because they get used a lot doesn't change that. A heck of a lot of deployed interfaces, web or desktop, simply suck. > > > More platforms to develop on and test with. > > Compared to a desktop app? I don't think so. > Did you ever try counting? X browsers * Y browser versions * Z > platforms. There are javascript and CSS bugs and differences between > all of these. If you can tell them to install a desktop app, you can alternatively tell them what browser to use. For example we use a complicated firefox-only browser app where I work, that relies heavily on canvas objects. But if you write your application with straightforward html you tend to have very few platform problems. > From my own professional experience, it's not any easier > to account for browser differences than it is for platform > differences. It's getting better as more people jump on the web > bandwagon and CSS and JS abstraction libraries show up, I guess I see that stuff as mostly-evil and prefer straightforward html. > I'm not talking about chrome and slickness. I'm talking about basic > usability concerns like "will this work with a higher font size" and > "will it reflow in a sensible way if I change the window size". The > CSS box model works okay for text, it's not so good for widgets. I just haven't had this problem with HTML interfaces. I've never even used CSS, though that makes me a bit of a lamer. An interface that needs to fill the whole screen with widgets is probably too complicated. > More than a few web apps end up writing their own layout engines in > dynamic javascript. This is sad. While I'm talking about chrome, add > "wasted screenspace due to browser chrome" to a limitation of web > apps, again unless you write your own browser host. This is another > example of a feature that makes a good browser (don't let arbitrary > web pages mess with my web browser functionality) clashing with the > desires of a good application (don't waste screen space with > irrelevant functionality). I guess the term I'd use to describe all these effects is "slick" and a heck of a lot of the time it's just not needed. Anyway you can pop a chromeless browser window with a simple javascript call. > Man, you should be in PR with the way you spin things. You can't > implement anything except the most trivial of applications using only > the simple, familiar web elements like HTML forms. Anything more > complicated than that needs to be done with DHTML and probably AJAX, > and those UI elements don't look anything like the familiar ones. You > go in one breath from saying that you can implement dialogs in HTML to > saying that the rich client is the *less* familiar of the interfaces? I don't see the contradiction--with HTML you have just a few widgets that everyone understands and you get an interface that's almost always self-explanatory. Yes you could call those interfaces trivial, but the little secret that I'm trying to convey is that very often, trivial is all that's needed. > If you'd said "if you're making something really simple that has > limited rich UI or data entry needs, consider a web application > instead" I wouldn't have posted. A web application is something you > make because the deployment and access benefits outweigh the UI and > integration limitations, not as your default "go to" whenever you > create an application. Well, I could back off to somewhere between the two. Like, "ask yourself whether your application really needs a rich gui or complex data entry features. If you can get by with a simple HTML interface, and a lot of the time you can, you'll probably have an easier time doing it that way and that should be the default". > I'd like an example you have of a desktop application that could have > just as easily been a web application. Bonus points if it's not a CRUD > screen, and double bonus if you don't just handwave away things like > file browsing. Although there are benefits even for the crud screen - > I've written screens and applications for data entry professionals and > they almost always prefer the speed optimizations you can make in a > client application. I guess I've written 4 or 5 nontrivial desktop gui apps and ZERO of them had file browsing. One of them did need access to the pc's serial port, which means there had to be application code on the desktop, but the gui could have been a browser (talking to an application-embedded http server) if browsers were available in those days. Another one of them saved some state to a local file but it did that without file browsing, and could have instead saved the state on a remote server if it were written as a remote app. I'm not saying file browsing is never needed, just that from experimental observation, it's quite often not needed. Again, it all depends on what you're trying to do. For data entry stuff you probably want the data on a remote server anyway, and you can do basic CRUD validation with fairly simple javascript. Maybe that departs from pure HTML but it's nothing like the ajax/dhtml madness that causes the problems you've described. From knomenet at gmail.com Thu Aug 16 16:22:02 2007 From: knomenet at gmail.com (Michael Speer) Date: Thu, 16 Aug 2007 16:22:02 -0400 Subject: Haskell lambdas in python Message-ID: <314e9ce40708161322g482ed01fsc5f24a065110ea8@mail.gmail.com> Hello python-list, I decided to have some fun and altered a copy of python to use a Haskell-like syntax for declaring lambdas. >>> filter( \ x -> x == 3 or x > 8 , [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] ) [3, 9, 10] >>> ( \-> "Hello World!" )() 'Hello World!' While doing this I found something interesting while changing the grammar to : old_lambdef: ( 'lambda' | '\\' ) [varargslist] ( ':' | '->' ) old_test ... lambdef: ( 'lambda' | '\\' ) [varargslist] ( ':' | '->' ) test In Parser/tokenizer.c, instead of needing to change only the PyToken_OneChar function to have a case '\\': return LAMBDAARGS; option, I also had to add case '\\': switch (c2) { case '\\': return LAMBDAARGS; } to PyToken_TwoChars. The interactive runtime requires the OneChar definition, and the compilation process ( specifically pgen ) requires the TwoChar definition. If anyone wants the changes required to play around with it just email me and I'll find somewhere to stick them on the web for download. It seems a waste that whack acts only as an end of line continuance. - Michael Speer -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070816/bdba39f9/attachment.html> From ocollioud at gmail.com Fri Aug 24 07:16:30 2007 From: ocollioud at gmail.com (olive) Date: Fri, 24 Aug 2007 11:16:30 -0000 Subject: Server-side scripting in python In-Reply-To: <46ceb673$0$415$426a74cc@news.free.fr> References: <1187614732.519547.296020@j4g2000prf.googlegroups.com> <gi6rp4-mes.ln1@lairds.us> <1187755436.972359.293360@i13g2000prf.googlegroups.com> <0k2up4-lla.ln1@lairds.us> <1187843960.922925.127990@i13g2000prf.googlegroups.com> <46ceb673$0$415$426a74cc@news.free.fr> Message-ID: <1187954190.571860.85920@m37g2000prh.googlegroups.com> > Yes : have a look at Pylons too. It's actually quite less 'polished' > than Django, but it's IMHO going in the right direction (as a matter of > fact, Turbogears 2.0 - another well-known Python MVC framework - will > be based on Pylons...). Django is clearly more oriented toward > content-management, which might not be what you want for this project. this opinion about Django is a little bit dated (see http://www.djangosites.org/ and http://code.djangoproject.com/wiki/DjangoPoweredSites). Django is really multi-purpose and is rarely use as a CMS, excepted through Ellington CMS which is itself a commercial fork oriented toward newspaper like publishing. I would use Plone instead as a general CMS. Olive. From hg at nospam.org Tue Aug 7 21:37:50 2007 From: hg at nospam.org (hg) Date: Tue, 07 Aug 2007 20:37:50 -0500 Subject: Emacs + python References: <ak8x8v2udo.fsf@googlemail.com> <mailman.1476.1186017909.22759.python-list@python.org> <4vasi.139194$wG2.61677@newsfe17.lga> <mailman.1524.1186077010.22759.python-list@python.org> <JpGsi.28744$GO6.24370@newsfe21.lga> <87zm189lnq.fsf@benfinney.id.au> Message-ID: <P79ui.45554$g86.40902@newsfe14.lga> Ben Finney wrote: > hg <hg at nospam.org> writes: > >> how about a cscope equivalent ? > > How about reading what was posted earlier in the thread, and give us a > description of what you want instead of a name that people might not > recognise? > > -- > \ "The judge asked, 'What do you plead?' I said, 'Insanity, your | > `\ honour. Who in their right mind would park in the passing | > _o__) lane?'" -- Steven Wright | > Ben Finney Cscope allows for instance to find the definition of a symbol. hg From bignose+hates-spam at benfinney.id.au Wed Aug 1 20:00:04 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 02 Aug 2007 10:00:04 +1000 Subject: Python end of file marker similar to perl's __END__ References: <1185940391.135261.130950@i38g2000prf.googlegroups.com> <1185976656.753817.27980@x40g2000prg.googlegroups.com> Message-ID: <874pjidcvv.fsf@benfinney.id.au> beginner <zyzhu2000 at gmail.com> writes: > Thanks everyone for responding. It doesn't look like python has > it. I would definitely miss it. As Steve said, the nice thing about > __END__ is that things below __END__ do not have to have legit > syntax. I think the unaddressed question is: Why is there so much code in your module with invalid syntax that this trick would be useful? > That let me focus on the lines of code I am debugging and do not > have to worry about some bad syntax down the line. This feature is > especially handy if I am, saying, replacing modoules or changing > data structures. I would strongly recommend you examine what part of your practice is leading you to write so much code with invalid syntax, without immediately testing and fixing it. Eliminate that part of the process ? possibly with test-driven development. -- \ "Holy unrefillable prescriptions, Batman!" -- Robin | `\ | _o__) | Ben Finney From rafaelv at spress.com.br Wed Aug 1 15:20:10 2007 From: rafaelv at spress.com.br (Rafael V.) Date: Wed, 01 Aug 2007 16:20:10 -0300 Subject: Subprocess and pipe-fork-exec primitive In-Reply-To: <46af9bcc$0$17509$9b622d9e@news.freenet.de> References: <mailman.1332.1185806811.22759.python-list@python.org> <46af9bcc$0$17509$9b622d9e@news.freenet.de> Message-ID: <46B0DCEA.6060409@spress.com.br> Hi Martin, the operating system I'm using is SUSE Linux 10, kernel 2.6.13. You're right, I was missing something. After you told me that it couldn't be Python preforming wait() on SIGCHLD, I decided to investigate further. My application requires access to a Informix database, and uses informixdb. The problem seems to be related to that module. I wrote a small piece of code to test it: --------------------------------------------------- #!/usr/bin/env python from os import fork, execl, waitpid from informixdb import connect try: conf = {} conf['dsn'] = 'db at server' conf['user'] = 'user' conf['password'] = 'password' connection = connect(**conf) except: pass pid = fork() if pid == 0: # Child execl("/bin/sh", "/bin/sh", "-c", "true") # Parent waitpid(pid, 0) print pid --------------------------------------------------- If you run the code above multiple times, some runs will trigger exceptions on the waitpid calls. Commenting the call to informixdb.connect(), no exceptions are triggered. I am concluding that informixdb, not Python, is handling the signals and reaping the subprocesses. Now Martin, do you think I can use informixdb.py and subprocess.py in the same application? I was thinking on forking subprocesses from the main thread and using other threads to access the Informix database, would that work? Thanks, Rafael. Martin v. L?wis escreveu: >> From my experience, this primitive will fail with 'no child processes' >> at the waitpid call if the forked child dies very quickly - before the >> parent is scheduled back for execution. This seems to happen because >> Python has a default SIGCHLD handler that, in this case, will reap the >> process before the parent has the chance to do it. > > What operating system is your experience from? On a POSIX system, > this should not happen - i.e. delivery of SIGCHLD should not cause > to make the child waited-for. Python itself does not perform wait() > in response to SIGCHLD. > >> I would like to know if this is correct, or am I missing something here? > > You must be missing something, although I'm uncertain what precisely > that is. > > Regards, > Martin From damondolby at googlemail.com Tue Aug 14 13:32:48 2007 From: damondolby at googlemail.com (towers) Date: Tue, 14 Aug 2007 10:32:48 -0700 Subject: module: zipfile.writestr - line endings issue In-Reply-To: <1187110504.154878.317460@19g2000hsx.googlegroups.com> References: <1187107452.905165.45700@l70g2000hse.googlegroups.com> <1187110504.154878.317460@19g2000hsx.googlegroups.com> Message-ID: <1187112768.095414.223640@w3g2000hsg.googlegroups.com> Thanks - your code works for me also. But I still get the issue when I read the file directly and add it to the archive. Say if I: 1. Use the test.csv file created with your code - currently the line endings look good (viewed in notepad on Win XP) 2. Run the following code: # begin code import zipfile import os.path # Now, create the zipfile dfile = open('test.csv', 'r') zip_file = zipfile.ZipFile(r'C:\temp\ice\line endings\test.zip', 'w', zipfile.ZIP_DEFLATED) zip_file.writestr('test.csv',dfile.read()) dfile.close() zip_file.close() 3. Then extract the file and the file endings have been corrupted. Now one long line in notepad. (Other programs interpret correctly though.) Maybe the issue lies with this way (i.e. dfile.read()) of writing the file to the archive...possibly. Damon On 14 Aug, 17:55, "programmer... at gmail.com" <programmer... at gmail.com> wrote: > On Aug 14, 11:04 am, towers <damondo... at googlemail.com> wrote: > > > > > Hi > > > I'm probably doing something stupid but I've run into a problem > > whereby I'm trying to add a csv file to a zip archive - see example > > code below. > > > The csv just has several rows with carriage return line feeds (CRLF). > > > However after adding it to an archive and then decompressing the line > > endings have been converted to just line feeds (LF). > > > Does anyone know if this is a bug or am I just doing something wrong? > > > Many Thanks, > > Damon > > > **************************************************************************** > > import zipfile > > > zipFile = zipfile.ZipFile('LocalZipFile.zip', 'a', > > zipfile.ZIP_DEFLATED) > > dfile = open('LocalCSVFile.csv', 'r') > > zipFile.writestr('test.csv',dfile.read()) > > dfile.close() > > zipFile.close() > > **************************************************************************** > > Line endings will drive you up the wall. Anyway, the python zipfile > library does not seem to be doing any translations. The code below > works for me. > > # begin code > import zipfile > import os.path > > # First create some work data... > csv_data = '1,2\r\n3,4\r\n5,6\r\n' > > # Now, create the zipfile > zip_file = zipfile.ZipFile(r'c:\tmp\test.zip', 'w', > zipfile.ZIP_DEFLATED) > zip_file.writestr('test.csv',csv_data) > zip_file.close() > > # Now, extract the info > zip_file = zipfile.ZipFile(r'c:\tmp\test.zip') > assert len(zip_file.read('test.csv')) == len(csv_data) > # end code > > Something else must be tweaking your line endings. > HTH! > > jw From gagsl-py2 at yahoo.com.ar Tue Aug 28 00:07:03 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 28 Aug 2007 01:07:03 -0300 Subject: Chaining programs with pipe References: <1187734166.384152.178040@o80g2000hse.googlegroups.com> <13cnbi87neru8c3@corp.supernews.com> <mailman.97.1187757319.32294.python-list@python.org> <13cogr3n6no937b@corp.supernews.com> <1187795716.083417.299540@q4g2000prc.googlegroups.com> <fau28j$gle$3@lust.ihug.co.nz> Message-ID: <op.txq4d1pux6zn5v@gabriel2.softlabbsas.com.ar> En Mon, 27 Aug 2007 05:35:51 -0300, Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> escribi?: > In message <1187795716.083417.299540 at q4g2000prc.googlegroups.com>, > Gabriel > Genellina wrote: > >> On 22 ago, 11:08, Grant Edwards <gra... at visi.com> wrote: >> >>> but I'm a Unix guy who occasionally tries >>> to ship a Windows version of a Python app: the concept of a >>> process defaulting to having a stderr or stdout that wasn't >>> writable was utterly foreign to me. >> >> Ah, that explains your previous post telling that things on Windows >> don't work as they "should". They work, but not necesarily as a >> "foreigner" would expect. > > So what's the good reason for Windows having unusable defaults for stderr > and stdout, then? You should ask the wxPython/wxWidgets guys why they choose to do things that way. Perhaps it's just an option that should be turned on. I'm not a wx guru. Tk programs don't have that problem, by example: you have a GUI *and* a console, if you want. A simple print statement with no console just goes into void space - no error, no crash, no GPF... You get what you ask for: if you pass /SUBSYSTEM:WINDOWS as an option to the linker (or put equivalent flags in the executable) you don't get a console by default. That's fine for most GUI programs that don't use stdout/stderr. If you want a console, create one using AllocConsole. Or do that on the parent process, and let the children inherit it (as when running the application from the command line, as opposed to double clicking an icon). Or link with /SUBSYSTEM:CONSOLE. Or use GetStdHandle/SetStdHandle inside the app to redirect STD_OUTPUT_HANDLE etc. -- Gabriel Genellina From kyosohma at gmail.com Mon Aug 20 10:17:02 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 20 Aug 2007 07:17:02 -0700 Subject: Python equivalent of Perl's $/ In-Reply-To: <mailman.9.1187619031.26576.python-list@python.org> References: <mailman.9.1187619031.26576.python-list@python.org> Message-ID: <1187619422.439013.69580@l22g2000prc.googlegroups.com> On Aug 19, 1:13 pm, John K Masters <johnmast... at oxtedonline.net> wrote: > I am currently working my way through Jeffrey Friedl's book Mastering > Regular Expressions. Great book apart from the fact it uses Perl for the > examples. > > One particular expression that interests me is '$/ = ".\n"' which, > rather than splitting a file into lines, splits on a period-newline > boundary. Combined with Perl's 'while (<>)' construct this seems a great > way to process the files I am interested in. > > Without wishing to start a flame war, is there a way to do this in Python? > > Regards, John > -- > War is God's way of teaching Americans geography > Ambrose Bierce (1842 - 1914) Python has a Regular Expressions module. Check it out here: http://docs.python.org/lib/module-re.html There's also a chapter from Dive Into Python that covers this topic too: http://www.diveintopython.org/regular_expressions/index.html Finally, Python "while" statement's docs can be found here: http://docs.python.org/ref/while.html Hope that helps! Mike From lac at openend.se Sat Aug 4 14:32:46 2007 From: lac at openend.se (Laura Creighton) Date: Sat, 4 Aug 2007 20:32:46 +0200 Subject: pyweek is happening august 02 - august 09 Message-ID: <200708041832.l74IWkRY027388@theraft.openend.se> 00:00 UTC 2007-09-02 to 00:00 UTC 2007-09-09 exactly. See www.pyweek.org PyconUK is happening. http://www.pyconuk.org/ 8th and 9th September. This means that those of us who generally do not see each other but are going to PyconUK could put together an entry and then sprint together on it before PyCon UK. There would be this terrible torment -- do I attend the con or get my game to work -- but it is still the best chance some of us have to work together yet. Talk to me if you are interested in maybe making a PyconUK pygame team. I think that this could be a lot of fun. Sign up on www.pyweek.org if you think so, as well. But mail me. John -- assuming we want to meet up _before_ PyConUK -- can that work? Can you point us at a cheap hostel for a few days? Laura Creighton From ninja.krmenadl at nes.com Mon Aug 20 13:09:48 2007 From: ninja.krmenadl at nes.com (Boris Ozegovic) Date: Mon, 20 Aug 2007 19:09:48 +0200 Subject: I Need help from all the group participants References: <fac7nj$ci9$1@localhost.localdomain> <1187629313.357121.196370@q4g2000prc.googlegroups.com> Message-ID: <fachs3$dcr$1@localhost.localdomain> mensanator at aol.com wrote: > The only sentence that comes to mind is: > > "I hope I never find myself in a hospital that uses your system." You are not funny. The system isn't for hospitals, it is for university purposes. -- Ne dajte da nas la?ljivac Bandi? truje: http://cnn.blog.hr/arhiva-2007-06.html#1622776372 From dummy666 at mail.ru Wed Aug 29 15:02:59 2007 From: dummy666 at mail.ru (askel) Date: Wed, 29 Aug 2007 12:02:59 -0700 Subject: Creating a multi-tier client/server application In-Reply-To: <1188408670.480447.42470@k79g2000hse.googlegroups.com> References: <1188360460.838635.186930@w3g2000hsg.googlegroups.com> <7xbqcqhqbw.fsf@ruckus.brouhaha.com> <46d54ed8$0$429$426a34cc@news.free.fr> <1188393925.007952.313110@r29g2000hsg.googlegroups.com> <46d57888$0$295$426a74cc@news.free.fr> <1188398008.538820.21960@d55g2000hsg.googlegroups.com> <46d59fa8$0$278$426a74cc@news.free.fr> <1188408670.480447.42470@k79g2000hse.googlegroups.com> Message-ID: <1188414179.783527.4240@50g2000hsm.googlegroups.com> On Aug 29, 1:31 pm, Jeff <jeff... at gmail.com> wrote: > Goldfish--thanks, I'll check it out. > > > > That, or something similar, may be what I do. It would mean, however, > > > developing my own method for transferring objects across the network, > > > Why transfering "objects" ? You only need to transfer data. > > I suppose I don't need to transfer objects, it just seems like it > would make it far easier (certainly less repetition of code) to > program the client-side app. If you prefer to deal with RPC-like protocol, take a look at Ice by ZeroC (http://www.zeroc.com/). From stefan.behnel-n05pAM at web.de Thu Aug 16 03:18:18 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 16 Aug 2007 09:18:18 +0200 Subject: ElementTree surprise In-Reply-To: <7x4pj0xax0.fsf@ruckus.brouhaha.com> References: <7xd4xoxf16.fsf@ruckus.brouhaha.com> <87bqd89gkd.fsf@wilson.homeunix.com> <7x4pj0xax0.fsf@ruckus.brouhaha.com> Message-ID: <46c3fa3a$0$16098$9b4e6d93@newsspool1.arcor-online.net> Paul Rubin wrote: > Torsten Bronger <bronger at physik.rwth-aachen.de> writes: >>> <foo bar="parrot"></foo> >> Technically, text is nodes as all other element nodes. In the >> parrot example, there is no empty textnode but no textnode at all. > > That is required by the xml standard? If yes, elementtree is doing > the right thing, but it surprises me, I would have expected an empty > string. Thanks. The XML standard defines both as being equivalent, so any XML parser would handle them exactly the same. Also, as most XML parsers have a SAX(-like) interface, which always generates events in the "<foo></foo>" form, there is not even a way for applications or libraries to distinguish between the two. So it's not even an ElementTree thing. ET just doesn't know what exactly was in the original XML byte stream. A very simple way to make sure you always get a string back is >>> text = element.text or "" BTW, you'd be even more surprised to see that ET can actually /store/ "" as text if you tell it to, and then returns an empty string when you ask for the .text property. But any empty text coming from the parser will always be None. Oh, and lxml.etree behaves exactly the same as ElementTree here. :) Stefan From kyosohma at gmail.com Fri Aug 17 11:47:15 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 17 Aug 2007 08:47:15 -0700 Subject: Hijack! Different book: In-Reply-To: <mailman.2077.1187297463.22759.python-list@python.org> References: <mailman.1957.1187093157.22759.python-list@python.org> <1187096231.194685.86030@m37g2000prh.googlegroups.com> <20070814154913.D8C3C1E400A@bag.python.org> <8a6b8e350708141020q495b22der4c362ee3df618d82@mail.gmail.com> <mailman.1979.1187113641.22759.python-list@python.org> <1187117012.088495.247890@q4g2000prc.googlegroups.com> <1187191950.037749.8050@z24g2000prh.googlegroups.com> <13c6fb3pntv6n13@corp.supernews.com> <1187263267.314987.253590@a39g2000hsc.googlegroups.com> <13c8u9nd4fk7r0d@corp.supernews.com> <mailman.2077.1187297463.22759.python-list@python.org> Message-ID: <1187365635.525716.322290@x40g2000prg.googlegroups.com> On Aug 16, 3:50 pm, Steve Holden <st... at holdenweb.com> wrote: > Dennis Lee Bieber wrote: > > On Thu, 16 Aug 2007 04:21:07 -0700, Paul Boddie <p... at boddie.org.uk> > > declaimed the following in comp.lang.python: > > >> Is this the book that came out before TurboGears even reached 1.0, > >> probably having diminished relevance now that there are 1.1 and 2.0 > > > Not sure -- I'd ordered it in January, but Amazon didn't ship it > > until a week ago; don't know if it was this, or the other book in the > > shipment that held it up. > > JANUARY!?????? So much for Amazon's customer service. Or is it only > February where you live? > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- Yeah...The Python Power! book was supposed to be released months ago, so I ordered it 4-6 months ago, but it only shipped a week ago when it actually released. Admittedly, this has nothing to do with the TurboGears book. Mike From f.guerrieri at gmail.com Fri Aug 31 09:20:36 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Fri, 31 Aug 2007 15:20:36 +0200 Subject: pure python for sms In-Reply-To: <46D81968.60303@fmed.uba.ar> References: <mailman.161.1188500323.28954.python-list@python.org> <BtHBi.28617$4A1.5445@news-server.bigpond.net.au> <46D81968.60303@fmed.uba.ar> Message-ID: <79b79e730708310620v32011da5xbb6580361477fffe@mail.gmail.com> On 8/31/07, Gerardo Herzig <gherzig at fmed.uba.ar> wrote: > Well, im not triyng to send a SMS `FROM' a cellphone, im trying to send > a SMS `TO' a cellphone. Here (in Argentina) are several sites who lets > you send a sms for free. You also can receive SMS responses via this page > http://sms.personal.com.ar/Mensajes/msn.htm > > While my tries using this page via urllib failed, i dont want to depend > on an external page anyway. The python class you send to me looks like > a pay site (if not, i dont see why the tokenpay() and getbalance() > methods :) > > I was also avaiable to send a sms in the form of an plain email > __cellphone_number at i_used_to_be_cool_smtp.com, but it not seems to work > this way no longer. Again, i dont want to do it that way anyway. > > Thats why im looking for a python implementation of that funcionality. Well but sooner or later you will have to pass your sms through some cellular system network whose services someone has to pay for...no? Francesco From sentientholon at gmail.com Tue Aug 21 13:03:39 2007 From: sentientholon at gmail.com (sentientholon) Date: Tue, 21 Aug 2007 17:03:39 -0000 Subject: Newbee Question In-Reply-To: <1187715131.514463.84960@57g2000hsv.googlegroups.com> References: <mailman.15.1187620149.26576.python-list@python.org> <1187621470.484615.7010@i13g2000prf.googlegroups.com> <mailman.19.1187621934.26576.python-list@python.org> <1187622390.854759.162320@q3g2000prf.googlegroups.com> <1187650036.450645.185500@a39g2000hsc.googlegroups.com> <1187685502.855643.122800@r34g2000hsd.googlegroups.com> <1187715131.514463.84960@57g2000hsv.googlegroups.com> Message-ID: <1187715819.382422.210680@m37g2000prh.googlegroups.com> On Aug 21, 11:52 am, "hd1... at yahoo.com" <hd1... at yahoo.com> wrote: > I tryed your code and got an error message #I use Wing IDE: > Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] > Type "help", "copyright", "credits" or "license" for more information. > > Evaluating lines 1-16 from truckStops.py > <string>:7: Warning: 'yield' will become a reserved keyword in the > future > Could not execute because an error occurred: > invalid syntax: <string>, line 7, pos 19: > yield stops, wage Python 2.2.3 is three versions behind. Generators only work in 2.2 by saying: from __future__ import generators And by default in anything from 2.3 on. Fred From mail at microcorp.co.za Fri Aug 3 02:52:29 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 3 Aug 2007 08:52:29 +0200 Subject: i am new to python-Please somebody help References: <1186047103.673871.150460@z24g2000prh.googlegroups.com><pan.2007.08.02.12.51.13.363293@REMOVE.THIS.cybersource.com.au><1186063842.827016.95030@q3g2000prf.googlegroups.com> <46b249a4$0$31219$426a74cc@news.free.fr> Message-ID: <00fb01c7d59b$97549b20$03000080@hendrik> "Bruno Desthuilliers" <bdes...art.fr> wrote: >Now if you want some examples of definitively "rude" newsgroups, I >suggest you take your chance on other newsgroups in the comp.* >hierarchy... I know someone who derisively refers to anybody that is associated with computers in any way as a "Pencil Neck". This leads me to wonder whether or not the rudeness stems from the physically deficient's urge to kick sand in the bully's face. - Hendrik From carsten at uniqsys.com Mon Aug 6 02:10:38 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 06 Aug 2007 02:10:38 -0400 Subject: Misleading wikipedia article on Python 3? In-Reply-To: <87y7gpr33a.fsf@pobox.com> References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> Message-ID: <1186380638.3288.24.camel@localhost.localdomain> On Sun, 2007-08-05 at 23:09 +0000, John J. Lee wrote: > I just wanted to know: is it easy to make my code so it > runs on 2.6 and 3.0, without funny stuff like a code translator? That depends on your definitions of "easy" and "funny stuff." I'm pretty sure you'll be able to run the same source code on Python 2.6 and Python 3.0 without either one breaking, as long as the code is written sufficiently carefully. You may have to give up some Python 3.0 features and/or write compatibility shims depending on what features you'll need. Whether that's acceptable depends on the features you need and how much "yak shaving" you find acceptable. For instance, if you never use print statements in your code, you won't notice that print is becoming a function. If you do, you'll have to make appropriate accommodations. HTH, -- Carsten Haese http://informixdb.sourceforge.net From kyosohma at gmail.com Tue Aug 28 10:20:05 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 28 Aug 2007 07:20:05 -0700 Subject: Getting subprocesses to be hidden on Windows In-Reply-To: <1188309590.114918.257670@y42g2000hsy.googlegroups.com> References: <1188246076.131276.292010@r34g2000hsd.googlegroups.com> <1188250115.875160.276780@r29g2000hsg.googlegroups.com> <1188292102.065625.82670@22g2000hsm.googlegroups.com> <1188308231.196513.291260@19g2000hsx.googlegroups.com> <1188309590.114918.257670@y42g2000hsy.googlegroups.com> Message-ID: <1188310805.381229.13270@y42g2000hsy.googlegroups.com> On Aug 28, 8:59 am, geoffbache <geoff.ba... at pobox.com> wrote: > > Which GUI toolkit are you using? Tkinter, wxPython, pyQt? > > Primarily PyGTK, but I was hoping it wouldn't matter. I hope to be > able > to start the process as indicated in the original post from within my > test > tool and instruct the subprocess to be hidden (or minimized? would > that be easier?), > irrespective of what it was (it might be a Java GUI or anything for > all I care...) > > > As for > > losing the command window on Windows, the best way that I know of is > > to just change the extension of the python file itself from *.py to > > *.pyw . I'm pretty sure you can suppress command windows if you're > > calling them from the command line using a flag, but I can't recall > > the flag off the top of my head. > > Thanks, that seemed to work. > > > One way to test while still being able to use your computer is to > > install a virtual machine with VMWare or some similar product. I use > > VMWare's free software for testing some of my scripts, but I've heard > > that Microsoft's got a free virtual product that isn't half bad. > > OK. If all else fails I might try that. But if there is a solution to > the original > problem it would be nice not to have to install VMWare everywhere for > convenient testing... > > Geoff I did a quick google and found the following, which probably only applies to Windows: http://www.tech-recipes.com/windows_tips512.html I know that with wxPython, you can tell it to whether or not to show the frame. Maybe pyGTK has the same functionality? This link seems to suggest that that maybe a valid option, but it doesn't detail how to accomplish it: http://www.daa.com.au/pipermail/pygtk/2000-August/000300.html This might be better: http://linuxgazette.net/issue78/krishnakumar.html Looks to me like you could just omit the "show" method. However, I have never used that particular toolkit. When you run stuff hidden like that, it can be difficult to kill them. Mike From alextabone at gmail.com Wed Aug 1 05:14:54 2007 From: alextabone at gmail.com (Acm) Date: Wed, 01 Aug 2007 02:14:54 -0700 Subject: calling a .net application from Python 2.5 Message-ID: <1185959694.045149.214050@19g2000hsx.googlegroups.com> I am working with Python 2.5. I would like to know how to call a .NET application (or .dll) from a Python script. Can anyone help please? Thank you. From jstroud at mbi.ucla.edu Wed Aug 22 13:26:38 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 22 Aug 2007 17:26:38 GMT Subject: libgmail failure In-Reply-To: <1187730447.621592.93740@q4g2000prc.googlegroups.com> References: <1187730447.621592.93740@q4g2000prc.googlegroups.com> Message-ID: <il_yi.1379$JD.695@newssvr21.news.prodigy.net> james.p.news at gmail.com wrote: > Hey all, > > I've been using libgmail to send out automated notification emails for > my company's nightly regression testing. Last night these emails > started failing, though the python code has not changed. I updated to > the latest libgmail, but that isn't helping. I've logged in to the > email account directly, and the account is still working fine. > > The error I get is "HTTP Error 400: Bad Request" when using > gmailAccount.login(). This doesn't throw an exception, just prints > the error. The code crashes outright when it tries to send mail. > > This code has been up and running for several months and just started > failing last night. Does anyone have an idea what's going on? > > The code and error follow (fairly short :-) > > Thanks much, > James Have you thought about spoofing explorer? Always spoof explorer. James From horpner at yahoo.com Mon Aug 13 09:37:26 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 13 Aug 2007 13:37:26 GMT Subject: Something in the function tutorial confused me. References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <slrnfbe1fd.n4.horpner@FIAD06.norwich.edu> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <slrnfbeofu.20s.horpner@FIAD06.norwich.edu> <1186424693.529497.217040@w3g2000hsg.googlegroups.com> <46B8626A.2070303@bigfoot.com> <mailman.1726.1186537161.22759.python-list@python.org> <5hsoi3F3mlni2U1@mid.individual.net> <f9ceb9$jsm$1@sea.gmane.org> <1186581124.3383.55.camel@dot.uniqsys.com> <mailman.1751.1186588156.22759.python-list@python.org> <slrnfbk19k.20o.horpner@FIAD06.norwich.edu> <1i2nhxn.tme05x17r39odN%aleax@mac.com> <m3hvi.37606$G23.6240@newsreading01.news.tds.net> <EAqvi.37622$G23.4722@newsreading01.news.tds.net> <1i2oxyo.cprrpi3nqji1N%aleax@mac.com> Message-ID: <slrnfc0mtk.1us.horpner@FIAD06.norwich.edu> On 2007-08-12, Alex Martelli <aleax at mac.com> wrote: > Neil Cerutti <horpner at yahoo.com> wrote: > ... >> OK, I've thought about this some more and I think the source >> of my confusion was I thought assignment in Python meant >> binding a name to something, not mutating an object. But in >> the case of augmented assignment, assignment no longer means >> that? > > "Plain" assignment *to a plain name* does mean "binding a name" > (the LHS) to "something" (the RHS). > > Other assignments (ones that are not "plain" assignments to > names) may have different meanings. For example: > >>>> class act(object): > ... def __init__(self, c): self._c = c > ... def getC(self): return self._c > ... def setC(self, *ignore): self._c += 1 > ... c = property(getC, setC) > ... >>>> x = act(0) >>>> x.c > 0 >>>> x.c = 23 >>>> x.c > 1 > > Here's an example where a plain assignment (to an attribute of x, not to > a plain name) obviously DOESN'T mean "binding a name to something": the > "something" (the RHS) is completely ignored, so the plain assignment is > mutating an object (x) and not binding any name to anything. That's enlightening. I hadn't considered the implications of generalizing assignment to names with assignment to qualified names. > Plain assignments to items and slices can also often be best > seen as "mutating an object" (the one being indexed or sliced > on the LHS) rather than "binding a name". For example: > >>>> l=list('ciao') >>>> l[1:3]='app' >>>> l > ['c', 'a', 'p', 'p', 'o'] That example makes me feel ashamed for not thinking of it, since I use the slicing assignment all the time and it's "obviously" not a binding construct. > If I was teaching Python and came upon this example, I would > definitely not try to weaselword the explanation of what's > going on in terms of "binding a name" (or several ``names'', > including ``rebinding" a new ``name'' l[4] to the 'o' that was > previously ``bound'' to l[3], etc:-): it's just orders of > magnitudes simpler to explain this as "mutating an object", > namely the list > > I take almost 3 pages in "Python in a Nutshell" (47 to 49 in > the second edition) to summarily explain every kind assignment > -- and that's in a work in which I've tried (successfully, I > believe from reviews) to be very, *VERY* concise;-). > > Summarizing that summary;-), a plain assignment to an identifier binds > that name; a plain assignment to an attribute reference x.y asks object > x (x can be any expression) to bind its attribute named 'y'; a plain > assignment to an indexing x[y] (x and y are arbitrary expressions) asks > object x to bind its item indicated by the value of y); a plain > assignment to a slicing is equivalent to the plain assignment to the > indexing with an index of slice(start, stop, stride) [[slice is a Python > builtin type]]. > > Plain assignment to an identifier "just happens"; all other cases of > plain assignment are requests to an object to bind one or more of its > attributes or items (i.e., requests for specific mutations of an object) > -- as for, say any method call (which might also be a request for some > kind of mutation), the object will do whatever it pleases with the > request (including, perhaps, "refusing" it, by raising an exception). > > Then we get into unpacking assignments and augmented > assignments, but I don't really want to write two more pages > worth of summary...;-). Thanks very much for taking the time to help clear up my erroneous model of assignment in Python. I'd taken a conceptual shortcut that's not justified. -- Neil Cerutti From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Aug 3 11:57:30 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 03 Aug 2007 17:57:30 +0200 Subject: (no) fast boolean evaluation ? In-Reply-To: <pan.2007.08.03.14.24.23.227662@REMOVE.THIS.cybersource.com.au> References: <30454$46b24f81$d443bb3a$10370@news.speedlinq.nl> <cfb58d850708021619s298f69b9p3af86905d1695939@mail.gmail.com> <mailman.1551.1186099243.22759.python-list@python.org> <46b2e56b$0$18879$426a74cc@news.free.fr> <pan.2007.08.03.14.24.23.227662@REMOVE.THIS.cybersource.com.au> Message-ID: <46b35069$0$17822$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Fri, 03 Aug 2007 10:20:59 +0200, Bruno Desthuilliers wrote: > >> Joshua J. Kugler a ?crit : >>> On Thursday 02 August 2007 15:19, Evan Klitzke wrote: >>>>> I discovered that boolean evaluation in Python is done "fast" >>>>> (as soon as the condition is ok, the rest of the expression is ignored). >>>> This is standard behavior in every language I've ever encountered. >>> Then you've never programmed in VB (at least 6, don't know if .net still >>> does this). Nested IF statements. AAAAAAAAAAAAAAAAAAAACK! >> I do remember an even brain-deadiest language that not only didn't >> short-circuit boolean operators but also didn't have an "elif" statement... > > > Is it a secret? > > I'm a little perplexed at why you say a language without "elif" is a good > sign of brain-death in a programming language. I understand that, given > the parsing rules of Python, it is better to use elif than the equivalent: > > if condition: > pass > else: > if another_condition: > pass > > > But that's specific to the syntax of the language. You could, if you > choose, design a language where elif was unnecessary: > > if condition: > pass > else if another_condition: > pass > > What advantage is there to "elif", apart from it needing three fewer > characters to type? > Sorry, I forgot to mention the language did not allow to have else & if in the same statement. IOW : if some_condition then do_sometehing else if some_other_condition then do_something_else else if yet_another_condition then do_yet_another_thing else if your_still_here then give_up('this language is definitively brain dead') end if end if end if end if From thomas at jollans.com Wed Aug 1 19:53:30 2007 From: thomas at jollans.com (Thomas Jollans) Date: Thu, 2 Aug 2007 01:53:30 +0200 Subject: sending very large packets over the network In-Reply-To: <9c8d48280708011555l5d1d439fu3c5fbcc61dc41f07@mail.gmail.com> References: <9c8d48280708011555l5d1d439fu3c5fbcc61dc41f07@mail.gmail.com> Message-ID: <200708020153.35321.thomas@jollans.com> On Thursday 02 August 2007, Walker Lindley wrote: > OK, I'm back with another networking question. I'm trying to seend large > amounts of information over TCP (the length of data being given to send() > is on the order of 16000 characters in length). Unfortunately on the > receiving end, the packets appear to be truncated. So I wrote some code > that continuously tries to send bigger and bigger packets until it fails > and noticed that it never fails at the same length. I'm not even sure these > two things are related, but is there some undocumented (or documented and I > missed it) maximum size for data you can pass to send()? First off, very long messages, that is messages whose length cannot be represented in a C size_t, are probably right out ;-) from the send(2) manual page on my Debian system: > If the message is too long to pass atomically through the underlying > protocol, the error EMSGSIZE is returned, and the message is not trans? > mitted. from the Python socket.send documentation [1] > Send data to the socket. The socket must be connected to a remote socket. > The optional flags argument has the same meaning as for recv() above. > Returns the number of bytes sent. Applications are responsible for checking > that all data has been sent; if only some of the data was transmitted, the > application needs to attempt delivery of the remaining data. that makes it quite clear that it's possible that not all data was transmitted. That you were unable to find a fixed size may be explainable in many ways - it might just be the way your operating system's TCP/IP stack works. If you just want to send data in some way or another, do yourself a favour and use socket.sendall instead of socket.send. Docs for socket.sendall: [1] > Send data to the socket. The socket must be connected to a remote socket. > The optional flags argument has the same meaning as for recv() above. > Unlike send(), this method continues to send data from string until either > all data has been sent or an error occurs. None is returned on success. On > error, an exception is raised, and there is no way to determine how much > data, if any, was successfully sent. [1]: http://docs.python.org/lib/socket-objects.html -- Regards, Thomas Jollans GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu Hacker key <http://hackerkey.com/>: v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part. URL: <http://mail.python.org/pipermail/python-list/attachments/20070802/5a5550bc/attachment.sig> From larry.bates at websafe.com Fri Aug 31 19:40:02 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 31 Aug 2007 18:40:02 -0500 Subject: Python Unicode to String conversion In-Reply-To: <1188600916.528901.189680@d55g2000hsg.googlegroups.com> References: <1188600916.528901.189680@d55g2000hsg.googlegroups.com> Message-ID: <wtSdndh9-MFRO0XbnZ2dnUVZ_o-mnZ2d@comcast.com> thijs.braem at gmail.com wrote: > Hi everyone, > > I'm having quite some troubles trying to convert Unicode to String > (for use in psycopg, which apparently doesn't know how to cope with > unicode strings). > > The error I keep having is something like this: > ERREUR: S?quence d'octets invalide pour le codage ?UTF8? : 0xe02063 > > (sorry, locale is french, it means "byte sequence invalid for encoding > <<utf8>>", the value is probably an e with one of the french accents) > > I've found lots of stuff about this googling the error, but I don't > seem to be able to find a "works always"-function just to convert a > unicode variable back to string... > > If someone could find me a solution, that'd really be a lifesaver. > I've been losing hours and hours over this one :s > > thijs > Question is, what should it be converted to when there is no corresponding ascii character to map the offending character to? Do you want to throw it away? Your expectation "works always" is very ill-defined. Write a small function to process the strings yourself and set up a substitution dictionary to do the conversion yourself. -Larry From sjmachin at lexicon.net Fri Aug 31 21:36:44 2007 From: sjmachin at lexicon.net (John Machin) Date: Fri, 31 Aug 2007 18:36:44 -0700 Subject: Parameter Passing - String Variable Truncated ? In-Reply-To: <1188604442.700651.94530@19g2000hsx.googlegroups.com> References: <1188604442.700651.94530@19g2000hsx.googlegroups.com> Message-ID: <1188610604.701171.287210@e9g2000prf.googlegroups.com> On Sep 1, 9:54 am, goldtech <goldt... at worldpost.com> wrote: > Hi, > > I'm passing what I think is a string parameter to another Python > program (spawn.py) - see the code snip below. But only the counter > part gets printed to a log file via spawn.py. Yet the echo print to > the output window shows the whole string with the fc part. Better > explained below I hope, there's the calling .py and the spawn > script .py: > ...snip... > while fc: > counter = counter + 1 > fc_cntr = str(counter) + ' : ' + fc > print fc_cntr + '\n' # Print to Pythonwin interactive window - > eg. "1 : New York" - all is printed OK > > arglist = [] > arglist.append(pythonPath) > arglist.append(spawn_script) > arglist.append(fc_cntr) # This gets sent to the spawn_script but > only "1" gets printed > > os.spawnv(os.P_WAIT, pythonPath, arglist) > fc = fcs.next() > ... > -------------------------- > ## the spawn_script > import win32com.client, sys, os, time, re > > in_featclass = sys.argv[1] > handle = open('C:\\log_file.txt', 'a') > handle.write(in_featclass + "\n") # ONLY the counter part gets printed > to the log file! Why? > -------------------------- Try handle.write(repr(sys.argv[1:]) + "\n") and come back with your conclusions ... unless of course someone has spoonfed you in the meantime. Another clue: write yourself a little arg-dumper script and try running it in a Command Prompt window. 8<--- import sys for x, arg in enumerate(sys.argv): print x, repr(arg) 8<--- HTH, John From afriere at yahoo.co.uk Mon Aug 20 21:18:43 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 20 Aug 2007 18:18:43 -0700 Subject: str().join() isn't working In-Reply-To: <1187634895.387910.179500@m37g2000prh.googlegroups.com> References: <496954360708200905i2100b32ag5983ab729e5d216f@mail.gmail.com> <mailman.4.1187633821.32294.python-list@python.org> <1187634895.387910.179500@m37g2000prh.googlegroups.com> Message-ID: <1187659123.397704.195900@m37g2000prh.googlegroups.com> On Aug 21, 4:34 am, kyoso... at gmail.com wrote: > to concatenate 2 lists to each other before it does the join, ... is > impossible in Python. The "+" operator is only for addition and for > two or more strings. Really? >>> [1,2,3] + [4,5,6] [1, 2, 3, 4, 5, 6] From dummy at example.com Sat Aug 25 06:57:24 2007 From: dummy at example.com (John W. Krahn) Date: Sat, 25 Aug 2007 10:57:24 GMT Subject: Regular expression use In-Reply-To: <famms0$em2$1@gemini.csx.cam.ac.uk> References: <famdl6$p9j$1@gemini.csx.cam.ac.uk> <famlj0$33k$1@mlucom4.urz.uni-halle.de> <famms0$em2$1@gemini.csx.cam.ac.uk> Message-ID: <oWTzi.1954$bO6.752@edtnps89> Nick Maclaren wrote: > In article <famlj0$33k$1 at mlucom4.urz.uni-halle.de>, > Mirco Wahab <wahab-mail at gmx.net> writes: > |> > |> Using complex regular expressions is like tank destruction > |> with contact charges glued on them. Only a few people > |> will even survive the first "usage", but survivors will > |> then eventually be able to destroy almost every tank with > |> tremendous speed and precision. > > I must remember that! It is nicely put. I couldn't understand it. (An old Centurion trooper.) John -- Perl isn't a toolbox, but a small machine shop where you can special-order certain sorts of tools at low cost and in short order. -- Larry Wall From jjl at pobox.com Tue Aug 7 15:49:43 2007 From: jjl at pobox.com (John J Lee) Date: Tue, 7 Aug 2007 20:49:43 +0100 (BST) Subject: mmm-mode, python-mode and doctest-mode? In-Reply-To: <46B8341E.2090805@gradient.cis.upenn.edu> References: <46B8341E.2090805@gradient.cis.upenn.edu> Message-ID: <Pine.LNX.4.64.0708072026540.6411@alice> On Tue, 7 Aug 2007, Edward Loper wrote: > [John J Lee] >> Is it possible to get doctest-mode to work with mmm-mode and python-mode >> nicely so that docstrings containing doctests are editable in doctest-mode? > > I recently released a new version of doctest-mode [1], and I came across your > email [2] (it was on the first page of google hits for "doctest-mode"). So I > decided to have a go at getting doctest-mode to play nicely with mmm-mode. > The result is available here: > > https://python-mode.svn.sf.net/svnroot/python-mode/trunk/python-mode/doctest-mode.el Nice! Works for me so far (emacs 22). I'm also very pleased to see that doctest-mode no longer attempts to auto-fill at the end of long lines -- that was extremely annoying, and the new behaviour is a big improvement. Here's another wish. My next-nearest doctest-mode annoyance: hitting TAB should have similar behaviour to python-mode. So, the first press of the TAB key gets you a sensible guess at the indentation you want. The second and subsequent TAB keypresses cycle through no indentation, '>>>' indentation, and '...' indentation. Ideally this would be made to work in combination with the standard indentation-cycling behaviour in those cases where multiple indentations are allowed within Python code (so, it might be ' ... ', '', ' >>> ', ' ... ',' ... ', ' ... ' as the TAB key is repeatedly pressed). >> `doctest-example' >> >> Used to edit doctest examples in text-editing modes, such as >> `rst-mode' or `text-mode'. Docstring submode regions start with >> optionally indented prompts (>>>) and end with blank lines. Use >> (C-c % C-e) to insert a new doctest-example region. When >> `doctest-execute' (C-c C-c) is called inside a doctest-example >> region, it executes all examples in the buffer. I couldn't immediately see how to get this working in a .doctest file, so haven't tried this yet. Another wish: Even though I don't normally run code from emacs directly, I do think it would be very handy indeed to be able to execute a *single* doctest example from doctest-mode. Don't know what keybinding would be conventional... John From countblabula at yahoo.com Mon Aug 6 15:04:55 2007 From: countblabula at yahoo.com (Lee Fleming) Date: Mon, 06 Aug 2007 12:04:55 -0700 Subject: Something in the function tutorial confused me. In-Reply-To: <mailman.1690.1186424847.22759.python-list@python.org> References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <slrnfbe1fd.n4.horpner@FIAD06.norwich.edu> <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <mailman.1690.1186424847.22759.python-list@python.org> Message-ID: <1186427095.157399.163160@k79g2000hse.googlegroups.com> On Aug 6, 1:26 pm, Steve Holden <st... at holdenweb.com> wrote: > Lee Fleming wrote: > > On Aug 6, 6:25 am, Neil Cerutti <horp... at yahoo.com> wrote: > > Because when the function is called, the line > > >> if y is None: y = [] > > > is executed, binding a brand new empty list to y. This > > "rebinding" happens every time the function is called, unless you > > provide an argument for y that is not None. > > > Thanks for the prompt replies. But I am still confused. This is what > > confuses me.... > > The first time you call the function, say with f(23), after the > > function ends, > > y no longer equals None. Therefore, calling f again, this time like > > this f(24), > > should make y equal [23,24], because the 'if y == None' test fails, or > > at least I think it > > fails, because y.append(x) added something that was not equal to None > > during the previous call. > > > Please help me! > > The thing that doesn't seem to have been stated explicitly is that each > function call creates a brand-new namespace. This namespace is > initialized from the function definition, which includes assignment of > default values to absent keyword arguments. The function definition, > then, contains a reference to each default argument value. > > In the case that tripped you up, however, the default argument you > provided was a mutable object (a list) that can be changed in place by > operations like .append(), whereas when you provide a None default any > further assignment to the argument name binds it to a new value. In the > first case, changes to the object are naturally reflected in later > calls, since it is the object referenced in the function definition that > is being mutated. > > It's only really the same difference as > > a = [1, 2] > b = a > a.append("three") > > which modifies a single list to which both names, a and b, are bound, and > > a = 5 > b = a > a += 3 > > which rebinds the name a to a new object, meaning that a and b are no > longer bound to the same object. > > regards > Steve > > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading -------------- Hide quoted text - > > - Show quoted text - Thanks! I'm glad you all took the time out to help me. :) From gherron at islandtraining.com Sun Aug 19 13:29:10 2007 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 19 Aug 2007 10:29:10 -0700 Subject: How to setup pyOpenGL3.0.a6 for window xp? In-Reply-To: <1187541646.185788.15310@k79g2000hse.googlegroups.com> References: <1187395670.267971.88750@q4g2000prc.googlegroups.com> <1187397743.937458.301590@q3g2000prf.googlegroups.com> <1187541646.185788.15310@k79g2000hse.googlegroups.com> Message-ID: <46C87DE6.30203@islandtraining.com> Jason wrote: > On Aug 17, 6:42 pm, Carl Banks <pavlovevide... at gmail.com> wrote: > >> Windows comes with OpenGL libraries. However, before you can use >> OpenGL you'll need a package that can provide an OpenGL context, which >> PyOpenGL doesn't do (easily). >> >> PyGame is the typical choice for most uses. If all you need is a >> simple window to draw on, this is the package you want. >> If you want an *easy* way to create an OpenGL window and context, you could try FLTK, and it's Python wrapper PyFLTK. It's a simple (nice, very small, well featured and consistent) widget toolkit with OpenGL support. Once the window is open, PyOpenGL (versions 2xx or 3xx) work perfectly on the window. See http://www.fltk.org/ Gary Herron >> However, it doesn't (easily) work with common GUIs like GTK and Wx. >> If you want to use use OpenGL in a GUI app, then you'll want to find >> an "OpenGL canvas widget" for that GUI. >> >> Carl Banks >> > > Sorry Carl, but I'm a bit confused with your third paragraph. Do you > mean that PyGame doesn't work easily with Wx/GTK, or that OpenGL > doesn't work easily with Wx/GTK? > > If it's the second, then I must disagree. wxPython comes with an > OpenGL widget in the "wx.glcanvas" module. The widget only requires > PyOpenGL. The wxPython Demo shows how to set up and program the > widget quite easily. Another example is at: "http:// > aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325392". > > Unfortunately, I don't have much experience with PyGTK. Their FAQ > does indicate that you need an extension to add OpenGL support. > > --Jason > > From neil.chriss at gmail.com Sun Aug 5 22:16:17 2007 From: neil.chriss at gmail.com (RichSaneSwindler) Date: Mon, 06 Aug 2007 02:16:17 -0000 Subject: Pyscripter In-Reply-To: <10a14$46b58c8d$d443bb3a$18267@news.speedlinq.nl> References: <1186302328.706942.242920@q75g2000hsh.googlegroups.com> <10a14$46b58c8d$d443bb3a$18267@news.speedlinq.nl> Message-ID: <1186366577.950835.56100@w3g2000hsg.googlegroups.com> On Aug 5, 4:45 am, Stef Mientki <S.Mientki-nos... at mailbox.kun.nl> wrote: > RichSaneSwindler wrote: > > I think that pyscripter is the most promising Python IDE around > > but for windows only ! > and I > > > am exciting about its possibilities. However, I find a few issues with > > it annoying enough that I don't use it. They seem easily fixed in > > which case I think it would be superior to most IDEs. I am wondering > > if any users out there would like to add to/debate this list of > > benefits and issues (for reference I am using Pyscripter > > Neil, > PyScripter has it's own discussion list > http://groups.google.com/group/PyScripter/topics?hl=en > and from my own experiences, > I know that Kiriakos (the designer) is very willing to listen to good ideas, > and if they are good he'll implement them in no time ! > > cheers, > Stef Thanks, I will copy my message there. Neil From jjl at pobox.com Mon Aug 20 15:38:27 2007 From: jjl at pobox.com (John J. Lee) Date: Mon, 20 Aug 2007 19:38:27 GMT Subject: urllib2.urlopen(url) pulling something other than HTML References: <1187635452.841155.88720@a39g2000hsc.googlegroups.com> Message-ID: <87lkc6xah9.fsf@pobox.com> "dogatemycomputer at gmail.com" <dogatemycomputer at gmail.com> writes: [...] > ---------------------------------------------------------- > f = formatter.AbstractFormatter(formatter.DumbWriter(StringIO())) > parser = htmllib.HTMLParser(f) > parser.feed(html) > parser.close() > return parser.anchorlist > ---------------------------------------------------------- > > I get the idea that we're allocating some memory that looks like a > file so formatter.dumbwriter can manipulate it. Don't worry too much about memory. The "StringIO()" probably only really allocates the memory needed for the "bookkeeping" that StringIO does for its own internal purposes, not the memory needed to actually store the HTML. Later, when you use the object, Python will dynamically (== at run time) allocate the necessary memory for the HTML, when the .write() method is called on the StringIO instance. Python handles the memory allocation for you -- though of course the code you write affects how much memory gets used. Note: - The StringIO is where the *output* HTML goes. - The formatter.DumbWriter likely doesn't do anything with the StringIO() at the time it's passed (it hasn't even seen your HTML yet, so how could it?). Instead, it just squirrels away the StringIO() for later use. > The results are > passed to formatter.abstractformatter which does something else to the > HTML code. Again, nothing much happens right away on the "f = ..." line. The formatter.AbstractFormatter just keeps the formatter so it can use it to format HTML later on. > The results are then passed to "f" which is then passed to The results are not "passed" to f. Instead, the results are given a name, "f". You can give a single object as many names as you like. > htmllib.HTMLParser so it can parse the html for links. I guess I htmllib.HTMLParser wants the formatter so it can format output (e.g. you might want to write out the same page with some of the links removed). It doesn't need the formatter to parse the HTML. HTMLParser itself is responsible for the parsing -- as the name implies. > don't understand with any great detail as to why this is happening. > I know someone is going to say that I should RTFM so here is the gist > of the documentation: > > formatter.DumbWriter = "This class is suitable for reflowing a > sequence of paragraphs." > formatter.AbstractFormatter = "The standard formatter. This > implementation has demonstrated wide applicability to many writers, > and may be used directly in most circumstances. It has been used to > implement a full-featured World Wide Web browser." <-- huh? The web browser in question was called "Grail". Grail has been resting for some time now. By today's standards, "full-featured" is a bit of a stretch. But I wouldn't worry too much about what they're trying to say there yet (it has to do with the way the formatter.AbstractFormatter class is structured, not what it actually does "out of the box"). > So.. What is dumbwriter and abstractformatter doing with this HTML and > why does it need to be done before parser.feed() gets a hold of it? The "heavy lifting" only really actually starts happening when you call parser.feed(). Before that, you're just setting the stage. > The last question is.. I can't find any documentation to explain > where the "anchorlist" attribute came from? Here is the only > reference to this attribute that I can find anywhere in the Python > documentation. > > ---------------------- > anchor_bgn( href, name, type) > This method is called at the start of an anchor region. The > arguments correspond to the attributes of the <A> tag with the same > names. The default implementation maintains a list of hyperlinks > (defined by the HREF attribute for <A> tags) within the document. The > list of hyperlinks is available as the data attribute anchorlist. > ---------------------- That is indeed the (only) documentation for .anchorlist . What more were you expecting to see? > So .. How does an average developer figure out that parser returns a > list of hyperlinks in an attribute called anchorlist? Is this They keep the Library Reference under their pillow :-) And strictly it doesn't *return* a list of links. And that's certainly not HTMLParser's main function in life. It merely makes such a list available as a convenience. In fact, many people instead use module sgmllib, which provides no such convenience, but otherwise does the same parsing work as module htmllib. > something that you just "figure out" or is there some book I should be > reading that documents all of the attributes for a particular > method? It just seems a bit obscure and certainly not something I > would have figured out on my own. Does this make me a poor developer > who should find another hobby? I just need to know if there is > something wrong with me or if this is a reasonable question to ask. But you *did* figure it out. How else is it that you come to be explaining it to us? Keep in mind that *nobody* knows all of the standard library. I've been writing Python code full time for years, and I often bump into whole standard library modules whose existence I'd forgotten about, or was never really aware of in the first place. The more you know about what it can do, the more convenience you'll get out of it, is all. > The last question I have is about debugging. The spider is capable > of parsing links until it reaches: > > "html = get_page(http://www.google.com/jobs/fortune)" which returns > the contents of a pdf document, assigns the pdf contents to html which > is later passed to parser.feed(html) which crashes. [...] > How would an experienced python developer check the contents of "html" > to make sure its not something else other than a blob of HTML code? I > should note an obviously catch-22.. How do I check the HTML in such > a way that the check itself doesn't possibly crash the app? I thought > about: > > try: > parser.feed(html) > except parser.HTMLParseError: > parser.close() > > > .... but i'm not sure if that is right or not? The app still crashes > so obviously i'm doing something wrong. That kind of idea is often the best way. In this case, though, you probably want to do an up-front check by looking at the HTTP Content-Type header (Google for it), something like this: response = urllib2.urlopen(url) html = response.read() if response.info()["Content-Type"] == "text/html": parse(html) John From software at ginstrom.com Sun Aug 26 21:00:42 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Mon, 27 Aug 2007 10:00:42 +0900 Subject: Using Regular Expresions to change .htm to .php in files In-Reply-To: <pan.2007.08.26.10.23.05@mailinator.com> References: <1187896823.843419.53220@q3g2000prf.googlegroups.com><46cdd386$0$27392$88260bb3@free.teranews.com> <pan.2007.08.26.10.23.05@mailinator.com> Message-ID: <008101c7e845$b12b4960$020ba8c0@MOUSE> > On Behalf Of Mark > This line should be: > > sed "s/\.htm$/.php/g" < $each > /tmp/$$ I think a more robust way to go about this would be: (1) Use os.walk to walk through the directory http://docs.python.org/lib/os-file-dir.html (2) Use Beautiful Soup to extract the internal links from each file http://crummy.com/software/BeautifulSoup/documentation.html from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(doc) links = soup('a') internal_links = [link["href"] for link in links if link.has_key("href") and not link["href"].startswith("http")] (4) Do straight string replacements on those links (no regex needed) (5) Save each html file to *.html.bak before changing Regards, Ryan Ginstrom From bdesth.quelquechose at free.quelquepart.fr Thu Aug 30 06:56:19 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 30 Aug 2007 12:56:19 +0200 Subject: Python doesn't see the directories I create In-Reply-To: <5jns3vFdmbcU6@mid.uni-berlin.de> References: <ldvBi.293202$LE1.92748@newsfe13.lga> <46d6856b$0$17674$426a74cc@news.free.fr> <mailman.133.1188471584.28954.python-list@python.org> <46d6a72c$0$20532$426a74cc@news.free.fr> <mailman.134.1188473377.28954.python-list@python.org> <5jns3vFdmbcU6@mid.uni-berlin.de> Message-ID: <46d7405e$0$421$426a74cc@news.free.fr> Marc 'BlackJack' Rintsch a ?crit : > On Thu, 30 Aug 2007 07:28:52 -0400, Steve Holden wrote: > > >>Bruno Desthuilliers wrote: >> >>>Steve Holden a ?crit : >>>Indeed. But I doubt a path starting with 'C:' will work fine on a >>>unix-like environment anyway !-) >> >>Just to be contrarian: >> >>sholden at bigboy ~/Projects/python.org/build >>$ ls C:/Steve/ >>Apache SANSsecurityOverview.pdf >>Apache2 SQLServer.txt >> ... >>Resume.odt todo.txt >>Resume.pdf untitled-1.py >> >>sholden at bigboy ~/Projects/python.org/build >> >>That's Cygwin, of course. Is that sufficiently "unix-like"? Though I >>have to admit that the different utilities all take different approaches >>to the use of Windows paths, and some just won't take them at all. > > Even on Unix it shouldn't be a problem on most file systems to create a > directory named 'C:' > > bj at s8n:~$ mkdir C: > bj at s8n:~$ touch C:/test.txt > bj at s8n:~$ ls -l C: > total 0 > -rw-r--r-- 1 bj bj 0 2007-08-30 14:38 test.txt > > :-) Ok, I get it, you guys are trying to make me mad !-) From DustanGroups at gmail.com Sun Aug 12 20:39:29 2007 From: DustanGroups at gmail.com (Dustan) Date: Mon, 13 Aug 2007 00:39:29 -0000 Subject: Complexity of methods etc In-Reply-To: <mailman.1892.1186963490.22759.python-list@python.org> References: <mailman.1892.1186963490.22759.python-list@python.org> Message-ID: <1186965569.076575.288090@l70g2000hse.googlegroups.com> On Aug 12, 7:04 pm, "Nathan Harmston" <ratchetg... at googlemail.com> wrote: > Hi, > > I was wondering if anyone knew of any resources, where I might be able > to find information about the complexity of certain python functions > or little tips on how to reduce complexity. I mean like the "".join(), > kind of thing? > > I want to see if there are any improvements I can add to my coding in > order to reduce time/space usage/ It's really difficult to understand what you mean. If you're looking for a reference on the functions that are available in the library, you have a long journey ahead of you at http://docs.python.org/ . From ptmcg at austin.rr.com Mon Aug 20 11:54:55 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 20 Aug 2007 08:54:55 -0700 Subject: regular expression dictionary search In-Reply-To: <mailman.25.1187624159.26576.python-list@python.org> References: <d6a0d8f10708181139m730d7aa6t1c9f6e624d6db9aa@mail.gmail.com> <mailman.25.1187624159.26576.python-list@python.org> Message-ID: <1187625295.287653.137080@r34g2000hsd.googlegroups.com> On Aug 20, 10:35 am, "Shawn Milochik" <Sh... at Milochik.com> wrote: > #!/usr/bin/env python <snip> > if __name__ == "__main__": > > print "The return for 'fred' : %s" % returnCode('fred') > print "The return for 'silk' : %s" % returnCode('silk') > print "The return for 'silky' : %s" % returnCode('silky') > print "The return for 'hand' : %s" % returnCode('hand') > print "The return for 'strand' : %s" % returnCode('strand') > print "The return for 'bank' : %s" % returnCode('bank') > Shawn - All that copy/pasting has got to have carpal tunnel written all over it - DRY! tests = "fred silk silky hand strand bank".split() for test in tests: print "The return for '%s' : %s" % (test, returnCode(test)) -- Paul From kyosohma at gmail.com Wed Aug 15 12:07:16 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 15 Aug 2007 09:07:16 -0700 Subject: moving files in a seperate thread (and/or with progress?) In-Reply-To: <mailman.1999.1187170117.22759.python-list@python.org> References: <mailman.1999.1187170117.22759.python-list@python.org> Message-ID: <1187194036.856068.323750@j4g2000prf.googlegroups.com> On Aug 15, 4:28 am, "Jorgen Bodde" <jorgen.maill... at gmail.com> wrote: > Hi all, > > I want to make a small batch copy tool that scans for certain files, > and copies them to a specified directory. Since the files are huge > (AVI / DIVX) typical 300 to 700 Mb, I want to provide the user with > some feedback during the file copy. > > Here is my dillemma; When I use shutil.move(..,..) I have to wait > until it's done, there is no feedback, so the GUI basically hangs. > However, shutil.move can be fast because it intelligently renames the > file when it is on the same medium, but slow when it moves to a > different one. > When I use my own implementation of a move mechanism that provides > feedback, I lose that intelligence, and I might slow down the copy > process unneccessarily. > > When I move files, feedback is handy to have, but not neccesary so I > thought I can also call shutil.move from a seperate thread so the main > GUI stays responsive. What are my options in aborting a move by > killing the thread or are there other (3rdparty) modules I might use > to get better move or copy performances? > > Just opening the file, performing a block copy myself seems like it > will slow down the transfer, but up until now I found no way to move > or copy with progress or abilities to abort the file transfer.. > > Any ideas? > > Regards, > - Jorgen What GUI toolkit are you using? I know that wxPython has a status widget that could be updated in a thread and it has some good examples of using threads with long running tasks. I created a program with it that deletes folders and updates me on its progress. You can see the wxPython implementation here: http://wiki.wxpython.org/LongRunningTasks Their widget is called a ProgressDialog. I think there's a custom one too... Mike From arkanes at gmail.com Tue Aug 21 15:45:17 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 21 Aug 2007 14:45:17 -0500 Subject: Python Path Dictionary In-Reply-To: <1187723618.729114.19020@19g2000hsx.googlegroups.com> References: <1187706985.476483.292820@g4g2000hsf.googlegroups.com> <mailman.66.1187710972.32294.python-list@python.org> <1187723618.729114.19020@19g2000hsx.googlegroups.com> Message-ID: <4866bea60708211245h655475b1gd7f2f2832898c376@mail.gmail.com> On 8/21/07, aine_canby at yahoo.com <aine_canby at yahoo.com> wrote: > On 21 Aug, 17:42, Gary Herron <gher... at islandtraining.com> wrote: > > aine_ca... at yahoo.com wrote: > > > Hi, > > > > > Do the Python Paths come in the form of a dictionary where I can > > > access a particular path my its key in the registry? > > > > > For example, in PythonWin Tools>>Edit Python Paths shows the name as > > > well of the address of each path > > > > > Thanks, > > > > > Aine > > > > If by "Python Paths" you mean the list of directories searched when > > doing an import, then it is a list (not a dictionary and you can access > > it as sys.path. > > > > Here it is on both my Linux and Windows systems: > > > > >>> import sys > > >>> sys.path > > > > ['', '/usr/lib/portage/pym', '/usr/lib/python25.zip', > > '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', > > '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', > > '/usr/lib/python2.5/site-packages', > > '/usr/lib/python2.5/site-packages/Numeric', > > '/usr/lib/python2.5/site-packages/PIL', > > '/usr/lib/python2.5/site-packages/gtk-2.0'] > > > > >>> import sys > > >>> sys.path > > > > ['', 'C:\\WINDOWS\\system32\\python24.zip', 'C:\\cygwin\\home\\Gary', > > 'c:\\python24\\DLLs', 'c:\\python24\\lib', > > 'c:\\python24\\lib\\plat-win', 'c:\\python24\\lib\\lib-tk', > > 'c:\\python24', 'c:\\python24\\lib\\site-packages', > > 'c:\\python24\\lib\\site-packages\\Numeric', > > 'c:\\python24\\lib\\site-packages\\PIL', > > 'c:\\python24\\lib\\site-packages\\gtk-2.0', > > 'c:\\python24\\lib\\site-packages\\win32', > > 'c:\\python24\\lib\\site-packages\\win32\\lib', > > 'c:\\python24\\lib\\site-packages\\Pythonwin'] > > Thanks. > > Yeah, that's exactly what I'm talking about, but I don't want the > list, I want to access a certain path by name. I'm guessing I'm going > to have to write a function to do this that reads the value from the > registry. > The elements of the path don't have names - they are a list of directories. You are mistaking Pythonwins configuration options (like where it searches for modules) for the python path. Note that the registry entry "PythonPath" (which is not respected by Python, but used by Pythonwin to override the default python path) is a semi-colon separated list, not a series of keys. From rdm at rcblue.com Sun Aug 19 17:56:25 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 19 Aug 2007 14:56:25 -0700 Subject: A problem with Time In-Reply-To: <46c469be$0$66145$7b0f0fd3@mistral.news.newnet.co.uk> References: <46c469be$0$66145$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <20070819215631.963231E4014@bag.python.org> At 08:30 AM 8/16/2007, special_dragonfly wrote: >Hello, > >I need to return the date yesterday in the form DDMMYYYY. I looked through >the modules: time, datetime and calendar but can't find anything that leaps >out at me. > >The problem I'm having is that although I can use time.localtime and get a >tuple of the year, month, day and so forth, I don't believe I can just minus >1 from the day, because I don't think it's cyclic, also, I can't see the >date being linked in with the month. > >So is there any way of getting yesterdays date? The question has already been well-answered, but since I've found using the datetime module to be tough going, I was wondering if either of these would be easier to understand and use: 1. <http://www.egenix.com/products/python/mxBase/mxDateTime/> I see that mxDateTime comes with a 55-page manual as a PDF. 2. <http://labix.org/python-dateutil> Dick Moores From rhamph at gmail.com Wed Aug 29 21:23:52 2007 From: rhamph at gmail.com (Adam Olsen) Date: Wed, 29 Aug 2007 19:23:52 -0600 Subject: Is LOAD_GLOBAL really that slow? Message-ID: <aac2c7cb0708291823h15e3f675mbeae9ecf37d653b6@mail.gmail.com> It seems a common opinion that global access is much slower than local variable access. However, my benchmarks show a relatively small difference: ./python -m timeit -r 10 -v -s 'x = [None] * 10000 def foo(): for i in x: list; list; list; list; list; list; list; list; list; list' 'foo()' 10 loops -> 0.0989 secs100 loops -> 0.991 secs raw times: 0.999 0.985 0.987 0.985 0.985 0.982 0.982 0.982 0.981 0.985 100 loops, best of 10: 9.81 msec per loop ./python -m timeit -r 10 -v -s 'x = [None] * 10000 def foo(): mylist = list for i in x: mylist; mylist; mylist; mylist; mylist; mylist; mylist; mylist; mylist; mylist' 'foo()' 10 loops -> 0.0617 secs 100 loops -> 0.61 secs raw times: 0.603 0.582 0.582 0.583 0.581 0.583 0.58 0.583 0.584 0.582 100 loops, best of 10: 5.8 msec per loop So global access is about 70% slower than local variable access. To put that in perspective, two local variable accesses will take longer than a single global variable access. This is a very extreme benchmark though. In practice, other overheads will probably drop the difference to a few percent at most. Not that important in my book. So my question: does somebody have a globals benchmark that shows a really significant slowdown vs local variables? -- Adam Olsen, aka Rhamphoryncus From jstroud at mbi.ucla.edu Fri Aug 3 21:32:54 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 03 Aug 2007 18:32:54 -0700 Subject: How to pass a reference to the current module In-Reply-To: <mailman.1598.1186190388.22759.python-list@python.org> References: <f90gsg$ek4$1@zinnia.noc.ucla.edu> <f90im3$8ms$1@daisy.noc.ucla.edu> <mailman.1598.1186190388.22759.python-list@python.org> Message-ID: <f90l06$hic$2@zinnia.noc.ucla.edu> Carsten Haese wrote: > This seems to confirm my suspicion that the do_something_with function > doesn't actually need a reference to the module, it only needs a > reference to the function to call. > > Maybe your hurdle is how to obtain a reference to a function from the > current module when all you have is the name of the function in a > string. The answer to that would be "globals()[funcname]". This is like a bad case of phone-tag. Please see my response to your previous post for why this does not seem feasible to me. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From horpner at yahoo.com Thu Aug 9 09:13:27 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 09 Aug 2007 13:13:27 GMT Subject: check if regeular expression has results References: <1186664302.050036.302670@g4g2000hsf.googlegroups.com> Message-ID: <slrnfbm4vk.194.horpner@FIAD06.norwich.edu> On 2007-08-09, shahargs at gmail.com <shahargs at gmail.com> wrote: > Hi, > I'm looking for the best way to check if regular expression return > true (it's mean - there is a match). for example, i want "if" that > check if this regular expression: .*born.*to.* has a match. > > What's the way to do that simply? Newgroups are a poor substitute for the docs. For one thing, newsgroups sometimes contain cranky people who say, "RTFM!" The docs will never do that. -- Neil Cerutti From anno4000 at radom.zrz.tu-berlin.de Fri Aug 24 07:39:23 2007 From: anno4000 at radom.zrz.tu-berlin.de (anno4000 at radom.zrz.tu-berlin.de) Date: 24 Aug 2007 11:39:23 GMT Subject: Regular expression use References: <famdl6$p9j$1@gemini.csx.cam.ac.uk> Message-ID: <5j7ubbF3sovufU1@mid.dfncis.de> Nick Maclaren <nmm1 at cus.cam.ac.uk> wrote in comp.lang.perl.misc: > > For reasons that I won't explain, as they are too complicated > and not terribly relevant, Your reasons are relevant as a motivation for your readers to answer such a broad question. > I am interested in discovering what > people actually use regular expressions for. Not the subject > domain, but the construction of the regular expressions. How is the construction of a regex related to what it is used for? That makes no sense. > I know about computer scientists and parsing, That's a (broad) subject domain. > and I know about > the use of relatively simple ones for things like extracting > HTML links from Web pages. That's another subject domain (and a regex for that purpose wouldn't qualify as "relatively simple"). > But I don't have much feel for the > (probably rare but difficult) uses of more complex ones for > other purposes. I have heard of several such uses, but don't > have an overall idea of what is going on. Your question is so badly defined, it would take considerable effort just to make sense of it. Given your premise of "Never mind what I need it for, just gimme the info," I won't even try. Anno From raims at dot.com Tue Aug 7 05:53:18 2007 From: raims at dot.com (Lawrence Oluyede) Date: Tue, 7 Aug 2007 11:53:18 +0200 Subject: get wikipedia source failed (urrlib2) References: <1186476847.728759.166610@o61g2000hsh.googlegroups.com> <1186479277.356613.111630@r34g2000hsd.googlegroups.com> Message-ID: <1i2h4ye.1jt6b1gh2e7rwN%raims@dot.com> <shahargs at gmail.com> wrote: > This source works fine for other site. the problem is in wikipedia. is > someone now any solution for this problem? Wikipedia, AFAIK, bans requests without a User Agent. http://www.voidspace.org.uk/python/articles/urllib2.shtml#headers -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From philippe.martin at att.net Sun Aug 26 19:54:14 2007 From: philippe.martin at att.net (hg) Date: Sun, 26 Aug 2007 23:54:14 GMT Subject: SCF (Python Smar Card Framework) In-Reply-To: <7x8x7xsws0.fsf@ruckus.brouhaha.com> References: <7OnAi.21500$eY.10887@newssvr13.news.prodigy.net> <7x8x7xsws0.fsf@ruckus.brouhaha.com> Message-ID: <GooAi.3699$JD.909@newssvr21.news.prodigy.net> Paul Rubin wrote: > hg <philippe.martin at att.net> writes: >> I am releasing much of my work including SCF (Cross platform Smart >> Card library & Tools) to the GPL license. >> >> If interested, go to http://www.SnakeCard.com/Source.html > > Wow, that is great. I haven't found any low cost programmable cards > (no large quantity purchases or developer licenses needed) other than > BasicCard which has some annoying limitations. Do you have any > suggestions? Thanks! > How about you post that on the forum I just opened ... we're going to get killed here ;-) hg From carsten at uniqsys.com Fri Aug 31 20:33:17 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 31 Aug 2007 20:33:17 -0400 Subject: Python Unicode to String conversion In-Reply-To: <1188600916.528901.189680@d55g2000hsg.googlegroups.com> References: <1188600916.528901.189680@d55g2000hsg.googlegroups.com> Message-ID: <1188606797.3221.13.camel@localhost.localdomain> On Fri, 2007-08-31 at 15:55 -0700, thijs.braem at gmail.com wrote: > Hi everyone, > > I'm having quite some troubles trying to convert Unicode to String > (for use in psycopg, which apparently doesn't know how to cope with > unicode strings). > > The error I keep having is something like this: > ERREUR: S?quence d'octets invalide pour le codage ?UTF8? : 0xe02063 I'm guessing that you are passing a latin-1 encoded string and pretend (or psycopg assumes) incorrectly that it's UTF-8 encoded. In latin-1 encoding, 0xe0 is a small letter a with a grave accent, 0x20 is a space, and 0x63 is a small letter c. While this is a perfectly valid latin-1 encoded character string, it doesn't represent a valid UTF-8 encoded character string. It seems that you need to pass a UTF-8 encoded string to the database. To give you specific advice on how to do that, we'd have to see your code. For now, I'll give you the generic advice of taking a look at http://www.amk.ca/python/howto/unicode . HTH, -- Carsten Haese http://informixdb.sourceforge.net From nawijn at gmail.com Wed Aug 29 08:09:35 2007 From: nawijn at gmail.com (Marco Nawijn) Date: Wed, 29 Aug 2007 05:09:35 -0700 Subject: Code design problem Message-ID: <1188389375.238847.298320@w3g2000hsg.googlegroups.com> Hello, I have a hard time figuring out an elegant and efficient design for the following problem. I am working on automation of structural design problems. In the majority of cases, this boils down to executing programs in batch in one or more loops. The scripts to control the execution differ from fortran to bash to python and so on. Most of them are ad hoc and what I call 'throw away scripts'. In order to improve the situation I would like to develop a Python module that supports the execution of external programs. Ideally I would like to make running locally or remote trivial for the users of the module. As an example, I would like the following (pseudo)-code to work: app = Application('patran') # Run on local machine app.start(args) app = Application('patran', host='myhost') # Run on remote machine app.start(args) The problem I face is that the implementation of the application class is completely different for the local and remote case. The local case is a straightforward implemenation using the subprocess module, the remote case is a CORBA implementation. Somehow I would like to switch from implementation class at runtime depending on whether or not the host parameter is specified or not. The Application, local implementation and remote implementation all have the same interface, so a possibility might be something like the following: class Interface(object): ..... def start(self): pass def stop(self): pass class LocalImplementation(Interface): ..... class GlobalImplementation(CorbaGlobalImplementation, Interface): ..... class Application(Interface): def __init__(self, program, host=None): .... if host: self.__impl = LocalImplementation(program) else: self.__impl = GlobalImplementation(program, host) # Forward all methods to the implementation class def start(self): self.__impl.start() def stop(self): self.__impl.stop() To me forwarding each call in the Application class looks a little bit redundant and I would like to get rid of it. Does anyone have any comments or suggestions? Can metaclass programming come to rescue? Kind regards, Marco Nawijn From jcd at sdf.lonestar.org Fri Aug 24 15:20:56 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 24 Aug 2007 15:20:56 -0400 Subject: How to replace a method in an instance. In-Reply-To: <alpine.LFD.0.999.0708241254420.30194@saturn.syslang.net> References: <mailman.258.1187971369.32294.python-list@python.org> <1187971953.261328.219000@q3g2000prf.googlegroups.com> <alpine.LFD.0.999.0708241223480.30194@saturn.syslang.net> <alpine.LFD.0.999.0708241254420.30194@saturn.syslang.net> Message-ID: <46CF2F98.8020000@sdf.lonestar.org> Steven W. Orr wrote: > On Friday, Aug 24th 2007 at 12:26 -0400, quoth Steven W. Orr: > > =>On Friday, Aug 24th 2007 at 09:12 -0700, quoth kyosohma at gmail.com: > => > =>=>On Aug 24, 11:02 am, "Steven W. Orr" <ste... at syslang.net> wrote: > =>=>> In the program below, I want this instance to end up calling repmeth > =>=>> whenever inst.m1 is called. As it is now, I get this error: > =>=>> > =>=>> Hello from init > =>=>> inst = <__main__.CC instance at 0x402105ec> > =>=>> Traceback (most recent call last): > =>=>> File "./foo9.py", line 17, in ? > =>=>> inst.m1() > =>=>> TypeError: repmeth() takes exactly 1 argument (0 given) > =>=>> > =>=>> #! /usr/bin/python > =>=>> def repmeth( self ): > =>=>> print "repmeth" > =>=>> > =>=>> class CC: > =>=>> def __init__( self ): > =>=>> self.m1 = repmeth > =>=>> print 'Hello from init' > =>=>> > =>=>> def m1 ( self ): > =>=>> print "m1" > =>=>> > =>=>> inst = CC() > =>=>> inst.m1() > => > =>=>Remove "self" from repmeth as it's not required in a function, only in > =>=>functions that are defined within a class. Of course, a function in a > =>=>class is also know as a method. > => > =>Sorry. I need repmeth to have self passed to it automatically if it's > =>called. I didn't mean to obfuscate the problem by not making a reference > =>to self in repmeth. > => > =>Am I being clear? > > On Friday, Aug 24th 2007 at 18:44 +0200, quoth Wildemar Wildenburger: > > =>Steven W. Orr wrote: > =>> Sorry. I need repmeth to have self passed to it automatically if it's > =>> called. I didn't mean to obfuscate the problem by not making a > reference > =>> to self in repmeth. > =>> > =>> Am I being clear? > =>> > =>> > =>Sort of. Maybe you fare better if you state what you want to achieve, > =>instead of how you think you should do it. Chances are you don't need to > =>replace a method in __init__, but there's another, less tricky way. > > Ok. I have a collection of classes that are produced by a factory. They > all inherit from a baseclass. One (maybe more) of the classes inherits a > method that he shouldn't. All I want is to be able to change that > particular class so that he will have the special method that he needs > instead of the default one that he inherits. I was thinking that instead > of making a special class for CC to inherit from which would give him his > special replacement method(s), I could simply assign them in a manner > which would more easily lend itself to later being table driven. > > If I had a choice, I'd rather not do it in init. Instead, I'd rather be > able to say something like > CC.m1 = repmeth > but since in the real world, CC inherits from his baseclass, the above > assignment causes the baseclass to be altered. :-( > > Please tell me if I need to provide more. > > Is there a reason you don't just create a subclass for the one that needs to call repmeth? class CC(object): def m1(self): print "m1" def m2(self): print "m2" class SpecialCC(CC): def m1(self): print "something else!" if __name__ == '__main__': a = CC() b = SpecialCC() for instance in a, b: instance.m1() instance.m2() --Output-- m1 m2 something else! m2 Is that what you're looking for, mas o menos? Cheers, Cliff From msherman77 at yahoo.com Wed Aug 22 17:51:35 2007 From: msherman77 at yahoo.com (Michael S) Date: Wed, 22 Aug 2007 17:51:35 -0400 (EDT) Subject: Python for web development ... In-Reply-To: <1187799217.054726.109380@z24g2000prh.googlegroups.com> Message-ID: <796330.18826.qm@web88303.mail.re4.yahoo.com> Check out http://www.modpython.org/, you can also use python with CGI http://docs.python.org/lib/module-cgi.html or fastcgi http://www.fastcgi.com/ --- thushianthan15 at gmail.com wrote: > > Hi everyone, > > I have to do a web based application for my final > year project. Since, > i am only familiar with basic HTML and Java Script, > i am totally new > to this one. My friends are using LAMP (P->PHP). But > i want to use > Python. Is it possible to use Python with Apache and > MySQL. Is it > possible ? Any websites/books ? > > Thank you > > -- > http://mail.python.org/mailman/listinfo/python-list > From aahz at pythoncraft.com Sat Aug 11 10:36:59 2007 From: aahz at pythoncraft.com (Aahz) Date: 11 Aug 2007 07:36:59 -0700 Subject: Augmented assignment (was Re: Something in the function tutorial confused me.) References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> <m3hvi.37606$G23.6240@newsreading01.news.tds.net> <f9kdpq$drp$1@panix3.panix.com> <bAjvi.47120$wv5.1434653@phobos.telenet-ops.be> Message-ID: <f9khib$kvq$1@panix3.panix.com> In article <bAjvi.47120$wv5.1434653 at phobos.telenet-ops.be>, Roel Schroeven <rschroev_nospam_ml at fastmail.fm> wrote: >Aahz schreef: >> >> Although Alex is essentially correct, the situation is a bit more complex >> and you are correct that augmented assignment allows the object to decide >> whether to mutate in place. However, the critical part of Alex's point >> is what you need to focus on: it's the *tuple* in Alex's example that >> intercepts the assignment call, not the list contained in the tuple. >> >> Obviously, you can easily work around it: >> >>>>> t = ([],) >>>>> l = t[0] >>>>> l += ['foo'] >>>>> t >> (['foo'],) > >I'm missing something here, I think. As far as I can tell, the language >reference says that the target is evaluated before the augmented >assignment is performed. If that's the case, I don't see how the tuple >in Alex' example has anything to with it: the assignment is to the list, >not the tuple. > >And watch this (Python 2.4.2): > > >>> tup = ([],) > >>> tup[0] += ['zap'] > >Traceback (most recent call last): > File "<pyshell#10>", line 1, in -toplevel- > tup[0] += ['zap'] >TypeError: object does not support item assignment > >So far that's the same as Alex' example, but look at the value of the >tuple now: > > >>> tup >(['zap'],) > >Despite the TypeError, the list *has* changed. Yup! Here's why: >>> def foo(bar): bar[0] += ['zap'] ... >>> import dis >>> dis.dis(foo) 1 0 LOAD_FAST 0 (bar) 3 LOAD_CONST 1 (0) 6 DUP_TOPX 2 9 BINARY_SUBSCR 10 LOAD_CONST 2 ('zap') 13 BUILD_LIST 1 16 INPLACE_ADD 17 ROT_THREE 18 STORE_SUBSCR 19 LOAD_CONST 0 (None) 22 RETURN_VALUE Notice the critical sequence: BINARY_SUBSCR, INPLACE_ADD, STORE_SUBSCR. It has to work that way to allow this: >>> l = [7] >>> l[0] += 1 >>> l [8] There's simply no way to get augmented assignment to work correctly with both lists and tuples when you allow both mutable and immutable elements. Someone will always get surprised, and overall with strings and numbers being the canonical list elements, I think making augmented assignment work correctly with lists and immutables was the best decision. But the unfortunate side-effect is that you get the TypeError with augmented assignment in tuples only after the mutation has been done. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "And if that makes me an elitist...I couldn't be happier." --JMS From Shawn at Milochik.com Fri Aug 17 14:29:03 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Fri, 17 Aug 2007 14:29:03 -0400 Subject: question In-Reply-To: <1187373737.410546.70930@w3g2000hsg.googlegroups.com> References: <1187373737.410546.70930@w3g2000hsg.googlegroups.com> Message-ID: <2dc0c81b0708171129m284b4940l30f5dec01e7b52c1@mail.gmail.com> You need to post some kind of code (even non-working) to show that you've actually done some work. Nobody will do your work for you. From stargaming at gmail.com Mon Aug 6 04:43:53 2007 From: stargaming at gmail.com (Stargaming) Date: 06 Aug 2007 08:43:53 GMT Subject: Something in the function tutorial confused me. References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> Message-ID: <46b6df49$0$26165$9b622d9e@news.freenet.de> On Sun, 05 Aug 2007 23:50:24 -0700, Lee Fleming wrote: > Hello, > I have a simple question. Say you have the following function: > > def f(x, y = []): > y.append(x) > return y > > print f(23) # prints [23] > print f(42) # prints [23, 42] > > As far as I understand, the default value y, an empty list, is created > when the def statement evaluates. With this thought in mind, the above > calls > to f make sense. > > But this, the code that "fixes" the list accumulation confounds me: def > f(x, y=None): > if y is None: y = [] > y.append(x) > return y > > print f(23) # prints [23] > print f(42) # prints [42] > > Why didn't the second call to f, f(42) return [23, 42]? As I understand > it, y is only None at the beginning of f(23). Then y changes from None > to 23. When f ends, doesn't y still have 23 in it, > just as it did in the first function I discussed? And if y has 23 in it, > won't the second call to f not execute what's in the if statement? > > In other words, what's going on here? How is it that y accumulates > argument values between function calls in the first function, but > doesn't in the second one? You're just unluckily shadowing the name `y` in the local scope of your function. Your code snippet could be rewritten as:: def f(x, y=None): if y is None: my_y = [] else: my_y = y my_y.append(x) return my_y HTH, Stargaming From richyjsm at gmail.com Wed Aug 8 20:43:02 2007 From: richyjsm at gmail.com (richyjsm at gmail.com) Date: Thu, 09 Aug 2007 00:43:02 -0000 Subject: what's the point of pow()? Message-ID: <1186620182.116846.327350@57g2000hsv.googlegroups.com> it's a serious question: why does the builtin pow function exist? for two argument pow we've got **. there's no add() for + or mul() for *.... and three argument pow-with-modulo seems like specilaist usage that belongs in the standard lib, not in the core. I know about crypto and number theory uses. are there others? it's obviously useful for something or else it would be slated for removal in python 3000, surely? Richard From robert.kern at gmail.com Mon Aug 20 15:41:53 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 20 Aug 2007 14:41:53 -0500 Subject: Mouse control with ctypes in OS X In-Reply-To: <facpo6$6h3$1@sea.gmane.org> References: <20070820135358.0B3052303D@atmail.b-one.net> <46C9CECC.6010401@ulmcnett.com> <facpo6$6h3$1@sea.gmane.org> Message-ID: <facqq2$90l$2@sea.gmane.org> Robert Kern wrote: > Googling around a bit more, however, I see that the Quartz Event Services is > documented and provides similar functionality. The DarwiinRemote project has a > mouse emulation mode for the Nintendo Wii controller that uses this API. It's > only available in OSX 10.4, however. Apologies for the self-response, but reading the docs more I see that CGPostMouseEvent(), the most relevant function in the API, has been available since 10.0. Sweet. That's just what I've been looking for, too. -- 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 david at asdf.asdf Mon Aug 27 01:21:37 2007 From: david at asdf.asdf (bambam) Date: Mon, 27 Aug 2007 15:21:37 +1000 Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com> <1187898049.734696.9500@l22g2000prc.googlegroups.com> <13csi2tn49esmc3@corp.supernews.com> <mailman.230.1187928865.32294.python-list@python.org> <13csqk47j0c56b0@corp.supernews.com> <CqSdnRl2x8928FPbnZ2dnUVZ_jSdnZ2d@speakeasy.net> <13ct7v3qn2v5206@corp.supernews.com> <mailman.238.1187948359.32294.python-list@python.org> <13d49lk6ue2as6d@corp.supernews.com> <13d4hutad1dq699@corp.supernews.com> <1i3h176.kjfosu1ly2afyN%aleax@mac.com> Message-ID: <13d4nr2b3sfm233@corp.supernews.com> Thank you. Steve. "Alex Martelli" <aleax at mac.com> wrote in message news:1i3h176.kjfosu1ly2afyN%aleax at mac.com... > bambam <david at asdf.asdf> wrote: > >> Is it safe to write >> >> A = [x for x in A if x in U] >> >> or is that undefined? I understand that the slice operation > > It's perfectly safe and well-defined, as the assignment rebinds the LHS > name only AFTER the RHS list comprehension is done. > > > Alex From wolf_tracks at invalid.com Thu Aug 23 07:30:26 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 23 Aug 2007 04:30:26 -0700 Subject: Baby Steps, optionDB In-Reply-To: <1187862216.183609.89810@r23g2000prd.googlegroups.com> References: <Uk7zi.1531$vU4.979@nlpi068.nbdc.sbc.com> <1187862216.183609.89810@r23g2000prd.googlegroups.com> Message-ID: <Pcezi.6450$924.6108@newssvr23.news.prodigy.net> That got things moving. Thanks. It looks like I have some typos to deal with now. I used to program in C++, and there's one thing I've never liked about OOP. Too much typing! Padraig wrote: > On Aug 23, 4:41 am, "W. Watson" <wolf_tra... at invalid.com> wrote: >> root.option_readfile('optionDB') > > Just leave out the line which tries to read in the non-existent config > file... > -- Wayne Watson (Nevada City, CA) Web Page: <speckledwithStars.net> From __peter__ at web.de Fri Aug 17 14:23:32 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 17 Aug 2007 20:23:32 +0200 Subject: Making a copy (not reference) of a file handle, or starting stdin over at line 0 References: <mailman.2115.1187372888.22759.python-list@python.org> Message-ID: <fa4p36$5gj$02$1@news.t-online.com> Shawn Milochik wrote: > How can I check a line (or two) from my input file (or stdin stream) > and still be able to process all the records with my function? One way: from itertools import chain firstline = instream.next() head = [firstline] # loop over entire file for line in chain(head, instream): process(line) You can of course read more than one line as long as you append it to the head list. Here's an alternative: from itertools import tee a, b = tee(instream) for line in a: # determine file format, # break when done # this is crucial for memory efficiency # but may have no effect in implementations # other than CPython del a # loop over entire file for line in b: # process line Peter From tomtim20 at gmail.com Fri Aug 24 03:53:16 2007 From: tomtim20 at gmail.com (tomtim20 at gmail.com) Date: Fri, 24 Aug 2007 00:53:16 -0700 Subject: Unequal Length Maze Message-ID: <1187941996.333191.323540@z24g2000prh.googlegroups.com> Hi All, what's the best algorithm to solve such problem ? http://www.stetson.edu/~efriedma/unequal/ I will really appreciate some pieces of code (python). Thanks, Tommy From vedrandekovic at v-programs.com Mon Aug 20 05:32:17 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Mon, 20 Aug 2007 02:32:17 -0700 Subject: building exe from script Message-ID: <1187602337.366419.92930@r29g2000hsg.googlegroups.com> Hello, Is there any solution for building exe file from python script something like bbfreeze.When user write some script in my program, it must compile script into exe without opening console ( cmd ).I'am working on Windows XP SP2 and Python 2.5. Regards, Vedran From kyosohma at gmail.com Mon Aug 20 11:06:30 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 20 Aug 2007 08:06:30 -0700 Subject: Newbee Question In-Reply-To: <mailman.19.1187621934.26576.python-list@python.org> References: <mailman.15.1187620149.26576.python-list@python.org> <1187621470.484615.7010@i13g2000prf.googlegroups.com> <mailman.19.1187621934.26576.python-list@python.org> Message-ID: <1187622390.854759.162320@q3g2000prf.googlegroups.com> On Aug 20, 9:58 am, "Shawn Milochik" <Sh... at Milochik.com> wrote: > On 8/20/07, kyoso... at gmail.com <kyoso... at gmail.com> wrote: > > > > > On Aug 20, 9:23 am, "HD1956" <hd7... at hotmail.com> wrote: > > > This is probably a simple code. I am a truck driver who gets paid by > > > stops and cases. I am trying to figure out how to code my stop pay. I > > > get 40 cents per stop up to 22 stops, and $1.40 per stops after that. > > > def calc(num): > > if num < 23: > > return 0.4 * num > > else: > > overtime = num - 22 > > x = 0.4 * 22 > > x += overtime * 1.4 > > return x > > > # Use your own brain next time > > > Mike > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Mike, > > I wonder if we were both just duped into helping someone with their homework... > > Shawn I like to write code, so it's not a big deal when it's something so simple. Still, that is beyond dumb! Nice code, by the way. Mike From aboudouvas at panafonet.gr Tue Aug 21 08:23:19 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Tue, 21 Aug 2007 05:23:19 -0700 Subject: IDE for Python In-Reply-To: <mailman.55.1187690455.32294.python-list@python.org> References: <mailman.55.1187690455.32294.python-list@python.org> Message-ID: <1187698999.545439.322600@k79g2000hse.googlegroups.com> On Aug 21, 12:00 pm, Joel Andres Granados <joel.grana... at gmail.com> wrote: > Hello list: > > I have tried various times to use an IDE for python put have always been > disapointed. I have also tried a lot of them (IDEs) in the last year. I was finally happy with Eclipse/Pydev but i was always wanted a more "true" IDE for Python. I think i found it in Eric4 http://www.die-offenbachs.de/eric/index.html You can download from here http://www.riverbankcomputing.co.uk/pyqt/download.php (binary installer for Windows that contains Eric and PyQt) and have a look at it! From sjmachin at lexicon.net Mon Aug 27 18:06:33 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 27 Aug 2007 15:06:33 -0700 Subject: my parser.py isn't imported In-Reply-To: <fau5l8$o0i$1@lust.ihug.co.nz> References: <874pimqpei.fsf@wilson.homeunix.com> <1188166462.066732.123620@i13g2000prf.googlegroups.com> <87ps19q5fs.fsf@wilson.homeunix.com> <fau5l8$o0i$1@lust.ihug.co.nz> Message-ID: <1188252393.684357.77710@q3g2000prf.googlegroups.com> On Aug 27, 7:33 pm, Lawrence D'Oliveiro <l... at geek- central.gen.new_zealand> wrote: > In message <87ps19q5fs.... at wilson.homeunix.com>, Torsten Bronger wrote: > > > So I'd like to know a means to tell *explicitly* what I want to > > import. Maybe I could use the imp module but that's ugly. > > That seems to be the standard Python-provided way to explicitly import the > file you want from the place you want. > > > I mean, there are hundreds of modules on my harddisk, so trying to avoid > > nameclashs should not be the solution... > > That is what namespace qualifiers are for, e.g. > > import my_custom_stuff.parser > > versus > > import parser > > > John Machin writes: > > >> 2. Failure to RTFabulousM: > >> """ > >> Details of the module searching and loading process are > >> implementation and platform specific. It generally involves > >> searching for a ``built- in'' module with the given name and then > >> searching a list of locations given as sys.path. > >> """ > > > ... the whole systems seems largely arbitrary, which I don't > > believe. ;-) > > The documentation <http://docs.python.org/lib/module-sys.html> says quite > clearly that the search order is controlled by sys.path. So why not > manipulate that to get the effect you want? Short answer: it doesn't work. The documentation that I quoted previously says that if a module is is built in, it will be selected, *before* sys.path is examined. The OP's original message stated quite clearly that the directory containing his own parser.py is at the front of sys.path. > > > "parser" is built-in on Windows but not on Linux. > > It is standard on all platforms > <http://docs.python.org/lib/module-parser.html>. "standard" != "builtin" From jehugaleahsa at gmail.com Sun Aug 5 12:43:24 2007 From: jehugaleahsa at gmail.com (jehugaleahsa at gmail.com) Date: Sun, 05 Aug 2007 16:43:24 -0000 Subject: the one python book In-Reply-To: <mailman.1611.1186233912.22759.python-list@python.org> References: <mailman.1611.1186233912.22759.python-list@python.org> Message-ID: <1186332204.704307.143440@i13g2000prf.googlegroups.com> On Aug 4, 7:23 am, "dhr" <dima.hris... at gmail.com> wrote: > newbie question: > > Is there a 'K&R" type of Python book? The book that you'd better have on > your shelf if you are going into Python? Personally, I have two paths for you to take. If you are a programmer already, then I would recommend that you buy Python in a Nutshell. It is actually a very concise book for people who just want to know what the language provides. I would actually recommend stopping once you get to the library reference and I would make sure look into classes. After you done with that day-long read, I would get your hands on the newest version of "Progamming Python" (O'Reilly). It has a lot of practical applications for Python and it is *not* a one-day read. It is enormous and it skips around a lot. I like it because it is doesn't necessarily stick to one topic so you pick up a lot of tricks along the way. It gets you started off learning some sweet c-style OS functions. If you don't know just about everything about Python by the end of that book, I would be very surprised. BTW, almost all of the Nutshell books have been fabulous. They kind of put it out there for you to suck up like a vacuum. The only failure in my opinion is the PHP nutshell . . . Since you even know hwo K&R (good job) is, then I assume you know how to program and are ready to skip all the crap. Best of luck, Travis From steve at holdenweb.com Sun Aug 5 10:22:23 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 05 Aug 2007 10:22:23 -0400 Subject: Comparing RFC1123 based Dates In-Reply-To: <1186281836.970400.103490@i13g2000prf.googlegroups.com> References: <1186281836.970400.103490@i13g2000prf.googlegroups.com> Message-ID: <f94mev$dol$1@sea.gmane.org> Phoe6 wrote: > I would like to parse RFC 1123 date format and compare two dates. I > find that > datetime module does not specifically confirms to any RFC. Any > suggestions as how I can handle the RFC 1123 date format using > standard libraries before I go to re based parsing? > I realise you want to stick to the standard library. If you decide you can't however, you should definitely take a look at mx.DateTime, as the mx.DateTime.ARPA submodule provides exactly what you require. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From van.lindberg at gmail.com Sat Aug 4 15:45:12 2007 From: van.lindberg at gmail.com (Van Lindberg) Date: Sat, 04 Aug 2007 14:45:12 -0500 Subject: Trying to find zip codes/rest example In-Reply-To: <46B4117B.8090002@jayloden.com> References: <f8vhct$3g6$1@sea.gmane.org> <46B4117B.8090002@jayloden.com> Message-ID: <46B4D748.6060102@gmail.com> Jay Loden wrote: > I don't remember the demo, but a little creative googling turned up > > http://bitworking.org/news/132/REST-Tips-URI-space-is-infinite > > Which matches the description above perfectly, so I assume it's what you were after :-) That is exactly what I was trying to find! I bow down before your superior google-fu. Thanks, VanL From soundplay at gmail.com Sat Aug 18 06:54:35 2007 From: soundplay at gmail.com (SHY) Date: Sat, 18 Aug 2007 12:54:35 +0200 Subject: passing arguments with ampersands Message-ID: <f6be0af40708180354u719f5c71p2be27e0ee8317f9b@mail.gmail.com> hey, i have a win32 gui application that accepts filenames as arguments (either via command line or via associating an extension to the application) which are then opened in it. the problem is that as soon as the filename contains characters like '&', the process fails at the very beginning (sys.argv). for example when the full path of the file im trying to open like this is Quote:D:\ftp\Music\Mixes & Compilations\Above & Beyond - Essential Mix\001_Essential_Mix_2004-06-06_-_Above_and_Beyond.txt when i put 'print sys.argv[1:]' at the very beginning of the script, all i get is this: Quote:['D:\\ftp\\Music\\Mixes'] i already have a piece of code that puts together paths with spaces sent via arguments, but this '&' drives me crazy. other than that, after i close the application (which actually starts without any errors), the commands line gets filled with a message like this: Quote:The system cannot find the path specified. 'Beyond' is not recognized as an internal or external command, operable program or batch file. any idea how to solve this? [image: Sad] thanks in advance! -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070818/a9827fa8/attachment.html> From max at alcyone.com Sun Aug 19 20:42:34 2007 From: max at alcyone.com (Erik Max Francis) Date: Sun, 19 Aug 2007 17:42:34 -0700 Subject: Python question (PyNoob) In-Reply-To: <3uOdnbA4Bc27fFXbnZ2dnUVZ8vidnZ2d@bt.com> References: <3uOdnbA4Bc27fFXbnZ2dnUVZ8vidnZ2d@bt.com> Message-ID: <k_Gdne2qrIfmflXbnZ2dnUVZ_qninZ2d@speakeasy.net> Anonymous wrote: > I have exp with C/C++ (and a few other langs). I want to use Python to > start doing the ff: > > 1). Data Munging (text processing) - instead of Perl > 2). Automating my build process > 3). (Possibly) some web data retrieval jobs > > Can anyone point me to resurces/possibly scripts that can get me up to > speed (to do these 3 things) ASAP, without having to learn the basics of > programming? That isn't possible without saying what it is that you actually want done. Besides, the point of specifically choosing Python here for such tasks would be your ability to manipulate them and write your own. If tools already exist that do what you need, which languages they were written in would be completely irrelevant. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis Never had very much to say / Laugh last, laugh longest -- Des'ree From uymqlp502 at sneakemail.com Fri Aug 31 01:38:49 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Thu, 30 Aug 2007 22:38:49 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <7xr6lk5m1o.fsf@ruckus.brouhaha.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> <m2wsvc1g12.fsf@manolo-blahnik.bibliotech.com> <7xr6lk5m1o.fsf@ruckus.brouhaha.com> Message-ID: <1188538729.605740.41440@q5g2000prf.googlegroups.com> > I guess one difference from unit test philosophy is > that at least > sometime, you'd run the entire application with all > the dbc checks > enabled, and just live with the slowdown. Yes, that's right. You don't expect to run efficiently with the self- test checks activated, but you can test your code more conveniently and comprehensively than unit tests by simply running your program as usual -- except with the checks activated. If you do that for any significant period of time, many bugs will find themselves, I'm sure. Also, to repeat once again, the embedded self-test (DbC) checks can be used for unit testing too. You simply activate the self-tests when you do your unit testing, and wait for them to throw exceptions. So it seems to me that you've killed two birds with one stone. From david at asdf.asdf Fri Aug 24 01:20:04 2007 From: david at asdf.asdf (bambam) Date: Fri, 24 Aug 2007 15:20:04 +1000 Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com><1187898049.734696.9500@l22g2000prc.googlegroups.com><13csi2tn49esmc3@corp.supernews.com> <mailman.230.1187928865.32294.python-list@python.org> Message-ID: <13csqk47j0c56b0@corp.supernews.com> Excellent. By symmetry, I see that "list" casts the set back into a list. I wonder why list has not been extended with the same (difference, interesection) methods? Casting to set looks a little kludgy: c = list(set(a)-set(b)) I wonder if that is clearer than the explicit loop? Steve. "Gabriel Genellina" <gagsl-py2 at yahoo.com.ar> wrote in message news:mailman.230.1187928865.32294.python-list at python.org... > En Thu, 23 Aug 2007 23:54:14 -0300, bambam <david at asdf.asdf> escribi?: > >> After examining your suggestion, I realised that another thing >> I am interested in could be generalised: I want the complement >> of the set of ports in pages, given a universal set in tempList. >> Ignoring the break condition for the moment, and my problem >> with int(port)/str(port), would you have offered a different solution >> if I had asked for the relative complement of a small set? >> >> a= ['a','b','c'] >> b= ['b'] >> c= a-b #set theoretic difference, a\b, a.~b, ['a','c'] > > If you want a set - just use a set: > > py> a = set(['a','b','c']) > py> b = set(['b']) > py> c = a-b > py> c > set(['a', 'c']) > > -- > Gabriel Genellina > From __peter__ at web.de Fri Aug 24 01:47:15 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 24 Aug 2007 07:47:15 +0200 Subject: unifying many packages under one name References: <mailman.231.1187929096.32294.python-list@python.org> Message-ID: <falrd3$ahe$03$2@news.t-online.com> Eric S. Johansson wrote: > I have a collection of packages and I want to put them under single > unifying > name. my goal is to reduce namespace pollution and make all these > packages accessible as 'import vvv.aaa'. In more detail, if I have > packages 'aaa' and 'bbb', what do I do to put those packages under > unifying name such as 'vvv'? the only way I can see to do it is to create > 'vvv' as a directory with its own __init__.py but I'm not sure that were > work right either. Of course you could make a module vvv.py with lots of import statements import aaa import bbb ... import zzz but then all submodules are imported eagerly with import vvv And then there's the hack import sys class Importer(object): def __getattr__(self, name): module = __import__(name) # you can do anything here setattr(self, name, module) return module sys.modules["vvv"] = Importer() Peter From bdesth.quelquechose at free.quelquepart.fr Wed Aug 1 14:06:54 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 01 Aug 2007 20:06:54 +0200 Subject: Where do they tech Python officialy ? In-Reply-To: <mailman.1423.1185957645.22759.python-list@python.org> References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> <1185265091.276958.239910@r34g2000hsd.googlegroups.com> <1i23wyk.avc945i4dwsiN%aleax@mac.com> <mailman.1423.1185957645.22759.python-list@python.org> Message-ID: <46b0cbf1$0$5279$426a74cc@news.free.fr> Alex Popescu a ?crit : > aleax at mac.com (Alex Martelli) wrote in news:1i23wyk.avc945i4dwsiN% > aleax at mac.com: > > >>NicolasG <nicolasg at gmail.com> wrote: >> ... >> >>>The problem is that I would like to work as a Python programmer but >>>all the job vacancies I can find requires a couple of years of >>>professional experience ... that I don't have. How a wanna be >>>programmer can start working as a programmer if there is no chance to >>>start from somewhere ? That's the reason I created this topic. >> >>Open source projects do not require previous professional experience > > to > >>accept volunteers. So, one way out of your dilemma is to make a name >>for yourself as an open source contributor -- help out with Python >>itself and/or with any of the many open source projects that use >> Python, >>and you will both learn a lot _and_ acquire "professional experience" >>that any enlightened employer will recognize as such. > > > It depends :-). In my experience I met employers being concerned by my > implication in the oss world :-). > These are the ones you don't wan't to work for anyway !-) From half.italian at gmail.com Thu Aug 9 21:38:37 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Fri, 10 Aug 2007 01:38:37 -0000 Subject: Threaded Design Question In-Reply-To: <1186686575.192491.82820@e16g2000pri.googlegroups.com> References: <1186683909.797328.68770@i13g2000prf.googlegroups.com> <1186686575.192491.82820@e16g2000pri.googlegroups.com> Message-ID: <1186709917.157105.310050@g12g2000prg.googlegroups.com> On Aug 9, 12:09 pm, "Justin T." <jmtull... at gmail.com> wrote: > On Aug 9, 11:25 am, half.ital... at gmail.com wrote: > > > Here's how I have it designed so far. The main thread starts a > > Watch(threading.Thread) class that loops and searches a directory for > > files. It has been passed a Queue.Queue() object (watch_queue), and > > as it finds new files in the watch folder, it adds the file name to > > the queue. > > > The main thread then grabs an item off the watch_queue, and kicks off > > processing on that file using another class Worker(threading.thread). > > Sounds good. > > > > > I made definite progress by creating two queues...watch_queue and > > processing_queue, and then used lists within the classes to store the > > state of which files are processing/watched. > > This sounds ugly, synchronization is one of those evils of > multithreaded programming that should be avoided if possible. I see a > couple of dirt simple solutions: > > 1. Have the watch thread move the file into a "Processing" folder that > it doesn't scan > 2. Have the watch thread copy the file into a python tempfile object > and push that onto the queue, then delete the real file. This can be > done efficiently (well, more efficiently than new.write(old.read()) > with shutil.copyfileobj(old, new) > > Both those take very few lines of code, don't require synchronization, > and don't require extending standard classes. Thanks foor the ideas Justin. I started subclassing/extending the Queue.Queue object with two additional classes. One to return the first item in the list without removing it from the queue, and one to return all items of the list without removing them. I think this will take me to where I want to go. If it doesn't work, I might just use your processing folder approach. That sounds the easiest, although I'm still interested in any idioms or other proven approaches for this sort of thing. ~Sean From ashwin.murali at gmail.com Wed Aug 1 05:03:59 2007 From: ashwin.murali at gmail.com (The Cruisemaniac) Date: Wed, 01 Aug 2007 09:03:59 -0000 Subject: Problem with subprocess.Popen() Message-ID: <1185959039.674882.210540@q75g2000hsh.googlegroups.com> Hi all, I'm trying to run a windows batch file from a python script using subprocess.popen(). The issue that I'm facing is that, if i give the batch file as parameter to the popen function, the script runs, but if i provide a parameter, it is not working. Can someone help me with the command. The actual windows command to be executed is: test.bat -t ABC_DE_FG_HI_001 "C:\ABCDEFGHIJKLMNOP.TXT" What is the actual parameter required for subprocess.Popen(parameter chain) in this case?? Kindly help me out... Regards and Thanks in advance... Ashwin Murali. From ptmcg at austin.rr.com Thu Aug 16 10:51:47 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 16 Aug 2007 07:51:47 -0700 Subject: Problem using Optional pyparsing In-Reply-To: <mailman.2045.1187248183.22759.python-list@python.org> References: <mailman.2045.1187248183.22759.python-list@python.org> Message-ID: <1187275907.006826.310350@50g2000hsm.googlegroups.com> On Aug 16, 2:09 am, "Nathan Harmston" <ratchetg... at googlemail.com> wrote: > Hi, > > I know this isnt the pyparsing list, but it doesnt seem like there is > one. I m trying to use pyparsing to parse a file however I cant get > the Optional keyword to work. <snip> Thanks, Peter, your comments are dead-on. Pyparsing-related posts crop up here every so often, usually with me as the culprit. But to address your question, I've added a "Getting Help" page to the pyparsing wiki, with links to the various mailing lists and support pages on SourceForge. Fortunately, I don't think this group minds an occasional trip down Pyparsing Lane (there've been no serious complaints so far). Some other suggestions/comments on your parser: - Good use of results names. For debugging, you can print out the parse results by using the dump() method - this gives you this kind of output: [1020, 'YS2-10a02.q1k', 'chr09', 1295, 42, 141045, 142297, 'C', 1254, 95.060000000000002, 1295, 'reject_bad_break', '0'] - dest_id: chr09 - dest_start: 141045 - dest_stop: 142297 - length: 1254 - percent_id: 95.06 - result: reject_bad_break - row_1: 1020 - row_11: [1295] - row_13: ['0'] - row_8: C - src_id: YS2-10a02.q1k - src_start: 1295 - src_stop: 42 This may give you some ideas on some more meaningful names ('row_8' looks like an obvious candidate for replacement, for instance). - If you are using pyparsing 1.4.7, you can abbreviate your calls to setResultsName to just ("name"), that is, this: src_id = identifier.setResultsName("src_id") can be written as just: src_id = identifier("src_id") - Don't use the name 'float' for the expression for a real number, since this masks the builtin Python type float, and more importantly, the builtin Python conversion function float (which you will want to use in the parse action for this expression). Perhaps a name like 'real' or 'realNumber' would do. - There is no need for the trailing space in defining Literal("ALIGNMENT"). - It is simpler to attach the parse actions to integer and real themselves, rather than on each line where they are used. If you end up with some integer field that you don't want converted, you can define it in situ, like this: zipCode = Word(nums) # don't use integer for this, don't want it converted or define a intString expression that does not do the conversion. - With these changes, your grammar section becomes a little more readable: make_int = lambda t: int(t[0]) make_float = lambda t: float(t[0]) integer = Word( nums ).setParseAction(make_int) real = Word( nums+".").setParseAction(make_float) identifier = Word( alphanums+"-_." ) alignment = Literal("ALIGNMENT").suppress() row_1 = integer("row_1") src_id = identifier("src_id") dest_id = identifier("dest_id") src_start = integer("src_start") src_stop = integer("src_stop") dest_start = integer("dest_start") dest_stop = integer("dest_stop") row_8 = oneOf("F C")("row_8") length = integer("length") percent_id = real("percent_id") row_11 = (integer + Optional(Literal("|") + delimitedList(Word(nums))("subItems")) )("row_11") result = Word(alphas+"_")("result") row_13 = commaSeparatedList("row_13") (although all the ()'s make row_11 a little tough to follow - this might deserve getting broken up into several lines.) And yes, I know that PEP8 says not to align '=' signs on successive assignment statments, but I truly believe it does help readability at times. -- Paul From f.guerrieri at gmail.com Tue Aug 28 06:04:40 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Tue, 28 Aug 2007 12:04:40 +0200 Subject: XML File -- dictionary edit/search In-Reply-To: <1188276957.123003.250410@q5g2000prf.googlegroups.com> References: <1188263724.306539.181980@y42g2000hsy.googlegroups.com> <1188276957.123003.250410@q5g2000prf.googlegroups.com> Message-ID: <79b79e730708280304h246914f7k6abd647cd7713024@mail.gmail.com> On 8/28/07, Nagarajan <naga86 at gmail.com> wrote: > A simple yaml file might just do the trick. > Your yaml file shall look like the following: > > Word-def.yaml > word1: word1's definition > word2: word2's definition > .. > .. > .. > Use pyyaml to handle yaml files. > -------- > import yaml > worddefs = yaml.load( open( "word-def.yaml", "r" ).read() ) > print worddefs > -------- I agree with the suggestion for yaml! Since definitions are to be inputed by the users, it could be better to use yaml.safe_load() to reduce the risks... francesco From gagsl-py2 at yahoo.com.ar Sun Aug 12 14:17:28 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 12 Aug 2007 15:17:28 -0300 Subject: Formatting Results so that They Can be Nicely Imported into a Spreadsheet. References: <1186270555.514649.311280@d30g2000prg.googlegroups.com> <1186278638.931477.39760@z24g2000prh.googlegroups.com> <Avati.40$Tu1.6@newsfe12.lga> <1186284359.668342.5880@d30g2000prg.googlegroups.com> <1186304814.129279.207100@j4g2000prf.googlegroups.com> Message-ID: <op.twk2n1q6x6zn5v@furufufa-ec0e13.cpe.telecentro.com.ar> En Sun, 05 Aug 2007 06:06:54 -0300, SMERSH009 <SMERSH009X at gmail.com> escribi?: > The only question that remains for me--and this is just for my > knowledge-- what does the "if i" mean in this code snippet? > f = [i.split() for i in d if i] > How is it helpful to leave a dangling "if i"? Why not just f = > [i.split() for i in d]? `if i` means `if i is considered true`. In this case we are talking about strings: "" is false and all other strings are true. So this is a way to say `if i is not the empty string`, effectively filtering out empty lines. Perhaps using more meaningful names for variables makes the code more clear: exploded_lines = [line.split() for line in lines if line] -- Gabriel Genellina From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Aug 2 04:32:41 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 02 Aug 2007 10:32:41 +0200 Subject: Awkward format string In-Reply-To: <1185984697.605529.157110@g12g2000prg.googlegroups.com> References: <1185984697.605529.157110@g12g2000prg.googlegroups.com> Message-ID: <46b196aa$0$18885$426a74cc@news.free.fr> beginner a ?crit : > Hi, > > In order to print out the contents of a list, sometimes I have to use > very awkward constructions. For example, I have to convert the > datetime.datetime type to string first, construct a new list, s/list/tuple/ > and then > send it to print. The following is an example. > > x=(e[0].strftime("%Y-%m-%d"), e[1].strftime("%Y-%m-%d"))+e[2:] > print >>f, "%s\t%s\t%d\t%f\t%f\t%f\t%d" % x > > e is a tuple. x is my new tuple. > > Does anyone know better ways of handling this? >>> from datetime import datetime >>> dt = datetime(2007,8,2) >>> dt datetime.datetime(2007, 8, 2, 0, 0) >>> str(dt) '2007-08-02 00:00:00' >>> "%s" % dt '2007-08-02 00:00:00' >>> dt.date() datetime.date(2007, 8, 2) >>> str(dt.date()) '2007-08-02' Do you really need datetime objects ? If not, using date objects instead would JustWork(tm) - at least until someone ask you to use another date format !-) Else, and since you seem to have a taste for functional programming: from datetime import datetime from functools import partial def iformat(e): fake = lambda obj, dummy: obj for item in e: yield getattr(item, 'strftime', partial(fake, item))('%Y-%m-%d') e = (datetime(2007,8,1),datetime(2007,8,2) ,42, 0.1, 0.2, 0.3, 1138) print tuple(iformat(e)) print "%s\t%s\t%d\t%f\t%f\t%f\t%d" % tuple(iformat(e)) From fake at email.org Sat Aug 4 09:56:26 2007 From: fake at email.org (MASI) Date: Sat, 4 Aug 2007 15:56:26 +0200 Subject: [DISLIN] Polar Grid Message-ID: <1lutleeq7w0r6.1ovbcr7dzd5p1$.dlg@40tude.net> Hi, in a polar graph if I define the position of the first label TOP or BOTTOM,the grid doesn't show. Is this a bug? e.g. dislin.polmod('top', 'clockwise') dislin.polar (1.,0., 0.2, 0., 30.) dislin.grdpol(3,16) From vasudevram at gmail.com Tue Aug 7 10:07:48 2007 From: vasudevram at gmail.com (vasudevram) Date: Tue, 07 Aug 2007 14:07:48 -0000 Subject: Web based Reporting tool for Python In-Reply-To: <1186460956.945148.162610@k79g2000hse.googlegroups.com> References: <1186460956.945148.162610@k79g2000hse.googlegroups.com> Message-ID: <1186495668.390714.250780@e16g2000pri.googlegroups.com> Madhu Alagu wrote: > Hi > > > > I am looking template based report tools for python.It has the ability > to deliver rich content onto the screen, to the printer or into PDF, > HTML, XLS, CSV and XML files. > > > > > > Thanks, > > Madhu Alagu I don't know if there's a _single_ tool that can do all you want (there may be, just that I don't know of one), but there are many tools that can each do some part of it. Here are some, off the top of my head - Googling should get you more for each category. For templating - Cheetah, others. For PDF - ReportLab. PDFLib has Python bindings too, but its paid for commercial use, IIRC. For HTML - Python standard library itself has some stuff, there must be others. For XLS/CSV - CSV output is easy enough to "roll your own". Then import the CSV into Excel. If this isn't good enough (and it may not be, depending on your needs, as it requires manual (ok, it is possible to sort of automate that too using COM) import of the CSV into Excel. Google for a Python lib for direct XLS generation. For XML - like CSV, for simple XML, can be written by you (its just outputting XML tags, attributes and content from your code). There might be issues with encodings, etc. - in which case use a lib. Python has many XML libs - do some research. David Mertz and Uche Ogbuji, among others, have written a lot of articles on Python and XML, many of them are about reviewing and comparing various libs like ElementTree, Gnosis XML utilities and others. Many of those and other articles are on IBM developerWorks and XML.com. Vasudev Ram http://www.dancingbison.com http://jugad.livejournal.com http://sourceforge.net/projects/xtopdf From Brian.McCann at viziant.net Mon Aug 20 17:05:49 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Mon, 20 Aug 2007 17:05:49 -0400 Subject: reading a line in file References: <93066C069973ED448DC2BCEA9C44A7383BE2B2@efmailx><2dc0c81b0708201029k5909d919vcf0deebae74a79c7@mail.gmail.com><93066C069973ED448DC2BCEA9C44A7383BE2B4@efmailx><2dc0c81b0708201207p7f83f2e0l6de15fd70be252a5@mail.gmail.com><93066C069973ED448DC2BCEA9C44A7383BE2B6@efmailx><46C9F561.50405@jayloden.com><2dc0c81b0708201314q727ca3a1s12bef74a25b20abc@mail.gmail.com><46C9F88A.9090400@jayloden.com> <2dc0c81b0708201335m1a158176o9ea456778d2a8597@mail.gmail.com> Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE2B7@efmailx> Hi Shawn, what if I had a file com.properties with the below line in it If I needed to capture the value of everything separeted by a ":" and asign each to a variable would regex be the right method to grab those? like a=jdbc b=oracle c=@127.0.0.1 d=1521 e:XE --Brian com.db.connstr=jdbc:oracle:thin:@127.0.0.1:1521:XE ________________________________ From: python-list-bounces+brian.mccann=viziant.net at python.org on behalf of Shawn Milochik Sent: Mon 8/20/2007 4:35 PM To: python-list at python.org Subject: Re: reading a line in file Although you're technically correct, I think there's a knee-jerk anti-regex reaction, citing the meaningless overhead. If you're running many thousands of records or something then it becomes a small issue compared to a replace statement or something. But in most cases it makes no difference at all. Run the example script both ways and I'm sure there will be no difference, and I prefer a clear regex to a convoluted (in my opinion) substring call. In any case, it's a preference, and I have never seen anything which convinced me that one should avoid regexes at all costs unless there's no other way to do it. And the comment about solving a problem by using regular expressions creating another problem is just asinine. Like so many other things, it's often repeated without any thought about whether it is true in general, much less in the situation in question. -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070820/198c8c11/attachment.html> From soundplay at gmail.com Mon Aug 27 12:38:08 2007 From: soundplay at gmail.com (SHY) Date: Mon, 27 Aug 2007 18:38:08 +0200 Subject: weird edgecolumn behavior in scintilla Message-ID: <f6be0af40708270938q5ecb3a6ka6185425b2103040@mail.gmail.com> hey everyone, i decided its time to heavily improve myself in python-gui programming and so i started building my own editor/ide for PHP. so far, most of the general/basic features are inspired (read: mostly copy-pasted) by eric4 IDE build upon qt4/scintilla combination. but i came across to a weird problem with the scintilla's edgemodes. when i set it up to edgeline mode and the edgecolumn is set to 80, the edgeline is drawn (assuming the default scintilla settings) at approximately 50th character from the left (and 30th character when the lexer is off - aka txt files), instead of the expected 80. ive tried to play around with the lexers' styles to change fonts (courier new, size 10) and stuff but it keeps drawing the line on 50th column. ive made a non-elegant and non-pragmatic workaround to this, by setting the edgecolumn to 128 when the lexer is turned on and 213 when it is off. both values approximately match the 80th column for courier-new size 10. i originally thought that the column length for the edgecolumn value is computed from the character width of the particular font, and so that by changing the font or its size, the edgecolumn would change appropriately. dunno if this is the problem of scintilla (cause the exactly same thing is present in eric4 as well) or i just missed some important setting. this is the code that handles the edgecolumn stuff when the editor is launched: [code] edgeMode = Preferences.getEditor("EdgeMode") edge = QsciScintilla.EdgeMode(edgeMode) self.setEdgeMode(edge) if edgeMode: self.setEdgeColumn(Preferences.getEditor("EdgeColumn")) self.setEdgeColor(Preferences.getEditorColour("Edge")) [/code] the EdgeColumn preferences value defaults to 80. any ideas? thanks in advance. SHY -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070827/19106239/attachment.html> From greg at cosc.canterbury.ac.nz Wed Aug 8 07:53:28 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 08 Aug 2007 23:53:28 +1200 Subject: Issues of state In-Reply-To: <7x8x8mpn37.fsf@ruckus.brouhaha.com> References: <op.tv98rva4wepdt4@ericb.pragmadev> <mailman.1680.1186416061.22759.python-list@python.org> <7x3aywr4tc.fsf@ruckus.brouhaha.com> <mailman.1684.1186422197.22759.python-list@python.org> <gg9mo4-p2m.ln1@lairds.us> <7x8x8mpn37.fsf@ruckus.brouhaha.com> Message-ID: <5htpcrF3lqmrnU1@mid.individual.net> Paul Rubin wrote: > I'm not sure what you're getting at in this context. You can write a > desktop app where the window system communicates with a gui toolkit > through a socket (at least that's how X windows works) An X server connection is *much* more stateful than an HTTP one. It persists throughout the entire use session of the application, for one thing, and there is heaps of state being kept on both sides of the connection. There's also a very high communication bandwidth between them. There's really no comparison. -- Greg From kyosohma at gmail.com Thu Aug 2 14:14:30 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 02 Aug 2007 18:14:30 -0000 Subject: problems playing with dates from any month. In-Reply-To: <mailman.1522.1186075887.22759.python-list@python.org> References: <mailman.1522.1186075887.22759.python-list@python.org> Message-ID: <1186078470.764903.99590@z24g2000prh.googlegroups.com> On Aug 2, 12:31 pm, "krishnakant Mane" <researchb... at gmail.com> wrote: > hello, > I have a very strange problem and I can't find any solution for that. > I am working on an accounting package which I wish to develop in python. > the simple problem is that I want to knoe how I can know if the given > date is the nth day of a month. > for example if a customer is supposed to pay his installment on every > 5th of all months, > I want to know if today is the fifth day (jan the fifth, feb the fifth > etc) for any given month. > I have not found any such function. > if I have looked (or over looked ) in the wrong places I am really sorry. > secondly I also want to know the way in which I can convert a given > string to a date object. > for example if I have a string "29/09/2005", I know it is a valid date > although it is in a string form. > now I want to convert the above string into a real date object. > how can I cast it this way? > regards, > Krishnakant. You should also check this place out: http://labix.org/python-dateutil Lots of cool date manipulation using the dateutil module. Mike From codey45 at yahoo.com Mon Aug 13 10:50:41 2007 From: codey45 at yahoo.com (codey45) Date: Mon, 13 Aug 2007 07:50:41 -0700 Subject: Car Air Conditioners In-Reply-To: <1186993120.706804.185590@b79g2000hse.googlegroups.com> References: <1186993120.706804.185590@b79g2000hse.googlegroups.com> Message-ID: <1187016641.379882.227860@q3g2000prf.googlegroups.com> On Aug 13, 1:18 am, Lepi Duja <digitalplusm... at gmail.com> wrote: > All the informations about car air conditioners can be found on this > website... > > http://car-air-conditioning.blogspot.com/ From kalin at el.net Sun Aug 12 16:56:45 2007 From: kalin at el.net (kalin mintchev) Date: Sun, 12 Aug 2007 16:56:45 -0400 (EDT) Subject: cgi and headers Message-ID: <49261.74.2.36.140.1186952205.squirrel@mail.el.net> hi there... i'm starting to work with python cgi scripts using ajax. one problem i have is that the cgi module doesn;t do (apparently) anything without the -- print "Content-type: text/html\n" -- line in the script. the issue is that the output of the script has to be an xml file and not an html. it's not really a problem for any normal browser but the retarded explorer thing doesn;t process the xml unless it gets back the xml header. so my scripts work fine on mozilla but not in explorer because of the missing xml header. what would be the correct solution for this? thanks.... From winkatl1213 at yahoo.com Thu Aug 2 11:54:04 2007 From: winkatl1213 at yahoo.com (winkatl1213 at yahoo.com) Date: Thu, 02 Aug 2007 08:54:04 -0700 Subject: Cross compiling 2.5.1 Message-ID: <1186070044.980325.159520@i38g2000prf.googlegroups.com> I was wondering if anyone could help me with cross-compiling Python 2.5.1 to a MIPS target. The approach I'm using is based off the suggestion in the README file that comes with the python source distribution. I managed to get the configure script to run using the following command line: $ ../Python-2.5.1/configure --host=mips-linux --enable-shared Next I run make and it builds the python interpreter and shared library. However, it then attempts to run the interpreter to complete the rest of the build process, and that of coarse fails. I read several posts on the internet from people who applied patches to the python source to enable cross-compling, but my impression was that 2.5.1 had merged some of this work. Can anyone give me some suggestions on how I get the makery to use the build interpreter instead of the host interpreter to complete the build process? Thanks in advance for any suggestions. Jeff From geoff.bache at pobox.com Mon Aug 27 16:21:16 2007 From: geoff.bache at pobox.com (geoffbache) Date: Mon, 27 Aug 2007 13:21:16 -0700 Subject: Getting subprocesses to be hidden on Windows Message-ID: <1188246076.131276.292010@r34g2000hsd.googlegroups.com> Hi, As part of my efforts to write a test tool that copes with GUIs nicely, I'm trying to establish how I can start a GUI process on Windows that will not bring up the window. So I try to hide the window as follows: info = subprocess.STARTUPINFO() info.dwFlags |= subprocess.STARTF_USESHOWWINDOW info.wShowWindow = subprocess.SW_HIDE proc = subprocess.Popen(..., startupinfo=info) This works, in a way, but doesn't work recursively. I.e. if the started process itself starts a window, that second window will not be hidden. This even applies to dialog boxes within the application. So instead of a lot of windows popping up I now get a lot of disembodied dialogs appearing, which is a slight improvement but not much. Also, certain processes (e.g. tkdiff) seem to ignore the directive to be hidden altogether. This is dead easy on UNIX with virtual displays like Xvfb. Can someone shed any light if it's possible on Windows from python? Regards, Geoff Bache From michele.simionato at gmail.com Wed Aug 1 01:44:21 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 01 Aug 2007 05:44:21 -0000 Subject: Python end of file marker similar to perl's __END__ In-Reply-To: <1185940391.135261.130950@i38g2000prf.googlegroups.com> References: <1185940391.135261.130950@i38g2000prf.googlegroups.com> Message-ID: <1185947061.985093.306840@22g2000hsm.googlegroups.com> On Aug 1, 5:53 am, beginner <zyzhu2... at gmail.com> wrote: > Hi All, > > This is just a very simple question about a python trick. > > In perl, I can write __END__ in a file and the perl interpreter will > ignore everything below that line. This is very handy when testing my > program. Does python have something similar? > > Thanks, > Geoffrey I wished from something like that. What you can do at the moment, is to comment or triple quote the code you don't want to run. Michele Simionato From gtaylor at CLEMSON.EDU Mon Aug 20 14:58:28 2007 From: gtaylor at CLEMSON.EDU (Greg Taylor) Date: Mon, 20 Aug 2007 14:58:28 -0400 Subject: CIE Colorspace Conversions Message-ID: <46C9E454.1070303@clemson.edu> Greetings, I'm not sure if this is the right place to probe for interest, but I figured I'd give it a shot. Recently, a project I undertook at work required us to convert between the various CIE color spaces (XYZ, Lab, LCH, Luv, etc.). I looked long and hard but didn't find any Python library that did this, I was able to find JavaScript and C-based implementations, but that's about it. For a good example of the kinds of conversions I am referring to, see: http://brucelindbloom.com/ColorCalculator.html This is likely only to interest those in the Graphic Communications industry (notably printers and anyone else having to deal with color science), but I'm curious to see if anyone out there in the Python community would have any use for a color conversion library. If I've missed an existing implementation, feel free to point it my way as well. I'd love to eventually be able to quickly convert between color spaces and perform comparisons like Delta E without having to worry about doing said conversions manually. I'm not too sure this excites anyone else, though! Greg Taylor Clemson University '08 Graphic Communications From godzillaismad at gmail.com Tue Aug 14 00:57:22 2007 From: godzillaismad at gmail.com (Godzilla) Date: Mon, 13 Aug 2007 21:57:22 -0700 Subject: Memory leak when creating lots of object Message-ID: <1187067442.084074.55010@z24g2000prh.googlegroups.com> Hello, I have a program that create and pop an object off a queue, but it is experiencing some memory leakage. I have been unable to detect where the memory leakage occur. The strange thing is when i replace the object creation with a plain integer/string, the leak goes away... Here's the code I used as my test: import Queue import threading import time q = Queue.Queue(0) class PDU: def __init__(self, name=''): self.name = name class qTest(threading.Thread): def __init__(self, name=''): threading.Thread.__init__(self) self.name = name self.threadContinue = True def run(self): count = 0 while self.threadContinue: pdu = q.get(True) del pdu count+=1 #print count if q.qsize() == 0: print "Total get in bulk", count count = 0 def stop(self): self.threadContinue = False q.put(1) if __name__ == "__main__": try: qt = qTest() qt.start() loopCount = 1000 while True: for i in range(loopCount): pdu = PDU() ## pdu = 1 q.put(pdu) time.sleep(5) except KeyboardInterrupt: print "Keyboard interrupted. Program exit." except Exception, why: print why if qt.isAlive(): qt.stop() I can see the memory usage increases slowly in Task Manager under XP, but do not know why. Anyone help? Thank you. From joshua at eeinternet.com Wed Aug 1 19:47:21 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 01 Aug 2007 15:47:21 -0800 Subject: Is shelve/dbm supposed to be this inefficient? Message-ID: <f8r62b$9lm$1@sea.gmane.org> I am using shelve to store some data since it is probably the best solution to my "data formats, number of columns, etc can change at any time" problem. However, I seem to be dealing with bloat. My original data is 33MB. When each row is converted to python lists, and inserted into a shelve DB, it balloons to 69MB. Now, there is some additional data in there namely a list of all the keys containing data (vs. the keys that contain version/file/config information), BUT if I copy all the data over to a dict and dump the dict to a file using cPickle, that file is only 49MB. I'm using pickle protocol 2 in both cases. Is this expected? Is there really that much overhead to using shelve and dbm files? Are there any similar solutions that are more space efficient? I'd use straight pickle.dump, but loading requires pulling the entire thing into memory, and I don't want to have to do that every time. [Note, for those that might suggest a standard DB. Yes, I'd like to use a regular DB, but I have a domain where the number of data points in a sample may change at any time, so a timestamp-keyed dict is arguably the best solution, thus my use of shelve.] Thanks for any pointers. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE From gnewsg at gmail.com Tue Aug 21 17:59:05 2007 From: gnewsg at gmail.com (billiejoex) Date: Tue, 21 Aug 2007 14:59:05 -0700 Subject: libgmail failure In-Reply-To: <1187730447.621592.93740@q4g2000prc.googlegroups.com> References: <1187730447.621592.93740@q4g2000prc.googlegroups.com> Message-ID: <1187733545.529286.78980@50g2000hsm.googlegroups.com> On 21 Ago, 23:07, "james.p.n... at gmail.com" <james.p.n... at gmail.com> wrote: > Hey all, > > I've been using libgmail to send out automated notification emails for > my company's nightly regression testing. Last night these emails > started failing, though the python code has not changed. I updated to > the latest libgmail, but that isn't helping. I've logged in to the > email account directly, and the account is still working fine. > > The error I get is "HTTP Error 400: Bad Request" when using > gmailAccount.login(). This doesn't throw an exception, just prints > the error. The code crashes outright when it tries to send mail. > > This code has been up and running for several months and just started > failing last night. Does anyone have an idea what's going on? > > The code and error follow (fairly short :-) > > Thanks much, > James > > Code: > ---------------------------------------------------------------------------?---------------------------- > def send(TO_LIST,SUBJECT,MESSAGE): > GA = libgmail.GmailAccount("xxx... at gmail.com","xxxxxxx") > try: > print "Logging in" > GA.login() > except libgmail.GmailLoginFailure: > print "\nLogin failed. (Wrong username/password?)" > else: > print "Log in successful.\n" > for RX in TO_LIST: > MSG = libgmail.GmailComposedMessage(RX,SUBJECT,MESSAGE) > if GA.sendMessage(MSG): > print "Message successfully sent to `%s` ." % RX > else: > print "Could not send message." > ---------------------------------------------------------------------------?---------------------------- > > Output: > ---------------------------------------------------------------------------?---------------------------- > Logging in > HTTP Error 400: Bad Request > Log in successful. > > No messages found > Traceback (most recent call last): > File "C:\projects\physware\testCases\PythonTestScripts > \SendEmail.py", line 58, in <module> > main() > File "C:\projects\physware\testCases\PythonTestScripts > \SendEmail.py", line 55, in main > send(TO_LIST,SUB,MSG) > File "C:\projects\physware\testCases\PythonTestScripts > \SendEmail.py", line 39, in send > if GA.sendMessage(MSG): > File "C:\projects\physware\testCases\PythonTestScripts\libgmail.py", > line 588, in sendMessage > U_ACTION_TOKEN: self._getActionToken(), > File "C:\projects\physware\testCases\PythonTestScripts\libgmail.py", > line 563, in _getActionToken > at = self._cookieJar._cookies[ACTION_TOKEN_COOKIE] > KeyError: 'GMAIL_AT' > ---------------------------------------------------------------------------?---------------------------- Don't know if it's for the same reason since I can't remember if the error was the same, but some times ago I had a similar problem. I used libgmail for copying a lot of mails from a google mail box to another and I've been "black-listed" after a while for flooding. After that I wasn't neither able to access my account from browser for a certain amount of time (one or two days). Try to do same operation 'manually' (by using a browser try to log-in by using your account, then send a mail) and see if you're able to do so. From naga86 at gmail.com Thu Aug 23 02:47:40 2007 From: naga86 at gmail.com (Nagarajan) Date: Thu, 23 Aug 2007 06:47:40 -0000 Subject: Raw strings to normal strings conversion? Message-ID: <1187851660.209024.59860@l22g2000prc.googlegroups.com> Is there a way by which I could obtain normal string form of a raw string. XML CDATA is returned as raw string. But I need the string to actually escape special chars. Any idea? From eggie5 at gmail.com Thu Aug 9 20:02:41 2007 From: eggie5 at gmail.com (eggie5) Date: Fri, 10 Aug 2007 00:02:41 -0000 Subject: beginner whitespace question In-Reply-To: <1186703525.591462.122140@m37g2000prh.googlegroups.com> References: <1186703261.136506.208660@x35g2000prf.googlegroups.com> <1186703525.591462.122140@m37g2000prh.googlegroups.com> Message-ID: <1186704161.334597.218750@z24g2000prh.googlegroups.com> On Aug 9, 4:52 pm, Dan Bishop <danb... at yahoo.com> wrote: > On Aug 9, 6:47 pm, eggie5 <egg... at gmail.com> wrote: > > > I keep getting an error for line 7, what's wrong with this? > > > from django.db import models > > > class Poll(models.Model): > > question = models.CharField(max_length=200) > > pub_date = models.DateTimeField('date published') > > > def __unicode__(self): > > return self.question > > The "def" statements have to be at the same indentation level as > what's before it. will they still be a part of the classes? From kw at codebykevin.com Sun Aug 19 11:52:34 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Sun, 19 Aug 2007 11:52:34 -0400 Subject: Python and Tkinter Programming--Expensive! In-Reply-To: <slrnfcdj46.t75.nick@irishsea.home.craig-wood.com> References: <Xllxi.9066$3x.1781@newssvr25.news.prodigy.net> <slrnfcdj46.t75.nick@irishsea.home.craig-wood.com> Message-ID: <1379c$46c8674b$4275d90a$31180@FUSE.NET> Nick Craig-Wood wrote: > W. Watson <wolf_tracks at invalid.com> wrote: >> Why is the book in Subject (author is Grayson) so expensive? $100 on Amazon >> and $195 on ABE. Aren't there alternatives? > > There is an excellent section (266 pages) on TKinter in "Programming > Python" by Mark Lutz. I've got the 2nd edition. > > Lutz concentrates on TK programming using classes, making re-usable > components which I found really helpful compared to the ad-hoc way I'd > seen TK presented previously. > +1 on Lutz. It's very current, and has helped me learn Tkinter programming (and I already have a background with Tk via Tcl). -- Kevin Walzer Code by Kevin http://www.codebykevin.com From vedrandekovic at v-programs.com Wed Aug 22 03:26:18 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Wed, 22 Aug 2007 00:26:18 -0700 Subject: redirect or cover .bat log In-Reply-To: <5j26bvF3s7lbpU2@mid.uni-berlin.de> References: <1187764689.836375.212730@z24g2000prh.googlegroups.com> <5j26bvF3s7lbpU2@mid.uni-berlin.de> Message-ID: <1187767578.925671.107000@q4g2000prc.googlegroups.com> On 22 kol, 09:19, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > vedrandeko... at v-programs.com schrieb: > > > Hello, > > > e.g I need run my my_scripts_setup.bat that contain: > > > python myscript_setup.py py2exe > > > Can I cover or redirect log of that process into my wx program? > > I'am using Windows XP SP2, and Python 2.5. > > Who's running the bat, and who's running the wx program? > > Diez Hi, First I convert my main wx program to exe with my py2exe setup,then under my main program (exe), I must run that .bat file and redirect or cover that process. Regards, Vedran From pyth0nc0d3r at gmail.com Mon Aug 20 16:42:25 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Mon, 20 Aug 2007 15:42:25 -0500 Subject: Regarding Classes Message-ID: <eb79828c0708201342sdb7e572h9dde11f914e12436@mail.gmail.com> What is the main reason of "self" when it involves classes/functions -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070820/0513ef3c/attachment.html> From flavio.preto at gmail.com Wed Aug 22 00:26:27 2007 From: flavio.preto at gmail.com (Flavio Preto) Date: Wed, 22 Aug 2007 01:26:27 -0300 Subject: Threads and racing conditions Message-ID: <5fb10ac20708212126j70f8100bka66fe5e3661904cc@mail.gmail.com> Hi, I have a doubt. Supose that i have the minimun class below: class db: def __init__(self): self.db = {} def read(self, key): return self.db[key] def write(self, key, value): self.db[key] = value and an object of this class is shared among some threads. Is it possible that in a read, the method return a value that is not an old or a new value? In other words, is it possible that a 'read' return (due to a 'write' at the same time by another thread) an invalid value that was never supposed to be there? Thanks, Flavio Preto -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070822/afed785e/attachment.html> From paul.faulstich at gmail.com Sun Aug 26 18:08:18 2007 From: paul.faulstich at gmail.com (paul) Date: Sun, 26 Aug 2007 15:08:18 -0700 Subject: pySerial in a daemon process In-Reply-To: <5je954F3s0nilU1@mid.individual.net> References: <1188158581.316824.89360@k79g2000hse.googlegroups.com> <5je954F3s0nilU1@mid.individual.net> Message-ID: <1188166098.738058.182580@w3g2000hsg.googlegroups.com> On Aug 26, 5:20 pm, Bjoern Schliessmann <usenet- mail-0306.20.chr0n... at spamgourmet.com> wrote: > paul wrote: > > If I put these back in and try to run the daemon, the script fails > > when I try to connect to the serial port, with this error: > > serial.serialutil.SerialException: Could not open port: [Errno 13] > > Permission denied: '/dev/ttyS0' > > Did you check the permissions on this file? Often you have to be > member of a "dialout" group or similar to get access. > > Regards, > > Bj?rn > > -- > BOFH excuse #172: > > pseudo-user on a pseudo-terminal THANKS! That did it, but perhaps can you explain to me why... Before I had posted this question first thing I did was to look at / dev/ttyS0, and indeed the group is dialout (gid=20), so I tried a couple of things: 1. checked my id to see if I was a member of dialout, and indeed I am. So, I edited the daemon script to use my id and set the gid to dialout (ie: os.setegid(20) & os.seteuid(1000)) and it still failed. 2. made the id I really want to use (pydaemon, uid=110) a member of dialout, and set the daemon script to use those (ie: os.setegid(20) & os.seteuid(110)) and it still failed... After reading your comment, I went and did a chgrp to set the various script file groups to dialout, and indeed it now works. What confuses me is that if the script needed that group, why doesn't the setegid or seteuid fail? Why does the script keep running okay until the connect, and fail then? Thanks! Paul From claird at lairds.us Mon Aug 13 13:37:36 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 13 Aug 2007 17:37:36 +0000 Subject: Process Control Help References: <1185808072.695752.20720@z28g2000prd.googlegroups.com> <mailman.1393.1185913913.22759.python-list@python.org> <1185923367.122846.117750@x40g2000prg.googlegroups.com> <heq5p4-29v.ln1@lairds.us> Message-ID: <0gh6p4-143.ln1@lairds.us> In article <heq5p4-29v.ln1 at lairds.us>, I mused: >In article <1185923367.122846.117750 at x40g2000prg.googlegroups.com>, >Azazello <tylerca at jeld-wen.com> wrote: >>On Jul 31, 12:45 pm, Walt Leipold <leip... at ace-net.com> wrote: > . > . > . >>> It has nothing to do with 'proprietary issues'. A lot of it has to do >>> with the perception of support -- who will support Python and custom >>> Python code if my plant shuts down? Who will train my developers and >>> operators? Who can I sue? The rest of it is because of the way the > . > . > . >>> Yes, it's a shame that you have to buy three packages to perform three >>> functions, and then buy other 3rd-party packages to tie them together. >>> Yes, it's a shame that industrial software is expensive, and >>> proprietary, and Windows-only, and generally has a brain-dead scripting >>> language (when it has any scriptability at all). Still, as much as it >>> galls me to say it, if your company's primary business isn't writing >>> industrial automation software, don't write industrial automation >>> software. > . > . > . >>> * Unless you're a hobbyist, if you want to do data acquisition or i/o, >>> purchase an i/o server for your particular bus/instrumentation from a >>> major manufacturer. You *can* write your own i/o server, especially for >>> simple protocols like Modbus, but the commercial versions have been >>> tested more exhaustively than you can manage. Also, the most common >>> protocol these days is OPC, which isn't a protocol at all in the >>> conventional sense -- it's a set of APIs to a Windows DLL, with the >>> wire-level details completely opaque -- so you'd have to buy a library >>> for that anyway. . . . >>> on Visual Basic for Applications rather than a better (and free and Open >>> Source!) language like Python. It's also a tragedy that the dominant >>> i/o 'protocol' for industrial automation isn't really a protocol, and is >>> Windows-only to boot. It's horrifying that the primary means of >>> communication between process control and data acquisition applications >>> is via DDE or ActiveX. And I find it incredible that people and >>> companies will pay large sums of money for some of the industrial >>> automation products on the market. But that's the way the industry >>> works, and, as frustrating as the commercial offerings are, using them >>> will probably be better for you and your company in the long run. > . > . > . >>I really appreciate your post Walt. I started this thread last week >>and I have to admit that in the subsequent days the 'option' of using >>Python for our control solutions is simply not feasible. Although the >>project I wanted to implement was fairly small scale, no 20 ton pieces >>or x-ray machinery, the principle of the matter remains the same, >>especially as a large corporation. As an intern returning to school >>in the fall, the underlying responsibility for a Python system was my >>original concern and discouragement to my employer for persuing this >>path. It became readily apparent that using the crumby software >>packaged with our control devices is surely faster in the long run, as >>we are not involved in software development. (The majority of my >>coworkers' formal programming experience is in FORTRAN) It has been a >>very discouraging few days. There's so much room for improvement and >>yet... My 4-day conclusion is unless you're already involved in >>controls software you must be crazy to join. Are many young engineers >>entering this field? >> > >At an anecdotal level, I'd guess that, no, there are few >young engineers entering this field. . . . 'Just occurred to me that a GREAT thing to do might be for a young engineer to catch the SD Best Practices 2007 East in Boston in September <URL: http://www.sdexpo.com/2007/sdbp/overview.htm >, which is running concurrently with Embedded Systems <URL: http://www.embedded.com/esc/boston/ > (as well as RFID World <URL: http://www.rfid-world.com/boston/ >). They sell inspiration by the half-hour. From arkanes at gmail.com Fri Aug 10 12:13:30 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 10 Aug 2007 11:13:30 -0500 Subject: The Future of Python Threading In-Reply-To: <1186760254.859080.137840@g12g2000prg.googlegroups.com> References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <87ir7n4fps.fsf@benfinney.id.au> <1186760254.859080.137840@g12g2000prg.googlegroups.com> Message-ID: <4866bea60708100913l59f63266x93286947d953e46b@mail.gmail.com> On 8/10/07, Ben Sizer <kylotan at gmail.com> wrote: > On 10 Aug, 15:38, Ben Finney <bignose+hates-s... at benfinney.id.au> > wrote: > > "Justin T." <jmtull... at gmail.com> writes: > > > The truth is that the future (and present reality) of almost every > > > form of computing is multi-core, and there currently is no effective > > > way of dealing with concurrency. > > > > Your post seems to take threading as the *only* way to write code for > > multi-core systems, which certainly isn't so. > > > > Last I checked, multiple processes can run concurrently on multi-core > > systems. That's a well-established way of structuring a program. > > It is, however, almost always more complex and slower-performing. > > Plus, it's underdocumented. Most academic study of concurrent > programming, while referring to the separately executing units as > 'processes', almost always assume a shared memory space and the > associated primitives that go along with that. > This is simply not true. Firstly, there's a well defined difference between 'process' and a 'thread' and that is that processes have private memory spaces. Nobody says "process" when they mean threads of execution within a shared memory space and if they do they're wrong. And no, "most" academic study isn't limited to shared memory spaces. In fact, almost every improvement in concurrency has been moving *away* from simple shared memory - the closest thing to it is transactional memory, which is like shared memory but with transactional semantics instead of simple sharing. Message passing and "shared-nothing" concurrency are very popular and extremely effective, both in performance and reliability. There's nothing "undocumented" about IPC. It's been around as a technique for decades. Message passing is as old as the hills. > > > We still worry about setting up threads, synchronization of message > > > queues, synchronization of shared memory regions, dealing with > > > asynchronous behaviors, and most importantly, how threaded an > > > application should be. > > > > All of which is avoided by designing the program to operate as > > discrete processes communicating via well-defined IPC mechanisms. > > Hardly. Sure, so you don't have to worry about contention over objects > in memory, but it's still completely asynchronous, and there will > still be a large degree of waiting for the other processes to respond, > and you have to develop the protocols to communicate. Apart from > convenient serialisation, Python doesn't exactly make IPC easy, unlike > Java's RMI for example. > There's nothing that Python does to make IPC hard, either. There's nothing in the standard library yet, but you may be interested in Pyro (http://pyro.sf.net) or Parallel Python (http://www.parallelpython.com/). It's not erlang, but it's not hard either. At least, it's not any harder than using threads and locks. From mcfletch at vrplumber.com Thu Aug 23 10:09:22 2007 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Thu, 23 Aug 2007 10:09:22 -0400 Subject: Question: wxpython and 3d engine example with model load ? In-Reply-To: <1187860306.533382.248430@j4g2000prf.googlegroups.com> References: <1187860306.533382.248430@j4g2000prf.googlegroups.com> Message-ID: <46CD9512.1010206@vrplumber.com> OpenPavilion wrote: ... > I would like to create an application, which uses wxpython tree, menu > and grid elements and embedds a 3d view of some of the listed objects > in an own detail window, so showing the object as a 3d model. > I know there is PyOpenGL as well, but I need to load complete models > (meshes done with cinema4d or blender) into the 3d view. > There's a bit of sample code in OpenGLContext/bin (yes, yes, I know, part of PyOpenGL, which you don't want) that does a VRML-97-scenegraph-rendering window + a shell (you'll need the latest CVS version to work with modern wxPythons). There's commented out code that inserted a tree (to show the scenegraph as a tree, but I haven't got that finished). Other options: * I think Pivy (Coin/Inventor wrapper) could likely be embedded in PyQt (it has a Qt-based window operation IIRC) if that's an acceptable compromise. * http://www.python-ogre.org/wiki/DownloadsPage seems to suggest there's an example for using Ogre with wxPython/wxWidgets. * http://panda3d.org/phpbb2/viewtopic.php?=&p=11555 suggests there's a way to get panda3d and wxPython working together I don't see a soya + wxPython page in a few seconds of googling, so I guess finding that is left as an exercise for the reader. HTH, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From Shawn at Milochik.com Mon Aug 20 15:07:02 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Mon, 20 Aug 2007 15:07:02 -0400 Subject: reading a line in file In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE2B4@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE2B2@efmailx> <2dc0c81b0708201029k5909d919vcf0deebae74a79c7@mail.gmail.com> <93066C069973ED448DC2BCEA9C44A7383BE2B4@efmailx> Message-ID: <2dc0c81b0708201207p7f83f2e0l6de15fd70be252a5@mail.gmail.com> Hopefully this will help (using your input file) #!/usr/bin/env python import re buildinfo = "input.txt" input = open(buildinfo, 'r') regex = re.compile(r"^\s*build.number=(\d+)\s*$") for line in input: if re.search(regex, line): print line buildNum = re.sub(r"^\s*build.number=(\d+)\s*$", "\\1", line) print line print buildNum From jon+usenet at unequivocal.co.uk Fri Aug 31 06:05:34 2007 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 31 Aug 2007 10:05:34 GMT Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188497498.3468.60.camel@dot.uniqsys.com> <mailman.188.1188546300.28954.python-list@python.org> <0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net> <1188551958.728836.137370@x35g2000prf.googlegroups.com> <fOadnfwlCJbQfErbnZ2dnUVZ_jCdnZ2d@speakeasy.net> Message-ID: <slrnfdfpve.ldo.jon+usenet@snowy.squish.net> On 2007-08-31, Erik Max Francis <max at alcyone.com> wrote: >> I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll >> and role similarly. >> >> My accent is probably from the East Midlands of the UK, but is not >> pronounced. > > _Troll_ and _frolic_ aren't pronounced with the same "o" sound in any > accent I've ever heard of. Welcome to England! > Which you pronounce _boat_ and _bot_ the same way, too? No. HTH HAND. From dogatemycomputer at gmail.com Mon Aug 20 16:48:36 2007 From: dogatemycomputer at gmail.com (dogatemycomputer at gmail.com) Date: Mon, 20 Aug 2007 13:48:36 -0700 Subject: urllib2.urlopen(url) pulling something other than HTML In-Reply-To: <1187641080.516885.122350@g4g2000hsf.googlegroups.com> References: <1187635452.841155.88720@a39g2000hsc.googlegroups.com> <1187641080.516885.122350@g4g2000hsf.googlegroups.com> Message-ID: <1187642916.824037.298750@o80g2000hse.googlegroups.com> Those responses were both very helpful. John's additional type checking is straight forward and easy to implement. I will also rewrite the application a second time using the class Gabriel offered. Both of these suggestions will help gain some insight into how Python works. "Don't even try to understand it - it's a mess. Use the HTMLParser module instead." I personally think the application itself "feels" more complicated than it needs to be but its possible that is just my inexperience. I'm going to do some reading about the HTMLParser module. I'm sure I could make this spider a bit more functional in the process. Thank you again for all of your help!! From sbellon at sbellon.de Sat Aug 11 06:16:30 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Sat, 11 Aug 2007 12:16:30 +0200 Subject: Destruction of generator objects References: <20070808002852.6228ae91@cube.tz.axivion.com> <1186613044.494852.306970@q75g2000hsh.googlegroups.com> <20070809011441.05d7dfb6@cube.tz.axivion.com> <1186819365.988117.232230@g4g2000hsf.googlegroups.com> Message-ID: <20070811121630.1b010eab@cube.tz.axivion.com> On Sat, 11 Aug, Kay Schluehr wrote: > On Aug 9, 1:14 am, Stefan Bellon <sbel... at sbellon.de> wrote: > > Sorry, I forgot to mention that I am forced to using Python 2.4. > It doesn't matter. You can use try...finally as well in Python 2.4. > It's just not possible to use except and finally clauses in one > statement such as: [snip] The problem is yield inside try-finally which is not possible in 2.4. -- Stefan Bellon From paul at subsignal.org Wed Aug 22 09:30:09 2007 From: paul at subsignal.org (paul) Date: Wed, 22 Aug 2007 15:30:09 +0200 Subject: Fast socket write In-Reply-To: <1187787707.377952.322280@57g2000hsv.googlegroups.com> References: <1187744469.240933.149610@r23g2000prd.googlegroups.com> <46cba22b$1_1@news.chariot.net.au> <1187787707.377952.322280@57g2000hsv.googlegroups.com> Message-ID: <fahdou$i8r$1@sea.gmane.org> Greg Copeland schrieb: > On Aug 21, 9:40 pm, Bikal KC <nepbabucxspamf... at yahoo.ca> wrote: >> Greg Copeland wrote: >>> I'm having a brain cramp right now. I can't see to recall the name of >> Is your cramp gone now ? :P > > > I wish. If anyone can remember the name of this module I'd realy > appreciate it. http://tautology.org/software/python-modules/sendfile probably... From aleax at mac.com Sun Aug 19 01:48:32 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 18 Aug 2007 22:48:32 -0700 Subject: How to call module functions inside class instance functions? References: <1187484041.838615.259980@e9g2000prf.googlegroups.com> <mailman.2154.1187486317.22759.python-list@python.org> <1187487622.450655.265000@q4g2000prc.googlegroups.com> Message-ID: <1i32cjp.1nqwivj14fwim3N%aleax@mac.com> beginner <zyzhu2000 at gmail.com> wrote: ... > testmodule.py > ----------------- > """Test Module""" > > def __module_level_func(): > print "Hello" > > class TestClass: > def class_level_func(self): > __module_level_func() > > > main.py > ------------------ > import testmodule > > x=testmodule.TestClass() > x.class_level_func() > > > The error message I am encountering is: NameError: global name > '_TestClass__module_level_func' is not defined > > I think it has something to do with the two underscores for > __module_level_func. Maybe it has something to do with the python > implementation of the private class level functions. > > By the way, the reason I am naming it __module_level_func() is because > I'd like __module_level_func() to be private to the module, like the C > static function. If the interpreter cannot really enforce it, at least > it is some sort of naming convention for me. The two underscores are exactly the cause of your problem: as you see in the error message, the compiled has inserted the CLASS name (not MODULE name) implicitly there. This "name mangling" is part of Python's rules. Use a SINGLE leading underscore (NOT double ones) as the "sort of naming convention" to indicate privacy, and Python will support you (mostly by social convention, but a little bit technically, too); use a different convention (particularly one that fights against the language rules;-) and you're "fighting city hall" to no good purpose and without much hope of achieving anything whatsoever thereby. Alex From __peter__ at web.de Fri Aug 17 17:21:43 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 17 Aug 2007 23:21:43 +0200 Subject: Array and floating point References: <1187384816.251783.95410@19g2000hsx.googlegroups.com> Message-ID: <fa53h9$qbe$02$1@news.t-online.com> Jonathan Shan wrote: > Hello, > > I'm experiencing a problem where the float being appended to the array > is not the same as the result of the appending. > >>>> from array import * >>>> x = array('f') >>>> x.append(float("0.1")) >>>> x[0] > 0.10000000149011612 >>>> float("0.1") > 0.10000000000000001 > > I'm expecting x[0] = 0.10000000000000001 array("f") is an array of C floats while Python's float type is a double in C terms. That's why you lose some precision. Try array("d") instead: >>> from array import array >>> x = array("d") >>> x.append(0.1) >>> x[0] 0.10000000000000001 Peter From limodou at gmail.com Sun Aug 19 00:03:33 2007 From: limodou at gmail.com (limodou) Date: Sun, 19 Aug 2007 12:03:33 +0800 Subject: ANN: UliPad 3.7 released! Message-ID: <505f13c0708182103k41ffabc9wcb1009538a76c10a@mail.gmail.com> UliPad is a flexible editor, based on wxPython. It's has many features,just like:class browser, code auto-complete, html viewer, directory browser, wizard, etc. The main feature is the usage of mixin. This makes UliPad can be extended easily. So you can write your own mixin or plugin, or simple script, these can be easy and seamless integrated with UliPad. What's new in 3.7 =================== New Features and Changes: #. Add PEP8 sytle checking #. Enhance calltip showing #. Add a new option in Preference, which is used for when you toggle comment lines(Ctrl+/ or Ctrl+\) if it'll popup a comment dialog. You can find it in Preference->Document->Show comment character dialog when adding comment. #. Saving auto todo window status #. Changing shortcut of quote dialog from Ctrl+Q to Ctrl+' #. Changing the number of recent files to 20 #. Changing shortcut Ctrl+Alt+L to Alt+Z, Ctrl+Alt+B to Alt+X #. Saving the status of Message window word wrap #. Saving the snippets window position #. The results of find in files can only show the filenames and you can copy them to clipboard #. Add Spanish language translation and Traditional Chinese language translation #. Using ZestyParser Module to parse the source code syntax #. Improving input assistant functionality #. Adding config.txt documentation #. When saving files, automatically adding accordingly filename suffix #. Adding mixin reload mechanism, it will be very useful when developing #. Adding folder sort functionality when adding new folder to directory browser window #. Adding template in input assistant, and you can press TAB key to jump to the next field. The template just like: ${1:something}. #. Adding LUA syntax support #. Adding mako(template module) support plugin #. Adding batch filenames rename plugin #. Enable ftp window be openned left or bottom pane according to the openning position #. Adding Alt+R shortcut for open recently files #. Merging new 1.20 version winpdb to ulipad Bug fix: #. Fix ctag support bug #. Fix default style bug #. Fix the wrong cursor jumping after undo operating #. Fix xml lexer type bug #. Fix copying bug when the text block has no indent #. Fix openning multi-view bug from menu items #. Fix the input focus losing bug when openning bottom pane or double-click on directory browser entries #. Fix user can open multi find dialogs bug #. Fix register functionality in windows UliPad has been ported to code.google.com, so you can visit the new project site at: http://code.google.com/p/ulipad, and also visit the new svn address. Recommends using source version. Source Code: http://ulipad.googlecode.com/files/ulipad.3.7.zip Win Execute Code: http://ulipad.googlecode.com/files/ulipad.3.7.exe If you have any suggestion or question, please subscribe the ulipad mailling list: http://groups.google.com/group/UliPad -- I like python! UliPad <<The Python Editor>>: http://code.google.com/p/ulipad/ My Blog: http://www.donews.net/limodou From stefan.behnel-n05pAM at web.de Thu Aug 30 15:28:30 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 30 Aug 2007 21:28:30 +0200 Subject: Simple elementtree question In-Reply-To: <1188495178.701968.246690@50g2000hsm.googlegroups.com> References: <1188495178.701968.246690@50g2000hsm.googlegroups.com> Message-ID: <46D71A5E.1000005@web.de> IamIan wrote: > This is in Python 2.3.5. I've had success with elementtree and other > RSS feeds, but I can't get it to work with this format: > > <?xml version="1.0"?><rdf:RDF > xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" > xmlns:dc="http://purl.org/dc/elements/1.1/" > xmlns:fr="http://ASPRSS.com/fr.html" > xmlns:pa="http://ASPRSS.com/pa.html" > xmlns="http://purl.org/rss/1.0/"> > <channel rdf:about="http://www.sample.com"> > <title>Example feed [...] > > > What I want to extract is the text in the title and link tags for each > item (eg. First story and http://www.sample.com/ > news/20000/news.htm). Starting with the title, my test script > is: > > import sys > from urllib import urlopen > > import elementtree.ElementTree as ET > > news = urlopen("http://www.sample.com/rss/rss.xml") > nTree = ET.parse(news) > for item in nTree.getiterator("title"): > print item.text > > Whether I try this for title or link, nothing is printed. Your document uses namespaces. What you are looking for is not the tag "title" without a namespace, but the tag "{http://purl.org/rss/1.0/}title" with the default namespace. http://effbot.org/zone/element.htm#xml-namespaces Stefan From sdoty044 at gmail.com Wed Aug 8 17:12:08 2007 From: sdoty044 at gmail.com (sdoty044 at gmail.com) Date: Wed, 08 Aug 2007 14:12:08 -0700 Subject: help a n00b with a Zope site-package install Message-ID: <1186607528.256756.209030@i38g2000prf.googlegroups.com> I am having a general problem getting Zope installed as part of my linux distro. Sadly, I have always used Python on Windows, and now I am have to do some work for Linux. My goal is to compile a SuSE linux distro of Python with all the same site-packages that I am using on Windows. The only thing I am having issues with is Zope. Using Yast is not an option... for I am stuck using SLES 9... and I am running with Python 2.4 and 2.5. SLES 9 only has packages for Python 2.3. From carsten at uniqsys.com Wed Aug 1 08:19:41 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 01 Aug 2007 08:19:41 -0400 Subject: Plain old SAX and minidom useable? But how then? In-Reply-To: <1185969539.653078.287360@w3g2000hsg.googlegroups.com> References: <1185969539.653078.287360@w3g2000hsg.googlegroups.com> Message-ID: <1185970781.3370.14.camel@dot.uniqsys.com> On Wed, 2007-08-01 at 04:58 -0700, Dobedani wrote: > [...] > "Nelson says: There's the stock Python install, which barely does > anything [for XML]. That's overstated. Plain old SAX and minidom may > not be ideal, but they're useable." > > Please: where then can I find examples of such use? If I cannot use > xpath, I would not mind to browse a bit - e.g. using functions like > getElementByTag() but I don't even know how to use those. TIA Here's a micro-tutorial: >>> import xml.dom.minidom >>> contents = """\ ... ... Parrot ... Holy Grail ... """ >>> dom = xml.dom.minidom.parseString(contents) >>> things = dom.getElementsByTagName("thing") >>> print things[0].childNodes [] >>> print things[0].childNodes[0].nodeValue Parrot >>> print things[0].hasAttribute("class") False >>> print things[0].getAttribute("class") >>> print things[1].childNodes [] >>> print things[1].childNodes[0].nodeValue Holy Grail >>> print things[1].hasAttribute("class") True >>> print things[1].getAttribute("class") special There's also the online documentation at http://docs.python.org/lib/module-xml.dom.minidom.html Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From Brian.McCann at viziant.net Fri Aug 24 09:03:30 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Fri, 24 Aug 2007 09:03:30 -0400 Subject: how to tar with python Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE2EF@efmailx> Hi, I'm trying to tar the contents of a directory "test" which contains 3 files foo1.xml ,foo2.xml, foo3.xml in my current directory /home/pythonbox/tmp I have the directory "test" if I run the below script it fails with the below error, but the files exist in the directory test any help would be greatly appreciated --Brian ################################## [tmp]$ ./tarup.py Traceback (most recent call last): File "./tarup.py", line 29, in ? tfile .add(f) File "/usr/lib64/python2.4/tarfile.py", line 1229, in add tarinfo = self.gettarinfo(name, arcname) File "/usr/lib64/python2.4/tarfile.py", line 1101, in gettarinfo statres = os.lstat(name) OSError: [Errno 2] No such file or directory: 'viz2.xml' ################################### import string import os import shutil import tarfile tfile = tarfile.open("files.tar.gz", 'w:gz') files = os.listdir("test") for f in files: tfile .add(f) tfile.close -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Aug 22 08:12:58 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 22 Aug 2007 14:12:58 +0200 Subject: Where we need to use Python ? In-Reply-To: <1187596936.136499.200280@l22g2000prc.googlegroups.com> References: <1187596936.136499.200280@l22g2000prc.googlegroups.com> Message-ID: <46cc281a$0$400$426a74cc@news.free.fr> gperumal at gmail.com a ?crit : > Hi > > Iam new to Python > I know Perl, JScript,C,C++,Java > But i want to know where excatly this python come in to picture Somewhere between Perl and Java. > And Is it a interpreted language or a programming language ??? It's obviously a programming language, but this has nothing to do with interpreted vs compiled - which FWIW is a property of an implementation, not of a language. Actually, most Python implementations are compiled to byte-code (specific one for CPython, JVM byte-code for Jython, CLR byte-code for Iron-Python). From sentientholon at gmail.com Wed Aug 22 16:36:07 2007 From: sentientholon at gmail.com (Frederick Polgardy) Date: Wed, 22 Aug 2007 20:36:07 -0000 Subject: Learning Python using a book based on version 1.5 In-Reply-To: <1187814437.775758.159510@e9g2000prf.googlegroups.com> References: <1187814437.775758.159510@e9g2000prf.googlegroups.com> Message-ID: <1187814967.887137.123050@q4g2000prc.googlegroups.com> On Aug 22, 3:27 pm, "dogatemycompu... at gmail.com" wrote: > Greetings, > > A friend of mine dropped off a copy of Sams Teach Yourself Python in > 24 Hours published in 2000. I skimmed the first couple of chapters > looking for the interpreter version and the book was based on version > Python version 1.5. > > Is this book still relevant? Should I toss it and look for something > newer? Yes, you should really toss it. I mean, sure, there's a lot of Python 1.5 that's still here, but there have been major changes in every minor version since 2.0. Fred From steve at holdenweb.com Mon Aug 6 19:22:12 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 06 Aug 2007 19:22:12 -0400 Subject: maybe a popen question... or something else? In-Reply-To: <1186441210.383700.301790@i13g2000prf.googlegroups.com> References: <1186441210.383700.301790@i13g2000prf.googlegroups.com> Message-ID: <46B7AD24.4010305@holdenweb.com> dude wrote: > Working on Windows XP > Say I have a Windows executable, foo.exe. > foo.exe is a command line tool that can take a number of different > arguments and perform corresponding actions. > > I want to invoke foo.exe from a Python script (using whatever will > work best). I want to continuously pass arguments to foo.exe in > between doing other stuff from within my Python script. > > Some pseudo code: > > processHandle = invoke("foo.exe") # what python module should "invoke" > be here? > > doUnrelatedStuff() > > processHandle.passArgs("arg1 arg2") # The same foo.exe I invoked above > gets these args for processing > > doMoreUnrelatedStuff() > > processHandle.passArgs("arg3 arg4") # The same foo.exe I invoked above > gets these args for processing > > processHandle.close() # "foo.exe is destroyed" > > Thanks for any help. > When you say "pass arguments", the methodology you outline definitely isn't going to fly with argument passing. When a command is invoked the arguments are taken from the command line, so it isn't possible to pass further arguments at a later time. You probably need to write to you sub-process's standard input stream. which you can do whit the subprocess module (the modern way to do it) or one of the various popen() functions. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From yan.python at gmail.com Tue Aug 14 02:21:24 2007 From: yan.python at gmail.com (yan.python at gmail.com) Date: Tue, 14 Aug 2007 06:21:24 -0000 Subject: how to move cursor in Interactive Interpreter Message-ID: <1187072484.626674.157200@x40g2000prg.googlegroups.com> i have a question. when i run Interactive Interpreter in linux command promt,how can i move the cursor. for example,when i enter a string,i often enter the quotation mark "" first,and the move the cursor inside the mark to enter the string,in windows,it is ok.but when i do that in linux,pressing the "left" key will just print "^[[D" in the screen ,but not what i want. so , how can i move the cursor Interactive Interpreter in linux? i've googled and find nothing useful.who i tell me what to do? From a.schmolck at gmail.com Mon Aug 13 13:49:19 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Mon, 13 Aug 2007 18:49:19 +0100 Subject: Fatest standard way to sum bytes (and their squares)? References: Message-ID: Alexander Schmolck writes: > Erik Max Francis writes: > >> Alexander Schmolck wrote: >> >>> Is this any faster? >>> >>> ordSum, orsSumSq = (lambda c:c.real,c.imag)(sum(complex(ord(x),ord(x)<<1) >>> for x in data)) >> >> That's pretty clever, but I neglected to mention that I need to accumulate the >> sums as ints/longs to avoid losing precision, so converting to floating point >> isn't an optional. > > I think you can safely use this trick (provided it really makes things faster) > provided you sum blocks no larger than 2**(53-8) bytes; Forgot about the squares; make this 2**(53-16); still pretty big. 'as From paddy3118 at googlemail.com Wed Aug 22 00:38:43 2007 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 21 Aug 2007 21:38:43 -0700 Subject: defaultdict of arbitrary depth In-Reply-To: <1187321113.841198.195100@22g2000hsm.googlegroups.com> References: <1187321113.841198.195100@22g2000hsm.googlegroups.com> Message-ID: <1187757523.509143.218730@x35g2000prf.googlegroups.com> On Aug 17, 4:25 am, Paul McGuire wrote: > In responding to another post on defaultdict, I posted an > implementation of a 2-level hashtable, by creating a factory method > that returned a defaultdict(dict). The OP of that other thread was > trying to build a nested tree from a set of n-tuples, in which the > first (n-1) values in each tuple were the keys for navigating down the > tree, and the final n'th value was the value for to be assigned to the > leaf node. My post worked only if n=2, which fortunately was the test > case that the OP gave. But it annoyed me that this required advance > knowledge of the number of keys. > > I've hacked out this recursivedefaultdict which is a > defaultdict(defaultdict(defaultdict(...))), arbitrarily deep depending > on the keys provided in the reference. > > Please comment. > > -- Paul > > from collections import defaultdict > > data = [ > ('A','B','Z',1), ('A','C','Y',2), ('A','C','X',3), > ('B','A','W',4), ('B','B','V',5), ('B','B','U',6), > ('B','D','T',7), > ] > > class recursivedefaultdict(object): > def __init__(self): > self.__dd = defaultdict(recursivedefaultdict) > def __getattr__(self,attr): > return self.__dd.__getattribute__(attr) > def __getitem__(self,*args): > return self.__dd.__getitem__(*args) > def __setitem__(self,*args): > return self.__dd.__setitem__(*args) > > table = recursivedefaultdict() > > for k1,k2,k3,v in data: > table[k1][k2][k3] = v > > for kk in sorted(table.keys()): > print "-",kk > for jj in sorted(table[kk].keys()): > print " -",jj > for ii in sorted(table[kk][jj].keys()): > print " -",ii,table[kk][jj][ii] > > prints: > - A > - B > - Z 1 > - C > - X 3 > - Y 2 > - B > - A > - W 4 > - B > - U 6 > - V 5 > - D > - T 7 There is something here: http://groups.google.com/group/comp.lang.python/msg/92502e0278c2a56e - Paddy. From thomas at jollans.com Sun Aug 19 18:40:40 2007 From: thomas at jollans.com (Thomas Jollans) Date: Mon, 20 Aug 2007 00:40:40 +0200 Subject: Syntax Question - list multiplication In-Reply-To: <1187560273.146491.90530@r29g2000hsg.googlegroups.com> References: <1187560273.146491.90530@r29g2000hsg.googlegroups.com> Message-ID: <200708200040.45740.thomas@jollans.com> On Sunday 19 August 2007, Pablo Torres wrote: > Hi guys! > > I am working on Conway's Game of Life right now and I've run into a > little problem. > > I represent dead cells with 0s and live ones with 1s. Check this out: > >>> grid = [[0] * 3] * 3 > >>> grid > > [[0, 0, 0], [0, 0, 0], [0, 0, 0]] > > >>> grid[0][0] = 1 > > [[1, 0, 0], [1, 0, 0], [1, 0, 0]] > > Now, that's not what I want. I just want the first element of the > first sublist to be a 1, not the first of every one. Here's what I > tried and didn't work: > > 0. grid = [[0] * 3][:] * 3 then the same grid[0][0] = 1 statement > 1. grid = [[0][:] * 3] * 3 followed by the same assignment > 2. (grid[0])[0] = 1 with the original initialization of the grid > > So, that means that it isn't a problem with two different variables > refering to the same list (0. and 1. prove that). What I don't > understand is why 2. doesn't work either. I'm baby-feeding my > instructions to Python and the mistake is still there. Any ideas? If you want three copies of the list, you need to copy it thrice (well, twice) Thus: >>> row = [0] * 3 >>> grid = [] >>> for n in xrange(3): grid.append(row[:]) ... >>> grid [[0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> grid[0][0] =1 >>> grid [[1, 0, 0], [0, 0, 0], [0, 0, 0]] >>> -- Regards, Thomas Jollans GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu Hacker key : v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part. URL: From rdm at rcblue.com Sun Aug 19 17:21:14 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 19 Aug 2007 14:21:14 -0700 Subject: Hot subject: a good python editor and/or IDE? Message-ID: <20070819212123.DDE1B1E4014@bag.python.org> At 02:47 AM 8/19/2007, S?bastien wrote: >Hi folks, > >I am currently using Eclipse+PyDev when developping Python projects but >I lack a fast, simple editor for tiny bit of scripts. So here is my >question: what is, for you, the current best ( but still kind of light! >) Python editor/IDE ? A tiny precision, I am on Ubuntu so I am looking >for a linux compatible editor. I thought Ulipad WAS linux-compatible. Isn't it? Dick Moores XP, Python 2.5, editor is Ulipad ====================================== Bagdad Weather From python at jayloden.com Wed Aug 8 03:15:05 2007 From: python at jayloden.com (Jay Loden) Date: Wed, 08 Aug 2007 03:15:05 -0400 Subject: Seek the one billionth line in a file containing 3 billion lines. In-Reply-To: <7xzm12o7o7.fsf@ruckus.brouhaha.com> References: <1186554220.272488.134780@d55g2000hsg.googlegroups.com> <7xzm12o7o7.fsf@ruckus.brouhaha.com> Message-ID: <46B96D79.9050100@jayloden.com> Paul Rubin wrote: > Sullivan WxPyQtKinter writes: >> This program: >> for i in range(1000000000): >> f.readline() >> is absolutely every slow.... > > There are two problems: > > 1) range(1000000000) builds a list of a billion elements in memory, > which is many gigabytes and probably thrashing your machine. > You want to use xrange instead of range, which builds an iterator > (i.e. something that uses just a small amount of memory, and > generates the values on the fly instead of precomputing a list). > > 2) f.readline() reads an entire line of input which (depending on > the nature of the log file) could also be of very large size. > If you're sure the log file contents are sensible (lines up to > several megabytes shouldn't cause a problem) then you can do it > that way, but otherwise you want to read fixed size units. If we just want to iterate through the file one line at a time, why not just: count = 0 handle = open('hugelogfile.txt') for line in handle.xreadlines(): count = count + 1 if count == '1000000000': #do something My first suggestion would be to split the file into smaller more manageable chunks, because any type of manipulation of a multi-billion line log file is going to be a nightmare. For example, you could try the UNIX 'split' utility to break the file into individual files of say, 100000 lines each. split is likely to be faster than anything in Python, since it is written in C with no interpreter overhead etc. Is there a reason you specifically need to get to line 1 billion, or are you just trying to trim the file down? Do you need a value that's on that particular line, or is there some other reason? Perhaps if you can provide the use case the list can help you solve the problem itself rather than looking for a way to seek to the one billionth line in a file. -Jay From byte8bits at gmail.com Fri Aug 10 12:08:32 2007 From: byte8bits at gmail.com (brad) Date: Fri, 10 Aug 2007 12:08:32 -0400 Subject: The Future of Python Threading In-Reply-To: <1186740111.918048.77920@d30g2000prg.googlegroups.com> References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> Message-ID: Justin T. wrote: > Hello, > > While I don't pretend to be an authority on the subject, a few days of > research has lead me to believe that a discussion needs to be started > (or continued) on the state and direction of multi-threading python. This is all anecdotal... threads in Python work great for me. I like Ruby's green threads too, but I find py threads to be more robust. We've written a tcp scanner (threaded connects) and can process twenty ports on two /16s (roughly 171K hosts) in about twenty minutes. I'm happy with that. However, that's all I've ever really used threads for, so I'm probably less of an expert than you are :) I guess it comes down to what you're doing with them. Brad From i_hate_jews at shiftmail.com Mon Aug 27 03:13:17 2007 From: i_hate_jews at shiftmail.com (Nenad Milicevic - The Aryan Serb) Date: Mon, 27 Aug 2007 00:13:17 -0700 Subject: Let's Unite Against Jews and Mongrels! Message-ID: <1188198797.772672.60840@r29g2000hsg.googlegroups.com> Rise up and shine, white sons and daughters Rise up and shine, you gotta fight to part those waters When we swim in the light, all will be okay The black, yellow and brown man will wash away. ------------------------------ Let's break the chains of Jewish and black domination! Unite, white brothers and sisters, and let's defeat those who oppress our white heritage! Our skin is our uniform! Serbian Committee for Aryan Defence Nenad Milicevic, executive Usenet name: Raoul Endymion or Raul Endymion ICQ 208030128 endymion at deadspam.com endimion at myrealbox.com Belgrade, Serbia From kyosohma at gmail.com Mon Aug 20 14:34:55 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 20 Aug 2007 11:34:55 -0700 Subject: str().join() isn't working In-Reply-To: References: <496954360708200905i2100b32ag5983ab729e5d216f@mail.gmail.com> Message-ID: <1187634895.387910.179500@m37g2000prh.googlegroups.com> On Aug 20, 1:16 pm, "Robert Dailey" wrote: > here is a more realized example of the lists I'm trying to join: > > _user_includes = [ > "../src", > "../resource", > "../inc", > "../src", > "../data", > "../gui", > "../script", > "../script/actions", > "../gui/dispatch", > "../gui/factories", > "../gui/frames", > "../gui/getters", > "../gui/localization", > "../gui/player", > "../gui/setters", > "../gui/utilities", > "../sis", > "../player", > "../platform/ngi", > "../../engine", > "../../engine/audio/NGI", > "../../engine/io", > "../../engine/io\NGI", > "../../engine/math", > "../../engine/math/fixed", > "../../engine/path/NGI", > "../../engine/text/NGI", > "../../engine/mem", > "../../engine/text", > "../../engine/observer", > "../../sdk/tiny_xml", > "../../sdk/zlib", > "../../sdk/lpng", > "../../sdk/IFDLib/Source/Precompile", > "../../sdk/IFDLib/Source/CoreLib", > "../../sdk/IFDLib/inc", > "../../sdk/IFDLib/Source/UtilLib", > "../../sdk/IFDLib/Source/GameLib", > "../../sdk/IFDlib/Source/OSLib/_NGI", > "../../sdk/stl-port/NGI", > "../../sdk/mini-boost/NGI", > "../../sdk/mini-boost/COMMON", > ] > > _system_includes = [ > "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include", > "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include/osextensions/rga", > "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include/osextensions/stdapis", > "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include/osextensions/stdapis/stlport", > "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/epoc32/include/variant" > ] > > On 8/20/07, Robert Dailey wrote: > > > Hi, > > > First have a look at the following code: > > > In main.py: > > ----------------------------------------------------------------------------------- > > space = " " > > > includes = space.join ( system._user_includes ) + " " + space.join( > > system._system_includes ) > > > In system.py: > > ----------------------------------------------------------------------------------- > > _user_includes = [ > > ] > > > _system_includes = [ > > ] > > > The above does not work. The interpreter states: "TypeError: sequence item > > 0: expected string, list found". I'm not sure what this means. Can anyone > > help me figure out what I'm doing wrong? Thanks. > > > PS: I've also tried putting strings in the lists above just to make sure > > that them being empty wasn't the problem. I got no different results. When you use join, you join the items in the list with each other to form one long string. In your statement, your script tries to concatenate 2 lists to each other before it does the join, which is impossible in Python. The "+" operator is only for addition and for two or more strings. See http://www.faqs.org/docs/diveintopython/odbchelper_join.html for more information on joins. Mike From jzgoda at o2.usun.pl Fri Aug 10 17:39:39 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 10 Aug 2007 23:39:39 +0200 Subject: Python Dies on "make install" In-Reply-To: References: Message-ID: fartknuckle napisa?(a): > When I try to build and install python from source It configures and > makes fine but upon 'make install' I always get to this > point: > > > > Listing /usr/local/lib/python2.5/xml/sax ... > Compiling /usr/local/lib/python2.5/xml/sax/__init__.py ... > Compiling /usr/local/lib/python2.5/xml/sax/_exceptions.py ... > Compiling /usr/local/lib/python2.5/xml/sax/expatreader.py ... > Compiling /usr/local/lib/python2.5/xml/sax/handler.py ... > Compiling /usr/local/lib/python2.5/xml/sax/saxutils.py ... > Compiling /usr/local/lib/python2.5/xml/sax/xmlreader.py ... > Compiling /usr/local/lib/python2.5/xmllib.py ... > Compiling /usr/local/lib/python2.5/xmlrpclib.py ... > Compiling /usr/local/lib/python2.5/zipfile.py ... > make: *** [libinstall] Error 1 > > > > I am currently trying to install 2.5.1. I get the error no matter what the > version is. Does anyone have an idea what may be causing this? > > I have gone through the config.log and found no errors concerning > zipfile.py or zipfile or zip. I am thinking the error is the next command > after the zipfile.py installation because I can go into > /usr/local/lib/python2.5 and zipfile.py is installed. > > Any help much appreciated. I saw this (and reported this issue in SF's tracker) at some time around 2.2/2.3 (just cann't recall). I don't know what causes this problem exactly, but in my case the installation succeeded if I removed prevoius python's library directory (/usr/lib/python2.x or /usr/local/lib/python2.x). The module that stopped installation was exactly the same. -- Jarek Zgoda http://jpa.berlios.de/ From raims at dot.com Wed Aug 15 13:01:17 2007 From: raims at dot.com (Lawrence Oluyede) Date: Wed, 15 Aug 2007 19:01:17 +0200 Subject: All names in the current module References: <87d4xowymq.fsf@wilson.homeunix.com> Message-ID: <1i2whvw.1qje42i1bh18bkN%raims@dot.com> Torsten Bronger wrote: > How can I get a list with all classes defined in the current module? > Thank you! rhymes at groove ~ % cat > t.py class A: pass rhymes at groove ~ % python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import t >>> print dir(t) ['A', '__builtins__', '__doc__', '__file__', '__name__'] Now you have the list of names. To find out if they are actual classes or not you can do this: >>> import inspect >>> for member in dir(t): ... print member, inspect.isclass(getattr(t, member)) ... A True __builtins__ False __doc__ False __file__ False __name__ False HTH -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From rdm at rcblue.com Sun Aug 12 12:34:42 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 12 Aug 2007 09:34:42 -0700 Subject: Puzzled by "is" In-Reply-To: References: <20070809194105.39BD11E400A@bag.python.org> <87zm1042f0.fsf@benfinney.id.au> <87ir7l5bv4.fsf@benfinney.id.au> Message-ID: <20070812163657.2F8F41E400B@bag.python.org> At 08:23 AM 8/12/2007, Steve Holden wrote: >Dick Moores wrote: > > So would a programmer EVER use "is" in a script? > >Sure. For example, the canonical test for None uses > > x is None > >because there is only ever one instance of type Nonetype, so it's the >fastest test. Generally speaking you use "is" to test for identity (do >these two expressions reference the same object) rather than equality >(do these two expressions evaluate to equivalent objects). Off the top of your head, could you or others give me as many examples as you can think of? Thanks again, Dick From Shawn at Milochik.com Thu Aug 16 11:42:40 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Thu, 16 Aug 2007 11:42:40 -0400 Subject: A problem with Time In-Reply-To: <46c469be$0$66145$7b0f0fd3@mistral.news.newnet.co.uk> References: <46c469be$0$66145$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <2dc0c81b0708160842n66258aa1p10f08c090af74950@mail.gmail.com> import time oneDay = 60 * 60 * 24 #seconds in one day date = time.time() yesterday = date - oneDay From steve at holdenweb.com Wed Aug 29 17:45:36 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 29 Aug 2007 17:45:36 -0400 Subject: re compiled object result caching? In-Reply-To: <1188417101.936530.182480@50g2000hsm.googlegroups.com> References: <1188417101.936530.182480@50g2000hsm.googlegroups.com> Message-ID: Dan wrote: > I find myself often using regular expressions in the following > pattern: > > foo_re = re.compile(r"foo(bar)") > # . . . > re_result = foo_re.search(line) > if re_result: > bar = re_result.group(1) > # . . . > > But, I keep thinking this is awkward, and I would kind of like to have > the re object to cache its result; along the lines of: > > foo_re = re.compile(r"foo(bar)") > # . . . > if foo_re.search(line): > foo_re.last_result().group(1) > If you wanted to implement this I don't really see why a method call is necessary. It would surely only need to be a simple attribute? Of course you then introduce the possibility that someone will reference if before using the RE in a search, plus it still requires separate storage if you want the ability to use the same RE for two different matches and compare the match results. > I realize I could do this with a wrapper object (I'm not sure if I can > subclass the re object..), but I was wondering what the community > thought of this. Good idea? Bad? Would it be difficult to add to the > standard re module? The only real downside I can think of is thread > safety. The other practical benefit I can think of is situations like > the following: > > if unlikely_condition and foo_re.search(line): > # . . . > > With the current implementation I think you would either have to do > the search even if unlikely_condition is False, or you would have to > do an annoying nested if. Is there another way to achieve this that > I'm not thinking of? > I see absolutely no reason why you can't create your own module with a compile function that produces an extended_RE object by compiling the RE passed as an argument and saving the compiled result. It can then delegate most method calls to the compiled RE, but extend certain of its methods to provide the behavior that you want. Personally I think it's anti-Pythonic to abhor matchobj = pat.match(...) You throw some clarity out just for the sake of making the "no match" case a teeny bit faster and a minute amount more readable. But others' opinions may differ. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From yuxi at ece.gatech.edu Mon Aug 13 23:52:39 2007 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Mon, 13 Aug 2007 23:52:39 -0400 Subject: Icons for GUI development In-Reply-To: <1187058129.306171.174590@g12g2000prg.googlegroups.com> References: <1187058129.306171.174590@g12g2000prg.googlegroups.com> Message-ID: Benjamin wrote: > I'm developing a mail client. Since GUI are usually improved with some > icons, I'm looking for some. Because I'm not a very gifted artist I'm > searching for a library of GPL or public domain icons. Any suggestions? > I frequently use the Crystal icon set. http://www.everaldo.com/crystal/ Also, a page of links I encountered recently which may help you: http://www.snap2objects.com/2007/06/06/85-killer-resources-every-designer-should-know/ From klove at tax.ok.gov Wed Aug 29 14:22:39 2007 From: klove at tax.ok.gov (Kenneth Love) Date: Wed, 29 Aug 2007 13:22:39 -0500 Subject: Accessing docstrings at runtime? Message-ID: <011b01c7ea69$95512fe0$e6003dcc@worf2> How do I print the docstring for a class property? When I run the code below, I get the docstring for the string module and not the one I set for the property. --------------------------------------------- # NOTE: Found in Python docs defining built-in functions (such as # property()). FIXED: Bug in getx, setx, and delx where "__x" # was misreferenced as "_x". class C(object): def __init__(self): self.__x = None def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x x = property(getx, setx, delx, "I'm the 'x' property.") if __name__ == "__main__" y = C() y.x = 'test' print y.x print y.x.__doc__ --------------------------------------------- I get the following output: --------------------------------------------- test str(object) -> string Return a nice string representation of the object. If the argument is a string, the return value is the same object. --------------------------------------------- What am I doing wrong? adTHANKSvance, Kenneth Love P.S. If I want a docstring and I do not want a delete function, do I just pass 'None' (minus quotes) for that parameter? -- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Kenneth Love | Oklahoma Tax Commission DP Programmer/Analyst | Information Technology (405) 522 - 5864 | http://www.tax.ok.gov/ -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- From Brian.McCann at viziant.net Wed Aug 29 14:46:03 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Wed, 29 Aug 2007 14:46:03 -0400 Subject: copying files References: <93066C069973ED448DC2BCEA9C44A7383BE30C@efmailx> Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE30D@efmailx> one thing I just noticed is that when I run the script I get a new symbolic link created in my current dir TEST_HOME------>lib --Brian ________________________________ From: python-list-bounces+brian.mccann=viziant.net at python.org on behalf of Brian McCann Sent: Wed 8/29/2007 2:40 PM To: python-list at python.org Subject: copying files Hi, with the code below I set a variable TEST_HOME to a path and the variable m to a path in my current dir. I have a symbolic link setting m---->lib when I run the script I get no errors and the lib dir with its 20 files does not get copied to /v01/test_home any help would be greatly appreciated --Brian #!/usr/bin/python import string import os import sys import errno import shutil import tarfile TEST_HOME = "/v01/test_home" m = "./lib" os.system("cp -r m TEST_HOME") -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Mon Aug 20 10:51:10 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 20 Aug 2007 07:51:10 -0700 Subject: Newbee Question In-Reply-To: References: Message-ID: <1187621470.484615.7010@i13g2000prf.googlegroups.com> On Aug 20, 9:23 am, "HD1956" wrote: > This is probably a simple code. I am a truck driver who gets paid by > stops and cases. I am trying to figure out how to code my stop pay. I > get 40 cents per stop up to 22 stops, and $1.40 per stops after that. def calc(num): if num < 23: return 0.4 * num else: overtime = num - 22 x = 0.4 * 22 x += overtime * 1.4 return x # Use your own brain next time Mike From Shawn at Milochik.com Mon Aug 20 12:04:37 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Mon, 20 Aug 2007 12:04:37 -0400 Subject: regular expression dictionary search In-Reply-To: <1187625295.287653.137080@r34g2000hsd.googlegroups.com> References: <1187625295.287653.137080@r34g2000hsd.googlegroups.com> Message-ID: <2dc0c81b0708200904y729d902blab403a4d5b5f9ec2@mail.gmail.com> On 8/20/07, Paul McGuire wrote: > On Aug 20, 10:35 am, "Shawn Milochik" wrote: > > #!/usr/bin/env python > > > if __name__ == "__main__": > > > > print "The return for 'fred' : %s" % returnCode('fred') > > print "The return for 'silk' : %s" % returnCode('silk') > > print "The return for 'silky' : %s" % returnCode('silky') > > print "The return for 'hand' : %s" % returnCode('hand') > > print "The return for 'strand' : %s" % returnCode('strand') > > print "The return for 'bank' : %s" % returnCode('bank') > > > > Shawn - > > All that copy/pasting has got to have carpal tunnel written all over > it - DRY! > > tests = "fred silk silky hand strand bank".split() > for test in tests: > print "The return for '%s' : %s" % (test, returnCode(test)) > > -- Paul > > -- > http://mail.python.org/mailman/listinfo/python-list > You're right. Thanks for the correction. My wrists are shot as it is, and it's easy enough in vim to copy & paste. You know how it is -- I made one test line, then copied it to a second, then copied it to a third... Guilty of not planning ahead. ;o) From rgelfand2 at hotmail.com Thu Aug 2 14:45:39 2007 From: rgelfand2 at hotmail.com (Roman) Date: Thu, 02 Aug 2007 11:45:39 -0700 Subject: XML Processing Message-ID: <1186080339.344993.167670@z24g2000prh.googlegroups.com> Is there a package that converts a string that contains special characters in xml to to literal value. For instance, converts string http://myhome/¶m to http://myhome/&param. Thanks in advance From http Tue Aug 28 18:27:44 2007 From: http (Paul Rubin) Date: 28 Aug 2007 15:27:44 -0700 Subject: Haskell like (c:cs) syntax References: Message-ID: <7xr6lnxpjz.fsf@ruckus.brouhaha.com> "Stefan Niemann" writes: > Is there a pattern matching construct in Python like (head : tail), meaning > 'head' matches the first element of a list and 'tail' matches the rest? I > could not find this in the Python documentation. Python's lists are actually linear arrays. You can subscript them, i.e. x[0] is the first element, and slice them, i.e. x[1:] is all elements after the first. Note that x[1:] actually makes a new array and copies all the elements of x. Normally in Python one writes iterative loops rather than recursing or folding over a list: for a in x: print a so slicing isn't that common. Python also has something called generators which are sort of like Haskell's lazy-evaluation lists. They often make it possible to program in a Haskell-like style. Note however that they are mutable objects, i.e. using g.next() to get the next element of a generator actually updates the generator's internal state. This can lead to a bunch of subtle pitfalls if you're not careful, but overall they are a very useful feature. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Aug 3 04:01:06 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 03 Aug 2007 10:01:06 +0200 Subject: __call__ considered harmful or indispensable? In-Reply-To: References: <46b24200$0$19638$426a74cc@news.free.fr> Message-ID: <46b2e0c2$0$14572$426a74cc@news.free.fr> Skip Montanaro a ?crit : >>> In this case there was a bug. Depending on inputs, sometimes obj >>> initialized to a class, sometimes an instance of that class. (I fixed >>> that too while I was at it.) The problem was that the use of __call__ >>> obscured the underlying bug by making the instance as well as the class >>> callable. > >> I don't quite get the point here. A concrete example would be welcome. > > The bug went something like this: > > obj = some.default_class > ... > if some_other_rare_condition_met: > ... several lines ... > obj = some.other_class() > ... > > Later, > > x = obj() > x(...) Ok, I see. A nasty one, indeed. From rex at no_spam.dicad.de Wed Aug 22 11:23:51 2007 From: rex at no_spam.dicad.de (Rex Turnbull) Date: Wed, 22 Aug 2007 17:23:51 +0200 Subject: Handwriting Recognition In-Reply-To: <1187637967.915548.53240@k79g2000hse.googlegroups.com> References: <1187635063.531103.7610@d55g2000hsg.googlegroups.com> <1187637967.915548.53240@k79g2000hse.googlegroups.com> Message-ID: dogatemycomputer at gmail.com schrieb/wrote: >>> import handwriting >>> ... >>> http://docs.python.org/lib/module-handwriting.html >>> ha ha, I kid, I kid. >>> I don't think this is an easy problem to solve. You'd probably want >>> Python to be a wrapper around whatever hand-writing recognition >>> software you find or buy. I know handwriting recognition software can >>> read the hand-writing on checks, so that may be a starting point. > > I once had someone explain to me how this actually works from a purely > mathematical standpoint and the topic was fascinating. Unfortunately > most of the math went straight over my head and, in the end, it was > explained to me that math itself is the problem. Handwriting (and > almost any other uncontrolled input) is usually emotional, not logical > in the strictest sense (which is why handwriting experts can tell a > great deal about a person from the handwriting). If you can mimic > handwriting (or any emotional) input in a mathematical expression then > you wouldn't be far from playing "god". > > This was the only thing I could find that may be helpful to you: > > http://sourceforge.net/projects/tomoe/ > > This includes a "stroke editor" and an engine which may suit your > needs. Hope this helps.. > > Good luck! > We use a neural net. Can't say much as I didn't write it. It takes a lot of training though (by training I mean training the software with each symbol). Cheers, Rex From __peter__ at web.de Thu Aug 16 03:57:02 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 16 Aug 2007 09:57:02 +0200 Subject: Problem using Optional pyparsing References: Message-ID: Nathan Harmston wrote: > I know this isnt the pyparsing list, but it doesnt seem like there is > one. I m trying to use pyparsing to parse a file however I cant get > the Optional keyword to work. My file generally looks like this: > > ALIGNMENT ?1020 ?YS2-10a02.q1k chr09 ? ? 1295 ? ? ? 42 ? ?141045 > 142297 ? C ? ?1254 95.06 1295 reject_bad_break 0 > > or this: > > ALIGNMENT ?36 ? ?YS2-10a08.q1k chrm ? ? ?208 ? ? ?165 ? ? 10745 > 10788 ? C ? ? ?44 95.45 593 reject_low 10,14 > > and my grammar work well for these lines, however somethings the row looks like: > ALIGNMENT ?53 ? ?YS2-10b03.p1k chr12 ? ? ?180 ? ? ?125 ? 1067465 > 1067520 ? C ? ? ?56 98.21 532|5,2 reject_low 25 > > So I try to parse the 532 using > > from pyparsing import * > > integer = Word( nums ) > float = Word( nums+".") > identifier = Word( alphanums+"-_." ) > > alignment = Literal("ALIGNMENT ").suppress() > row_1 = integer.setResultsName("row_1")#.setParseAction(make_int) > src_id = identifier.setResultsName("src_id") > dest_id = identifier.setResultsName("dest_id") > src_start = integer.setResultsName("src_start")#.setParseAction(make_int) > src_stop = integer.setResultsName("src_stop")#.setParseAction(make_int) > dest_start = integer.setResultsName("dest_start")#.setParseAction(make_int) > dest_stop = integer.setResultsName("dest_stop")#.setParseAction(make_int) > row_8 = oneOf("F C").setResultsName("row_8") > length = integer.setResultsName("length")#.setParseAction(make_int) > percent_id = float.setResultsName("percent_id")#.setParseAction(make_float) > row_11 = integer + Optional(Literal("|") + commaSeparatedList ) > )#.setResultsName("row_11")#.setParseAction(make_int) > result = Word(alphas+"_").setResultsName("result") > row_13 = commaSeparatedList.setResultsName("row_13") > > def make_alilines_status_parser(): > ? ? return alignment + row_1 + src_id + dest_id + src_start + src_stop > + dest_start + dest_stop + row_8 + length + percent_id + row_11 + > result + row_13 > > def parse_alilines_status(ifile): > ? ? alilines = make_alilines_status_parser() > ? ? for l in ifile: > ? ? ? ? yield alilines.parseString( l ) > > However my parser always fails on lines of type 3. Does anyone know > why the Optional part is not working. The commaSeparatedList includes the rest of the line into its last item: >>> commaSeparatedList.parseString("a,b c") (['a', 'b c'], {}) You can fix this by defining your own delimitedList that doesnt accept whitespace, e. g.: >>> delimitedList(Word(alphanums)).parseString("a,b c") (['a', 'b'], {}) Peter From kyosohma at gmail.com Tue Aug 28 10:27:14 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 28 Aug 2007 07:27:14 -0700 Subject: wxpython:how to minimize to taskbar In-Reply-To: <1188310247.587456.103440@i13g2000prf.googlegroups.com> References: <1188310247.587456.103440@i13g2000prf.googlegroups.com> Message-ID: <1188311234.313691.151890@22g2000hsm.googlegroups.com> On Aug 28, 9:10 am, Jimmy wrote: > I'm kinda newbie to python and wxPython. Now I'm confronting a thorny > problem: how can I make my program minimize to the taskbar > represented as an ico, and when there is some message from network > coming, it will pop out? Look at the wxPython demo source code. I found the code I needed in the main.py file under the DemoTaskBarIcon class, which is a subclass of wx.TaskBarIcon. You can't view it by running the demo. You have to open the main.py file itself. On my Windows box, it's found here: C:\Program Files\wxPython2.8 Docs and Demos\demo You'll have to call a handler when you receive a message from the network that basically calls your program's "show" command. Mike From larry.bates at websafe.com Tue Aug 28 19:59:55 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 28 Aug 2007 18:59:55 -0500 Subject: Pythonic way of reading a textfile line by line without throwing an exception In-Reply-To: References: <1ab7b8470708281647g59e685ect371f20aaea30b070@mail.gmail.com> Message-ID: Deivys Ramirez wrote: > Hi everyone, > > I'm a Python newbie but have experience programming PHP and C so i'm > not really new to programming but new to Python. > > What's the "pythonic" way of reading a text file, line by line, > without throwing an exception when there's nothing to be read? > > I've been trying to map my while(!eof(fp)) mindset to the file object > Python gives me when I call open() but have had no good results. > > Regards, > > Deivys Ramirez > Lima-Peru File objects are iterable so you you can just loop on them. fp=open(filename, 'r') for line in fp: # do something with line fp.close() -Larry Bates From steveo at syslang.net Wed Aug 15 10:36:02 2007 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 15 Aug 2007 10:36:02 -0400 (EDT) Subject: Retry: Question about FutureWarning In-Reply-To: <1187183459.675090.194800@w3g2000hsg.googlegroups.com> References: <1187183459.675090.194800@w3g2000hsg.googlegroups.com> Message-ID: Thanks guys, but that's not my question. The question is this: Why does the call to filterwarnings not work if it's placed inside the M1 module? Why do I have to place the call in M4 to make it work? This is more a question about how import works than it is about what the value of -1 is. ;-) On Tuesday, Aug 14th 2007 at 18:49 -0700, quoth Erik Max Francis: =>Steven W. Orr wrote: => =>> M1.py:268: FutureWarning: hex/oct constants > sys.maxint will =>> return positive values in Python 2.4 and up =>> StartTime = safe_dict_get ( dic, 'starttime', 0xFFFFFFFF ) => ... =>> import warnings =>> warnings.filterwarnings('ignore', category=FutureWarning) =>> =>> My question is this: Why can the warning not be shut off by putting the =>> two lines in M1 where the reference exists to 0xFFFFFFFF ? => =>You really don't want to shut off the warning; it means just what it says: => =>Python 2.3.5 (#1, Feb 8 2005, 23:36:23) =>[GCC 3.2.3] on linux2 =>Type "help", "copyright", "credits" or "license" for more information. => >>> 0xffffffff =>:1: FutureWarning: hex/oct constants > sys.maxint will return =>positive values in Python 2.4 and up =>-1 => =>Python 2.4.3 (#1, Mar 29 2006, 17:16:11) =>[GCC 3.2.3] on linux2 =>Type "help", "copyright", "credits" or "license" for more information. => >>> 0xffffffff =>4294967295L => On Wednesday, Aug 15th 2007 at 06:10 -0700, quoth Paul McGuire: =>On Aug 14, 8:49 pm, Erik Max Francis wrote: => =>So if by '0xFFFFFFFF' you meant -1, then change this line to use -1. =>Otherwise, if you really meant 4294967295L, leave it at 0xFFFFFFFF and =>move on. => =>-- Paul => =>-- =>http://mail.python.org/mailman/listinfo/python-list => -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From Brad.Johnson at ballardtech.com Tue Aug 21 16:36:15 2007 From: Brad.Johnson at ballardtech.com (Brad Johnson) Date: Tue, 21 Aug 2007 20:36:15 +0000 (UTC) Subject: IDE for Python References: <46CAB7D4.5070308@gmail.com> Message-ID: Joel Andres Granados gmail.com> writes: > > Hello list: > > I have tried various times to use an IDE for python put have always been > disapointed. Not sure which platform you're on, but I've really liked PyScripter for the Windows platform. From rbysamppi at gmail.com Sun Aug 5 21:28:52 2007 From: rbysamppi at gmail.com (rbysamppi at gmail.com) Date: Mon, 06 Aug 2007 01:28:52 -0000 Subject: Relative-importing * In-Reply-To: <87vebv9yrr.fsf@benfinney.id.au> References: <1185559874.299008.167010@x40g2000prg.googlegroups.com> <871weth2gg.fsf@benfinney.id.au> <46ae3894$0$19609$426a34cc@news.free.fr> <1186200218.666444.254200@q3g2000prf.googlegroups.com> <87vebv9yrr.fsf@benfinney.id.au> Message-ID: <1186363732.188847.48070@q3g2000prf.googlegroups.com> On Aug 4, 7:10 am, Ben Finney wrote: > rbygscrse... at gmail.com writes: > > Yes, I'mimporting* for a reason, a good one, I think. > > Reading your description, I must say I don't see a good reason. > > > I have a set of modules (the number planned to reach about 400) that > > would be dynamically loaded by my program as needed, and they're > > somewhat similar to each other. I wish each of them to import * from > > a certain "parent" module, so that they'll receive whatever > > functions and variables I want all of them to share (using the > > parent module's __all__), which may be overrided by the "child" > > modules at their discretion. Sort of like class inheritance, but I'm > > not doing that because implementing that would be a lot more tedious > > and less elegant. > > It seems to me, based only on this description, that class inheritance > would be far *more* elegant, and much easier to follow when reading > the code. > > If all these functions and other objects are so closely-related that > they form the core of some inheritance-like system, what's so > inelegant about wrapping them in a class so that the inheritance is > explicit in the module where it happens? > > -- > \ "The only tyrant I accept in this world is the still voice | > `\ within." -- Mahatma Gandhi | > _o__) | > Ben Finney Remember that I'm a relative beginner at Python, and actually programming in general, so forgive me if what seems obvious is opaque to me. This project's my way of learning the language. :) I tried a class-based system. The reasons why I would prefer using modules only rather than classes in modules was because I think that it's a little redundant, and this redundancy made it more difficult to grapple with the module/classes' names. This system is for implementing "moves" in a game, of which there will eventually be about 500 when all are implemented. I decided to try to implement each move in a separate module, so we could add and maintain moves to the system at convenience instead of editing a single huge module with hundreds of classes. (Each move is completely separate and unrelated to each other, other than the fact that they share a few variables. In addition, I plan to make it possible to have a user add new move modules at their discretion as extensions to the game.) However, this ended up with a system where every single module had a single class representing the move in it. The name of the class and module have to be the same so that dynamic importing is possible, but the repetition of the name is undesirable, as it increases the chance of errors that might be hard to diagnose. (Because I'm planning to have it possible for a hypothetical user to create his/her own modules, I care a lot about making it as simple as possible.) (In addition, it probably would make the program somewhat slower to have an internal class inside every module, and performance is important to me, as I'm planning to use this project in a future game. These modules are not going to have full-fledged object construction and so forth. I don't want to construct and use objects at all--it seems like a waste of time and memory to me to inherit __new__, __del__, and so on. All that I want these modules to do is to encapsulate varying information and behavior for /other/ objects to use.) It's not a matter of life-and-death for me if I have to use class inheritance. But I think it would suboptimal. But regardless of if it's the "right thing to do", do you all think it's an unintended bug? Thanks again! :) From basilisk96 at gmail.com Fri Aug 24 23:37:18 2007 From: basilisk96 at gmail.com (Basilisk96) Date: Sat, 25 Aug 2007 03:37:18 -0000 Subject: GUI and distrubution In-Reply-To: <1187974418.175783.50860@i38g2000prf.googlegroups.com> References: <1187974418.175783.50860@i38g2000prf.googlegroups.com> Message-ID: <1188013038.882337.97130@q3g2000prf.googlegroups.com> On Aug 24, 12:53 pm, anders wrote: > I have looked att Python onwww.showmedo.com > And after this i start testing writing som program i Python. > But... > > So how is the preferably way to distribute software written i Python > i am NOT into hiding stuff, more a easy way of giving eg friends > a copy of the program without having them installtion a lott > och other stuff. > > My next question is witch is the best GUI to use, also consider > the delivery question above. > > // Anders Indeed a popular set of questions; but what is your platform? Without that information, I'll just give you my biased opinion: wxPython GUI toolkit, py2exe for distribution, and WiX or Inno Setup for the installer. Now, you guess what my platform is ;-) Once you get comfortable writing a few py2exe setup scripts, try Andrea Gavana's GUI2Exe - it makes the distribution process a bit less painful. Of course, you're welcome to search for other stuff as suggested by the other responses. Cheers, Basilisk96 From Werner.Merkl at fujitsu-siemens.com Thu Aug 30 02:38:27 2007 From: Werner.Merkl at fujitsu-siemens.com (Werner) Date: Wed, 29 Aug 2007 23:38:27 -0700 Subject: self extracting zipefile (windows) and (standard module) zipefile In-Reply-To: <1188393780.454058.196360@22g2000hsm.googlegroups.com> References: <1188388421.010643.19050@50g2000hsm.googlegroups.com> <1188393780.454058.196360@22g2000hsm.googlegroups.com> Message-ID: <1188455907.151360.34740@50g2000hsm.googlegroups.com> On 29 Aug., 15:23, kyoso... at gmail.com wrote: > On Aug 29, 6:53 am, Werner wrote: > > > > > > > Hi, > > > I try to read (and extract) some "self extracting" zipefiles on a > > Windows system. The standard module zipefile seems not to be able to > > handle this. > > > >>> fName = r"C:\tmp\mySelfExtratingFile.exe" > > >>> import zipfile > > >>> zipefile.is_zipfile(fName)) > > > False > > > Is there a wrapper or has some one experience with other libaries to > > extract those files? > > > Thanks in advance > > Werner > > Since it's an executable, why not just use the subprocess module? > > I did find this set of scripts, but I don't know if they will help:http://www.example-code.com/python/zip.asp > > I did find how to extract via the command line, which you could use in > conjunction with the subprocess module:http://help.globalscape.com/help/cutezip2/Creating_and_extracting_arc... > > Mike- Zitierten Text ausblenden - > > - Zitierten Text anzeigen - thank you for answer. I found, that WinZip aund 7-ZIP may handle my files (I'm not shure, if it's really zip...) So, I thing I try the 7- zip command line tool (but I'd prefered a Python buildin version) Werner From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Aug 29 03:45:03 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 29 Aug 2007 09:45:03 +0200 Subject: Check for dict key existence, and modify it in one step. In-Reply-To: <1188324850.000752.60230@19g2000hsx.googlegroups.com> References: <1188311810.226363.295500@w3g2000hsg.googlegroups.com> <46d43860$0$428$426a74cc@news.free.fr> <1188324850.000752.60230@19g2000hsx.googlegroups.com> Message-ID: <46d523fb$0$30465$426a74cc@news.free.fr> rodrigo a ?crit : > You're right of course, I was unclear. I wasn't using 'dict' to > override the dict clas, but just as a standin for the example (the > actual dictionary names are varied). I guessed so, but Python's behaviour wrt/ naming can be somewhat surprising for newcomers, and accidentally shadowing builtins (or not builtins FWIW) names is a common pitfall. So better to warn newcomers lurking here !-) From dijkstra.arjen at gmail.com Fri Aug 10 06:31:05 2007 From: dijkstra.arjen at gmail.com (dijkstra.arjen at gmail.com) Date: Fri, 10 Aug 2007 10:31:05 -0000 Subject: Question about properties. In-Reply-To: <1186741289.074717.174370@e16g2000pri.googlegroups.com> References: <1186741289.074717.174370@e16g2000pri.googlegroups.com> Message-ID: <1186741865.755891.207090@i13g2000prf.googlegroups.com> On Aug 10, 12:21 pm, king kikapu wrote: > Hi, > > i read in a book the following code snippet that is dealing with > properties: > > class ProtectAndHideX(object): > def __init__(self, x): > assert isinstance(x, int), '"x" must be an integer!"' > self.__x = ~x > > def get_x(self): > return ~self.__x > > x = property(get_x) > > Can anyone please help me understand what the symbol "~" does here ?? > > Thanks for any help! >>> help(2) .... | __invert__(...) | x.__invert__() <==> ~x hth. Duikboot From horpner at yahoo.com Thu Aug 2 15:06:49 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 02 Aug 2007 19:06:49 GMT Subject: __call__ considered harmful or indispensable? References: Message-ID: On 2007-08-02, Neil Cerutti wrote: > On 2007-08-02, skip at pobox.com wrote: >> I don't personally use __call__ methods in my classes, but I >> have encountered it every now and then here at work in code >> written by other people. The other day I replaced __call__ >> with a more obvious method name, so now instead of executing >> >> obj(foo, bar, baz) >> >> the code in question is >> >> obj.execute(foo, bar, baz) >> >> In this case there was a bug. Depending on inputs, sometimes >> obj initialized to a class, sometimes an instance of that >> class. (I fixed that too while I was at it.) The problem was >> that the use of __call__ obscured the underlying bug by making >> the instance as well as the class callable. >> >> In this particular case it was clearly unnecessary and just >> obfuscated the code. I'm wondering, are there some general >> cases where __call__ methods of a user-defined class are simply >> indispensable? > > In C++ they are called functors, and they are very useful as > surrogate functions with state. I haven't seen them used in the > same way in Python much, because Python has more immediate > solutions to (most of) these problems. > > Here's a (somewhat goofy) example: > > class is_consecutive(object): > def __init__(self, seed, compare=operator.lt): That was supposed to be operator.le, not lt. I forgot to repaste after fixing that bug. > self.last_value = seed > self.compare = compare > def __call__(self, total, value): > if total is False: > return False > lv = self.last_value > self.last_value = value > return self.compare(lv, value): > > a = range(15) > >>>> reduce(is_consecutive(0), a) > True >>>> reduce(is_consecutive(0), a + [1,2]) > False > > It's been a while since I had to be in the STL mindset, so I > couldn't think of a better example. > -- Neil Cerutti The pastor will preach his farewell message, after which the choir will sing, "Break Forth Into Joy." --Church Bulletin Blooper From apt.shansen at gmail.com Tue Aug 21 00:31:07 2007 From: apt.shansen at gmail.com (Stephen Hansen) Date: Mon, 20 Aug 2007 21:31:07 -0700 Subject: wxpython thread exception crash In-Reply-To: <13ckp4nj0kt6583@corp.supernews.com> References: <13ckp4nj0kt6583@corp.supernews.com> Message-ID: <7a9c25c20708202131i4de63f3du136fa5b43e57b265@mail.gmail.com> On 8/20/07, [david] wrote: > > What am I doing wrong? > I'm trying to capture stdErr in a multi-threaded program. You can't reliably access the GUI anywhere except in the main thread; you're printing to stderr from the worker thread, and thus its writing to the GUI control, and that action is occuring within the worker thread. Sometimes it'll work. Eventually it'll always fail. Try adjusting the write method of RedirectText to: def write(self,string): wx.CallAfter(self.out.WriteText, string) "wx.CallAfter" is a convienence function to call from a worker thread "into" the GUI thread and execute the specified method with the given options. It makes modifying the GUI very easy. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Tue Aug 7 05:19:09 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Aug 2007 09:19:09 GMT Subject: How to use C enum in Python CTypes? References: <1186462639.872254.25660@z24g2000prh.googlegroups.com> <5hqgogF3ldifeU1@mid.uni-berlin.de> <1186478018.409193.188130@e9g2000prf.googlegroups.com> Message-ID: <5hqrodF3ldifeU5@mid.uni-berlin.de> On Tue, 07 Aug 2007 02:13:38 -0700, rozniy wrote: > On Aug 7, 2:11 pm, Marc 'BlackJack' Rintsch wrote: >> On Tue, 07 Aug 2007 04:57:19 +0000, rozniy wrote: >> > This site >> >http://python.net/crew/theller/ctypes/tutorial.html#bugs-todo-and-non... >> >> > says that enumeration types is not implemented, >> > "Enumeration types are not implemented. You can do it easily yourself, >> > using c_int as the base class." >> >> I would just define constants: >> >> (OLSS_AD, >> OLSS_DA, >> OLSS_DIN, >> OLSS_DOUT, >> OLSS_SRL, >> OLSS_CT) = map(ctypes.c_int, xrange(6)) > > Wouldn't that assign integer values 0 to 5 to the things? Yes. > I don't know if it'll give me the correct results. It should. Enumerations in C are more or less just integer constants. Ciao, Marc 'BlackJack' Rintsch From kyosohma at gmail.com Fri Aug 31 11:25:03 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 31 Aug 2007 08:25:03 -0700 Subject: Question involving a Python app... In-Reply-To: <1188571968.529938.55770@i38g2000prf.googlegroups.com> References: <1188571968.529938.55770@i38g2000prf.googlegroups.com> Message-ID: <1188573903.389912.93530@r29g2000hsg.googlegroups.com> On Aug 31, 9:52 am, sberry wrote: > I am a Flash developer (also a Python dev) and I use an editor called > SEPY Actionscript Editor. The latest release version does not support > Flash CS3, so I downloaded the source from subversion, edited it, and > recompiled to get a version that worked with CS3. Right now, in order > to run the program I have to do a command line "python main.pyw." > > The question now is this: > Others in my company would like to use the version I have compiled > without installing Python, wxPython, 4suite, antlr, and a whole bunch > of other Python libs. So, how do I create an executable (on Windows) > to install the program so it will run without the aforementioned > framework being installed? > > I know this isn't really an entirely "Pythonic" question, but this > group has always been very helpful in the past. > > Thanks I find GUI2exe to be very easy to use. It's just py2exe with a GUI frontend. See http://xoomer.alice.it/infinity77/main/GUI2Exe.html for more information. Mike From hancock.robert at gmail.com Mon Aug 13 19:03:45 2007 From: hancock.robert at gmail.com (milan_sanremo) Date: Mon, 13 Aug 2007 23:03:45 -0000 Subject: chmod g+ Equivalent In-Reply-To: <1i2t81z.1f4cmrhu1sy8iN%raims@dot.com> References: <1187042290.821786.178420@19g2000hsx.googlegroups.com> <1i2t81z.1f4cmrhu1sy8iN%raims@dot.com> Message-ID: <1187046225.596726.97390@g4g2000hsf.googlegroups.com> On Aug 13, 6:33 pm, ra... at dot.com (Lawrence Oluyede) wrote: > milan_sanremo wrote: > > I've read the documentation on os.chmod() and can implement all the > > standard commands, but what is the syntax for the equivalent of chmod g > > + to set the group id? > > chmod() [1] takes as the second parameter a bitwise or-ed combination of > a series of values. If you look at chmod's man page ("man 2 chmod" on > the shell) you can see the following values for the group id (I have OSX > so the actual value may be different on your OS): > > #define S_IRWXG 0000070 /* RWX mask for group */ > #define S_IRGRP 0000040 /* R for group */ > #define S_IWGRP 0000020 /* W for group */ > #define S_IXGRP 0000010 /* X for group */ > > So you just have to OR them to accomplish your goal. > I understand that for setting the standard rwx permissions, but how do these affect the ability to change the setgid bit? Under Solaris you cannot do it from the command line in absolute mode, so perhaps it is not possible in python I'm trying to get the equivalent of 'chmod g+' not something like 'chmod 755'. From pyth0nc0d3r at gmail.com Sun Aug 26 15:29:47 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Sun, 26 Aug 2007 14:29:47 -0500 Subject: the del function Message-ID: import random constant_array = "" red = blue = grey = black = 0 r1 = r2 = r3 = r4 = 1 blu1 = blu2 = blu3 = blu4 = 2 g1 = g2 = g3 = g4 = 3 bla1 = bla2 = bla3 = bla4 = 4 single_players = [r1,r2,r3,r4,blu1,blu2,blu3,blu4,bla1,bla2,bla3,bla4,g1,g2,g3,g4] _red = [1,1,1,1] #print random.randint(0,10 #red team x = 0 while x < 4: array = single_players[4:17] length = len(array) - 1 ray = random.randint(0,length) _red[x] = array[ray] del array[ray] print array x = x + 1 print _red Ok I'm working on a game function where at the end of the game it remix's the teams. For some odd reason the del array[ray] isn't actually deleting the array item in the list I get the following output: C:\Documents and Settings\program\Desktop\python\pygame>remix.py [2, 2, 2, 4, 4, 4, 4, 3, 3, 3, 3] [2, 2, 2, 4, 4, 4, 4, 3, 3, 3, 3] [2, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3] [2, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3] [2, 2, 4, 4] The _red function is fine, but the del function isn't working. What did I do wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jdvolz at gmail.com Wed Aug 22 14:02:59 2007 From: jdvolz at gmail.com (Josh Volz) Date: Wed, 22 Aug 2007 11:02:59 -0700 Subject: Error with long running web spider In-Reply-To: <1187805496.980676.271830@l22g2000prc.googlegroups.com> References: <1187805496.980676.271830@l22g2000prc.googlegroups.com> Message-ID: <1187805779.572023.297350@l22g2000prc.googlegroups.com> On Aug 22, 10:58 am, Josh Volz wrote: I'm running this program on Windows XP, using Python 2.5. I'm using Active State Komodo IDE 4.0 as the run environment. Thanks, J. > Hi everyone: > > I have a spider that is relatively long running (somewhere between > 12-24 hours). My problem is that I keep having an issue where the > program appears to freeze. Once this freezing happens the activity of > the program drops to zero. No exception is thrown or caught. The > program simply stops doing anything. It even stops printing out its > activity to stdout. The program itself appears to run in about 14 > megs of memory. Basically, the program looks up pages on a particular > website, and then reads the HTML of those pages, parses it (lots of > long regular expressions are used), and saves the found information to > an object (which is later translated to SQL and the SQL is written to > a file). > > I've actually had this same problem with several long running Python > programs. Any ideas? > > Thanks in advance. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Aug 19 17:34:36 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 19 Aug 2007 23:34:36 +0200 Subject: Development for dual core machine References: <1187515287.226791.186700@j4g2000prf.googlegroups.com> <7x3ayfsagr.fsf@ruckus.brouhaha.com> Message-ID: <5irrbdF3r2m8aU3@mid.individual.net> Paul Rubin wrote: > Python threading doesn't support multiple CPU's because of the > GIL. :s/support/take full advantage of/ Regards, Bj?rn -- BOFH excuse #46: waste water tank overflowed onto computer From http Mon Aug 6 11:06:06 2007 From: http (Paul Rubin) Date: 06 Aug 2007 08:06:06 -0700 Subject: Tkinter or wxpython? References: <1186410331.905174.21370@q3g2000prf.googlegroups.com> <7xps204tin.fsf@ruckus.brouhaha.com> <1186411846.690086.120280@z24g2000prh.googlegroups.com> Message-ID: <7xps20push.fsf@ruckus.brouhaha.com> kyosohma at gmail.com writes: > I agree that making web apps is probably the way of the future. > However, there are lots of security risks involved with it that need > to be understood. One of the problems that raging is about AJAX, see > here: http://arstechnica.com/news.ars/post/20070802-security-experts-warn-developers-about-the-risks-of-premature-ajax-ulation.html Yes, do be careful of ajax, and of internet programming in general. However, the usual use of a desktop app is deployment within one company, so if you write it as a web app you can ease the security issue by firewalling the server so that it can't be accessed through the outside internet. That still makes deployment a lot easier, since there are zero desktop installations required, and you can upgrade the software whenever you want at the server side. From vodela.sai at gmail.com Thu Aug 2 13:33:25 2007 From: vodela.sai at gmail.com (Rohan) Date: Thu, 02 Aug 2007 17:33:25 -0000 Subject: Email Message-ID: <1186076005.729346.327140@z24g2000prh.googlegroups.com> I was wondering if there could be an arrangement where a file could be attached and send as an email. For ex f = open(add.txt,w) f.write('python') f.close() Now I would like to send an email with add.txt as an attachment, is it possible ? some one give me a pointer towards this. From zzbbaadd at aol.com Thu Aug 30 02:44:33 2007 From: zzbbaadd at aol.com (zzbbaadd at aol.com) Date: Wed, 29 Aug 2007 23:44:33 -0700 Subject: list index() Message-ID: <1188456273.102334.48660@50g2000hsm.googlegroups.com> What's with the index() function of lists throwing an exception on not found? Let's hope this is rectified in Python 3. If nothing else, add a function that doesn't throw an exception. There are a million situations where you can have an item not be in a list and it is not an exception situation. From arkanes at gmail.com Fri Aug 31 19:56:03 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 31 Aug 2007 18:56:03 -0500 Subject: Python Unicode to String conversion In-Reply-To: <1188600916.528901.189680@d55g2000hsg.googlegroups.com> References: <1188600916.528901.189680@d55g2000hsg.googlegroups.com> Message-ID: <4866bea60708311656p26aa0644w4ad71ab019ff5eb5@mail.gmail.com> On 8/31/07, thijs.braem at gmail.com wrote: > Hi everyone, > > I'm having quite some troubles trying to convert Unicode to String > (for use in psycopg, which apparently doesn't know how to cope with > unicode strings). > > The error I keep having is something like this: > ERREUR: S?quence d'octets invalide pour le codage ?UTF8? : 0xe02063 > > (sorry, locale is french, it means "byte sequence invalid for encoding > <>", the value is probably an e with one of the french accents) > > I've found lots of stuff about this googling the error, but I don't > seem to be able to find a "works always"-function just to convert a > unicode variable back to string... encode(). You didn't post the code that was failing, I can encode that value into UTF-8 (and unless I'm very much mistaken, you should be able to encode any unicode string to UTF-8). From sbellon at sbellon.de Tue Aug 7 18:28:52 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Wed, 8 Aug 2007 00:28:52 +0200 Subject: Destruction of generator objects Message-ID: <20070808002852.6228ae91@cube.tz.axivion.com> Hi all, I'm generating a binding from Python to C using SWIG. On the C side I have iterators over some data structures. On the Python side I currently use code like the following: def get_data(obj): result = [] iter = make_iter(obj) while more(iter): item = next(iter) result.append(item) destroy(iter) return result Now I'd like to transform it to a generator function like the following in order to make it more memory and time efficient: def get_data(obj): iter = make_iter(obj) while more(iter): yield next(iter) destroy(iter) But in the generator case, I have a problem if the generator object is not iterated till the StopIteration occurs, but if iteration is stopped earlier. In that case, the C iterator's destroy is not called, thus the resource is not freed. Is there a way around this? Can I add some sort of __del__() to the generator object so that in case of an early destruction of the generator object, the external resource is freed as well? I'm looking forward to hearing your hints! -- Stefan Bellon From wpdster at gmail.com Tue Aug 7 09:16:14 2007 From: wpdster at gmail.com (Patrick Doyle) Date: Tue, 7 Aug 2007 09:16:14 -0400 Subject: Importing * From a Package In-Reply-To: <20070806143253.4947.1097304571.divmod.quotient.19513@ohm> References: <20070806143253.4947.1097304571.divmod.quotient.19513@ohm> Message-ID: > There's no reliable way to differentiate between names which you defined > using something other than an import statement, names you defined with an > import statement with the intent of publishing them as part of your external > API, and names you defined with an import statement which you only intended > to use internally. So Python doesn't even try to differentiate betweem them. > ok, that makes sense > >"[It] imports whatever names are defined in the package [including] > >any submodules of the package that were explicitly loaded by previous > >import statements." This is the part that has me confused -- why does "from package import *" go on to import names that were explicitly loaded by previous import statements? Here is a contrived example (contrived by virtue of culling it out of an existing code base I was reorganizing into packages when I stumbled across this: Directory structure: ./ ./SDRGen ./SDRGen/__init__.py ./SDRGen/TFGenerator.py The SDRGen/__init__.py file is empty. The SDRGen/TFGenerator.py file contains the following 2 lines: class TFGenerator: pass Now, at the python prompt I type (and get) the following: >>> from SDRGen.TFGenerator import * >>> TFGenerator >>> from SDRGen import * >>> TFGenerator <46d674c2$0$417$426a34cc@news.free.fr> <1188496588.750629.208100@g4g2000hsf.googlegroups.com> <1188498073.997168.282420@q5g2000prf.googlegroups.com> Message-ID: In message , Carsten Haese wrote: > On Thu, 2007-08-30 at 11:21 -0700, zzbbaadd at aol.com wrote: > >> I wish they were not >> getting rid of dict.has_key() in Python 3, which I prefer to IN. > > That wish will only come true if you maintain your own fork of Python 3. > has_key() will go away, period. It has been made obsolete by "in", which > is faster and more concise. And is also a backdoor way of introducing non-virtual methods into Python, is it not. From arkanes at gmail.com Wed Aug 8 10:10:29 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 8 Aug 2007 09:10:29 -0500 Subject: twisted - locking threads when deferToThread is used In-Reply-To: <4866bea60708080709v797c5a67w158f6f988ef5c304@mail.gmail.com> References: <46B99CCB.1070304@iptel.org> <4866bea60708080709v797c5a67w158f6f988ef5c304@mail.gmail.com> Message-ID: <4866bea60708080710ma83a713p622c2997df812a6a@mail.gmail.com> On 8/8/07, Chris Mellon wrote: > On 8/8/07, Ladislav Andel wrote: > > Hi, > > I'm writing an application which will be periodically testing servers. > > I will have a global list of these servers(domain names) and need to do > > few tasks. > > 1) DNS checks - I will use asynchronous twisted-names for it > > - in case there is a difference comparing to the list it should update > > the list(then also in DB) > > 2) ICMP pings - should be also possible to do it asynchronously > > 3) Blocking function which will be pinging with SIP requests > > - here I will use function deferToThread to make it non-blocking. > > > > Questions: > > 1) How do I lock each thread when writing to a global list in twisted? > > 2) How will I put together all three results mentioned above in the > > global list > > - is it by using function callLater ? > > 3) Could you help me with a rough skeleton of this application, please? > > > > Thank you, > > Lada > > > > > deferToThread returns the result of the passed function in a Deferred. > Callbacks and errbacks will be run in the main event loop, so you > don't need to worry about thread safety of the callbacks, just of the > function itself. > > The basic model would look something like this: > > def querySIP(what): > return sip.query(what) #native, *threadsafe*, blocking call > > sipquery = reactor.deferToThread(querySIP, what) > sipquery.addCallback(lambda result: sip_results.append(result)) > sipquery.addErrback(log.err) > And, of course, deferToThread is a function in the twisted.internet.threads module, not a method of the reactor. From claird at lairds.us Fri Aug 3 09:35:14 2007 From: claird at lairds.us (Cameron Laird) Date: Fri, 3 Aug 2007 13:35:14 +0000 Subject: XML Processing References: <1186080339.344993.167670@z24g2000prh.googlegroups.com> <1186081434.012668.206770@z24g2000prh.googlegroups.com> <1186082619.193097.207650@x40g2000prg.googlegroups.com> Message-ID: In article <1186082619.193097.207650 at x40g2000prg.googlegroups.com>, wrote: >On Aug 2, 2:09 pm, Jay Loden wrote: >> kyoso... at gmail.com wrote: >> > On Aug 2, 1:45 pm, Roman wrote: >> >> Is there a package that converts a string that contains special >> >> characters in xml to to literal value. For instance, converts >stringhttp://myhome/¶mtohttp://myhome/¶m. >> >> >> Thanks in advance >> >> > I've seen examples using the HTMLgen module. But here's another script >> > I just found: >> >> >http://mail.python.org/pipermail/python-list/1999-November/016814.html >> >> > I would think that you could use regular expressions too. >> >> > Mike >> >> I would reccommend against using the example above or using regular >expressions, since both are likely to miss corner cases, and the stdlib >has an encode function that's already designed for this task >> >> http://docs.python.org/lib/module-xml.sax.saxutils.html >> >> The encode() function in xml.sax.saxutils also is extensible, should >you run into any entities that it fails to escape in the current >implementation. >> >> -Jay > >Yes, I am an idiot. > ! Unproved, as Scotsmen are wont to say. This and similar questions arise frequently enough that I recommend for those who want to pursue the subject. From laurent.pointal at limsi.fr Thu Aug 2 03:18:05 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Thu, 02 Aug 2007 09:18:05 +0200 Subject: Python IMAP web-access In-Reply-To: <46b0c675$0$90272$14726298@news.sunsite.dk> References: <46b0c675$0$90272$14726298@news.sunsite.dk> Message-ID: Damjan a ?crit : > Is there some project that implements web access to an IMAP store? > > Maybe something AJAXy like http://roundcube.net/?? I dont know if this fill your need, but in my Python bookmarks, for webmail I have a reference to NiMail (http://www.nimail.org/). A+ Laurent. From klove at tax.ok.gov Wed Aug 29 16:33:02 2007 From: klove at tax.ok.gov (Kenneth Love) Date: Wed, 29 Aug 2007 15:33:02 -0500 Subject: Accessing docstrings at runtime? References: <011b01c7ea69$95512fe0$e6003dcc@worf2> <4866bea60708291128o29803077r5fe06249ab6cc29c@mail.gmail.com> Message-ID: <012701c7ea7b$cc285220$e6003dcc@worf2> On 08/29/07, Chris Mellon wrote: > On 8/29/07, Kenneth Love wrote: >> How do I print the docstring for a class property? >> >> [[[ SNIP EXAMPLE ]]] >> >> What am I doing wrong? >> > > You're looking at an instance, not at the class. y.x is going through > the descriptor lookup and is returning the string, so the __doc__ is > the the __doc__ of the string object, as you see. > > If you want to look at the property directly, look it up in the class > object: > > C.x.__doc__ That worked. Thanks! Kenneth From pyth0nc0d3r at gmail.com Tue Aug 28 18:21:29 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Tue, 28 Aug 2007 17:21:29 -0500 Subject: Okay learning python is somewhat hard. In-Reply-To: <46D49A7B.8010600@sdf.lonestar.org> References: <46D49A7B.8010600@sdf.lonestar.org> Message-ID: Yep I'll keep hacking at it aye :D. Also I'll do some searching on the new styled classes. On 8/28/07, J. Cliff Dyer wrote: > > A couple thoughts: > > First, your class looks like it describes the line, not just the > midpoint. Your method calculates the midpoint of that line, so let the > class be a line class. That way you can add other useful methods to it: > > Line.midpoint() > Line.length() > Line.slope() > > etc. > > Second, you're losing fractions because all of your code deals with > integers. Integer division rounds down. So instead of dividing by 2, > divide by 2.0, to force the calculation into floating point. Better yet > (conceptually speaking), explicitly cast your input to floating point > variables: self.x1 = float(x1), etc. > > Third. ALWAYS use new style classes. > > class Line(object): > > not > > class Line: > > Otherwise, it looks like you're on your way. Keep hacking at it. > > Cheers, > Cliff > > > > Lamonte Harris wrote: > > Since I can't really focus on PROJECTS[since I don't know much python > > I can't do any projects because all my projects are BIG], So I decided > > to work on some problems I've gotten from school from started > > geometry, So I attempted to make a script to get the midpoint of a > > line segment using the formula giving: > > > > [1 and 2 are subscripts] > > > > X1 + X2 > > ----------- = mid pt. (x) > > 2 > > > > Y1 + Y2 > > ----------- = mid pt. (y) > > 2 > > > > So i tried coding the following script. > > > > #MIDPOINT OF A LINE > > class midpoint: > > def __init__(self,x1,x2,y1,y2): > > self.x1 = x1 > > self.x2 = x2 > > self.y1 = y1 > > self.y2 = y2 > > self.dictionary = {'x' : '','y' : ''} > > self.calculate_mid_point() > > def calculate_mid_point(self): > > X = self.x1 + self.x2 > > X = X/2 > > self.dictionary['x'] = X > > Y = self.y1 + self.y2 > > Y = Y/2 > > self.dictionary['y'] = Y > > c_x = -2 > > c_y = -2 > > d_x = 4 > > d_y = 3 > > midpoint_ = midpoint(c_x,d_x,c_y,d_y) > > print midpoint_.dictionary > > > > It works and all, but I can't get the fraction or decimal from the > > output :S > > > > Output: > > {'y': 0, 'x': 1} > > > > On my paper the real output is: > > x = 1 > > y = 1/2 > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From aboudouvas at panafonet.gr Fri Aug 10 11:04:07 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Fri, 10 Aug 2007 08:04:07 -0700 Subject: The Future of Python Threading In-Reply-To: <87ir7n4fps.fsf@benfinney.id.au> References: <1186740111.918048.77920@d30g2000prg.googlegroups.com> <87ir7n4fps.fsf@benfinney.id.au> Message-ID: <1186758247.986802.81990@e9g2000prf.googlegroups.com> > All of which is avoided by designing the program to operate as > discrete processes communicating via well-defined IPC mechanisms. Hi Ben, i would like to learn more about this, have you got any links to give me so i can have a look ? From johnmasters at oxtedonline.net Wed Aug 1 17:28:40 2007 From: johnmasters at oxtedonline.net (John K Masters) Date: Wed, 1 Aug 2007 22:28:40 +0100 Subject: Wing IDE for Python v. 3.0 beta1 released In-Reply-To: <46AF8ED7.2070206@wingware.com> References: <46AF8ED7.2070206@wingware.com> Message-ID: <20070801212840.GA25065@spookie1.spookiegate> On 15:34 Tue 31 Jul , Wingware wrote: > Hi, > > I'm happy to announce the first beta release of Wing IDE 3.0. It is > available from http://wingware.com/wingide/beta > If their support for paid customers is anything like their support for prospective customers then I would leave well alone. I have been trying wing for a few days but have noticed that auto-completion does not work on all modules. I submitted this to wing and was told that probably my PYTHONPATH was wrong. I subsequently submitted a question about the licensing, i.e. whether I could use wing on a home setup using Debian Etch, where I develop my apps, and a work setup, using Debian Etch, with no net access. So far I have had no response Regards, John From carsten at uniqsys.com Fri Aug 17 00:02:11 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 17 Aug 2007 00:02:11 -0400 Subject: How to say $a=$b->{"A"} ||={} in Python? In-Reply-To: <1187320510.165621.224150@l22g2000prc.googlegroups.com> References: <1187303750.590497.208060@x40g2000prg.googlegroups.com> <1187311999.880853.135780@j4g2000prf.googlegroups.com> <1187320510.165621.224150@l22g2000prc.googlegroups.com> Message-ID: <20070817035900.M74081@uniqsys.com> On Fri, 17 Aug 2007 03:15:10 -0000, beginner wrote > On Aug 16, 9:32 pm, Carsten Haese wrote: > > What is the best solution in Perl need not be the best solution in > > Python. In Python you should just use a tuple as your dict key, i.e. > > a[k1,k2] = v, unless you have some other constraints you're not telling > > us. > > > > HTH, > > > > -- > > Carsten Haesehttp://informixdb.sourceforge.net > > I use tuples this way all the time. It is indeed very neat. But it > is not a replacement for double hash-table. If I want to retrieve > information just by K1, it is not efficient to index on (K1, K2). If you have to look up all values associates with k1 and any k2, you're right, that's not efficient. That would fall under "other constraints you're not telling us." I'm not a mind reader. -Carsten From orsenthil at gmail.com Sat Aug 4 23:35:11 2007 From: orsenthil at gmail.com (Phoe6) Date: Sun, 05 Aug 2007 03:35:11 -0000 Subject: Comparing RFC1123 based Dates In-Reply-To: <1186281836.970400.103490@i13g2000prf.googlegroups.com> References: <1186281836.970400.103490@i13g2000prf.googlegroups.com> Message-ID: <1186284911.988459.324690@e16g2000pri.googlegroups.com> Phoe6 wrote: > I would like to parse RFC 1123 date format and compare two dates. I > find that > datetime module does not specifically confirms to any RFC. Any > suggestions as how I can handle the RFC 1123 date format using > standard libraries before I go to re based parsing? Well, >>> import time >>> timeobj = time.strptime("Thu, 01 Dec 1994 16:00:00 GMT","%a, %d %b %Y %H:%M:%S %Z") was easy. Thanks, Senthil From steve at holdenweb.com Tue Aug 28 19:16:31 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 28 Aug 2007 19:16:31 -0400 Subject: Gmane's been quiet ... Message-ID: ... so I was wondering if it's just me who hasn't seen any postings today? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From aboudouvas at panafonet.gr Sat Aug 11 07:53:11 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Sat, 11 Aug 2007 04:53:11 -0700 Subject: Ipc mechanisms and designs. In-Reply-To: References: <1186760055.658942.116300@x40g2000prg.googlegroups.com> Message-ID: <1186833191.686023.50970@57g2000hsv.googlegroups.com> On Aug 10, 10:33 pm, Nikita the Spider wrote: > In article <1186760055.658942.116... at x40g2000prg.googlegroups.com>, > king kikapu wrote: > > > > Hi King Kikapu > There's a shared memory module for Python, but it is *nix only, I'm > afraid. I realize you said "mainly Windows" but this module seems to do > what you want so maybe you can work out a creative solution. > > http://NikitaTheSpider.com/python/shm/ Yes, i am currently developing mainly on windows but a cross-platform solution would surely interests me. I will check it out this! @Alex: Thanks, it looks very-very interesting... From jeff_barish at earthlink.net Tue Aug 28 16:23:41 2007 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Tue, 28 Aug 2007 14:23:41 -0600 Subject: Biased random? References: Message-ID: Ivan Voras wrote: > Hi, > > I have a list of items, and need to choose several elements from it, > "almost random". The catch is that the elements from the beginning > should have more chance of being selected than those at the end (how > much more? I don't care how the "envelope" of probability looks like at > this point - can be linear). I see that there are several functions in > Python standard libraries for various distribution, but is there an easy > pythonic way to make them do what I need? If you take the difference between two uniformly distributed random variables, the probability density function forms an isosceles triangle centered at 0. Take the absolute value of that variable and the pdf is a straight line with maximum value at 0 tapering to 0 at max. Thus, z = abs(randint(0, max) - randint(0, max)) ought to do the trick. -- Jeffrey Barish From antroy at gmail.com Wed Aug 15 08:03:17 2007 From: antroy at gmail.com (Ant) Date: Wed, 15 Aug 2007 05:03:17 -0700 Subject: buggie in else syntax ? In-Reply-To: References: <46C21D70.8000409@gmail.com> <200708150138.57816.thomas@jollans.com> Message-ID: <1187179397.682278.214710@50g2000hsm.googlegroups.com> On Aug 15, 9:40 am, stef mientki wrote: > Thomas Jollans wrote: ... > else: JSM(230) ; \ > if b>3: <== SYNTAX ERROR pointing to the "f" of if This is equivalent to: > else: JSM(230) ; if b>3: If statements (any compund statements in fact such as for loops etc) *must* start on a new line (with indentation as necessary): http://docs.python.org/ref/compound.html -- Ant... http://antroy.blogspot.com/ From 55rebels at gmail.com Thu Aug 16 09:33:21 2007 From: 55rebels at gmail.com (55rebels at gmail.com) Date: Thu, 16 Aug 2007 06:33:21 -0700 Subject: Python Book Recommendations In-Reply-To: References: <1b31ae500708141638w77614014o6f382d0389bc69df@mail.gmail.com> <1187191803.845011.30400@x35g2000prf.googlegroups.com> Message-ID: <1187271201.262706.132080@i38g2000prf.googlegroups.com> On Aug 15, 11:47 pm, Laurent Pointal wrote: > Azazello a ?crit : > > > > > On Aug 15, 7:47 am, "Shawn Milochik" wrote: > >> If I could have only one book, I would buy "Core Python, Second > >> Edition," by Wesley Chun. > > >> For the record, I own: > >> Core Python, Second Edition (great) > >> wxPython in Action (haven't used yet) > >> Beginning Python (barely used) > >> Python in a Nutshell (use as a reference, although interactive python > >> dir() is more useful) > >> Dive into Python (great book) > >> Python Cookbook (great book) > >> Python Pocket Reference (not very useful) > >> Python Phrasebook (I love the Phrasebook series, but this isn't a > >> necessary book) > > > I would like to add: > > > Foundations of Python Network Programming > > There was a review about this one on slashdot:http://books.slashdot.org/books/04/10/13/1815209.shtml?amp;tid=192&am... > > > > > I also use the Python Essential Reference. (although all of the > > information is probably online it's nice to have a solid paper > > reference) Byte of python - online book. Best I've seen yet, online anyway. Especially great for newbies... like me. Wish I could buy a hard copy. From conra2004 at yahoo.com Mon Aug 13 06:07:46 2007 From: conra2004 at yahoo.com (yadin) Date: Mon, 13 Aug 2007 03:07:46 -0700 Subject: negative polar axis Message-ID: <1186999666.642856.16820@19g2000hsx.googlegroups.com> hi! how can i do polar plot in python with negative axes that is the value of the magnitude is negative From hadronquark at googlemail.com Mon Aug 6 06:32:56 2007 From: hadronquark at googlemail.com (Hadron) Date: Mon, 06 Aug 2007 12:32:56 +0200 Subject: Emacs + python. References: <00tzrdm1zd.fsf@googlemail.com> Message-ID: Hadron writes: > Sorry to repeat, but I had to reinstall and lost all my news. > > I am looking for pointers on using emacs with python. I use emacs v > 22.0.91 (Ubuntu snapshot). > > It comes with its own python mode. > > The problem is that the debugger just hangs when I start it. The > interpreter runs fine. Any ideas? > > What versions of python.el or python-mode.el or ..... are you using and > why? > > Many thanks for any pointers. I upgraded to emacs 23 from http://peadrop.com/blog/2007/01/06/pretty-emacs/ and it works fine now. Crosspost & Followup-To: gnu.emacs.help From kib2 at free.fr Sun Aug 26 15:20:09 2007 From: kib2 at free.fr (tool69) Date: Sun, 26 Aug 2007 21:20:09 +0200 Subject: New UI Toolkit In-Reply-To: <1188146822.129605.160560@22g2000hsm.googlegroups.com> References: <1188146822.129605.160560@22g2000hsm.googlegroups.com> Message-ID: <46d1d363$0$404$426a74cc@news.free.fr> Gerdus van Zyl a ?crit : Seems very promising. But I'm afraid with the Swing-like interface, i.e : did you use the same widget positionning ? From deets at nospam.web.de Wed Aug 1 04:50:49 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 01 Aug 2007 10:50:49 +0200 Subject: standalone process to interact with the web References: <1185899130.331170.151980@e16g2000pri.googlegroups.com> Message-ID: <5havr9F3inuj7U1@mid.uni-berlin.de> beginner wrote: > Hi Everyone, > > I am looking for a way to allow a standalone python process to easily > interactive with a few web pages. It has to be able to easily receive > requests from the web and post data to the web. > > I am thinking about implementing a standalone soap server, but I am > not sure which library is good. > > Any suggestions? Forget SOAP. Use XMLRPC. SOAP is bloated, not to interoperable and the last time I checked (has been a while though) the python-implementations were troublesome. http://wanderingbarque.com/nonintersecting/2006/11/15/the-s-stands-for-simple Diez From arkanes at gmail.com Fri Aug 31 12:12:22 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 31 Aug 2007 11:12:22 -0500 Subject: So what exactly is a complex number? In-Reply-To: <1188576174.3479.9.camel@dot.uniqsys.com> References: <1188576174.3479.9.camel@dot.uniqsys.com> Message-ID: <4866bea60708310912q2c8ec987i37f679596e3926e7@mail.gmail.com> On 8/31/07, Carsten Haese wrote: > On Thu, 2007-08-30 at 20:11 -0500, Lamonte Harris wrote: > > Like in math where you put letters that represent numbers for place > > holders to try to find the answer type complex numbers? > > Is English your native language? I'm having a hard time decoding your > question. > I'm pretty sure he was describing middle school algebra. From willshak at 00hvc.rr.com Tue Aug 21 08:10:53 2007 From: willshak at 00hvc.rr.com (willshak) Date: Tue, 21 Aug 2007 08:10:53 -0400 Subject: Latest models of Gibson guitars In-Reply-To: References: <1187544898.289948.322160@22g2000hsm.googlegroups.com> <190820071924351381%rag@nospam.techline.com> <1187623025.845370.251530@x40g2000prg.googlegroups.com> Message-ID: <13cllic3qnulb28@news.supernews.com> on 8/20/2007 5:51 PM Lew said the following: > RickH wrote: >> On Aug 19, 9:24 pm, Randall Ainsworth >> wrote: >>> In article , Hermit >>> >>> wrote: >>>> How does the image quality compare with a DSLR? >>> Depends on whether it's a Paul or a Strat. >> >> A Strat is a Fender, but I'd rather win a Gibson es175. > > Please do not include comp.lang.java.programmer in this discussion, as > it is waaaay off topic. > Don't feel like the Lone Ranger! It is off topic for every newsgroup to which it was posted. -- Bill In Hamptonburgh, NY To email, remove the double zeroes after @ From shahargs at gmail.com Tue Aug 7 05:34:37 2007 From: shahargs at gmail.com (shahargs at gmail.com) Date: Tue, 07 Aug 2007 02:34:37 -0700 Subject: get wikipedia source failed (urrlib2) In-Reply-To: <1186476847.728759.166610@o61g2000hsh.googlegroups.com> References: <1186476847.728759.166610@o61g2000hsh.googlegroups.com> Message-ID: <1186479277.356613.111630@r34g2000hsd.googlegroups.com> On 7 , 11:54, shaha... at gmail.com wrote: > Hi, > I'm trying to get wikipedia page source with urllib2: > usock = urllib2.urlopen("http://en.wikipedia.org/wiki/ > Albert_Einstein") > data = usock.read(); > usock.close(); > return data > I got exception because HTTP 403 error. why? with my browser i can't > access it without any problem? > > Thanks, > Shahar. This source works fine for other site. the problem is in wikipedia. is someone now any solution for this problem? From jmtulloss at gmail.com Thu Aug 9 15:09:35 2007 From: jmtulloss at gmail.com (Justin T.) Date: Thu, 09 Aug 2007 19:09:35 -0000 Subject: Threaded Design Question In-Reply-To: <1186683909.797328.68770@i13g2000prf.googlegroups.com> References: <1186683909.797328.68770@i13g2000prf.googlegroups.com> Message-ID: <1186686575.192491.82820@e16g2000pri.googlegroups.com> On Aug 9, 11:25 am, half.ital... at gmail.com wrote: > > Here's how I have it designed so far. The main thread starts a > Watch(threading.Thread) class that loops and searches a directory for > files. It has been passed a Queue.Queue() object (watch_queue), and > as it finds new files in the watch folder, it adds the file name to > the queue. > > The main thread then grabs an item off the watch_queue, and kicks off > processing on that file using another class Worker(threading.thread). > Sounds good. > > I made definite progress by creating two queues...watch_queue and > processing_queue, and then used lists within the classes to store the > state of which files are processing/watched. > This sounds ugly, synchronization is one of those evils of multithreaded programming that should be avoided if possible. I see a couple of dirt simple solutions: 1. Have the watch thread move the file into a "Processing" folder that it doesn't scan 2. Have the watch thread copy the file into a python tempfile object and push that onto the queue, then delete the real file. This can be done efficiently (well, more efficiently than new.write(old.read()) with shutil.copyfileobj(old, new) Both those take very few lines of code, don't require synchronization, and don't require extending standard classes. From nospam at myisp.ifyouplease.com Wed Aug 29 10:50:06 2007 From: nospam at myisp.ifyouplease.com (Neil Wallace) Date: Wed, 29 Aug 2007 15:50:06 +0100 Subject: Jython 2.2 on Ubuntu In-Reply-To: References: <-YOdnW_k3p6Fy0nb4p2dnAA@bt.com> Message-ID: Thanks Tim, I subscribed to the Jython group hosted by sourceforge, and they are a great bunch of guys/gals. Here's what I did to fix my problem. 1. removed Jython 2.1 (using Synaptic)jytho 2. added the following lines (as root) to /etc/profile # set PATH for Jython PATH=$PATH:/home/neil/jython2.2 export PATH I had to restart X, that's it solved!! Neil Tim Couper wrote: > you need to ensure that the correct jython executable is in a directory > which is on your on your path. > > I've just successfully test-subscribed to > https://lists.sourceforge.net/lists/listinfo/jython-users. Maybe you > could try again. > > Tim > > Dr Tim Couper > CTO, SciVisum Ltd > > www.scivisum.com > > > > Neil Wallace wrote: >> Hi all, >> >> I am a novice Python/Jython programmer, and Ubuntu user. >> >> Ubuntu still only supports only version 2.1 of Jython. I have used the >> GUI installer of Jython 2.2, and installed it to the default >> /root/jython2.2 directory. The install went without issues. >> >> However, typing ............jython --version >> in a teminal still gives me ........ Jython 2.1 on java (JIT: null) >> >> What else do I need to do? >> >> regards >> Neil. >> >> p.s. I posted this to the jython group hosted by sourceforge, but it >> bounced. :-( >> From jloden at jayloden.com Thu Aug 9 13:49:30 2007 From: jloden at jayloden.com (Jay Loden) Date: Thu, 09 Aug 2007 13:49:30 -0400 Subject: Puzzled by "is" In-Reply-To: <46BB530B.3030304@jayloden.com> References: <20070809173855.9FDEB1E4009@bag.python.org> <46BB530B.3030304@jayloden.com> Message-ID: <46BB53AA.2090001@jayloden.com> Jay Loden wrote: > Dick Moores wrote: >> >>> () is () >> True >> >>> (1,) is (1,) >> False >> >> Why? >> >> Thanks, >> >> Dick Moores > >From the docs for 'is': The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value. So you're actually testing whether or not the identity of the object is the same, not whether (1,) == (1,): >>> (1,) == (1,) True >>> id((0,)) == id((0,)) False -Jay From sdrodrian at sdrodrian.com Sat Aug 11 10:30:03 2007 From: sdrodrian at sdrodrian.com (sdrodrian at sdrodrian.com) Date: Sat, 11 Aug 2007 07:30:03 -0700 Subject: Do you want to know about ISLAM Message-ID: <1186842603.707519.156590@57g2000hsv.googlegroups.com> goglemai... at gmail.com wrote: > Do you want to know about ISLAM, > the fastest growing peril to the World ? > If yes, this is the ONLY site you need visit: http://islamisbad.com Or, you could just read your newspapers with your BRAINS instead of your sheep's horns. S D Rodrian http://poems.sdrodrian.com http://physics.sdrodrian.com http://mp3s.sdrodrian.com All religions are local. Only science is universal. . From Brian.McCann at viziant.net Wed Aug 29 14:40:57 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Wed, 29 Aug 2007 14:40:57 -0400 Subject: copying files Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE30C@efmailx> Hi, with the code below I set a variable TEST_HOME to a path and the variable m to a path in my current dir. I have a symbolic link setting m---->lib when I run the script I get no errors and the lib dir with its 20 files does not get copied to /v01/test_home any help would be greatly appreciated --Brian #!/usr/bin/python import string import os import sys import errno import shutil import tarfile TEST_HOME = "/v01/test_home" m = "./lib" os.system("cp -r m TEST_HOME") #os.system("tar -cvf viziant-ingestion.tar /v01/") -------------- next part -------------- An HTML attachment was scrubbed... URL: From ladaan at iptel.org Wed Aug 8 11:51:34 2007 From: ladaan at iptel.org (Ladislav Andel) Date: Wed, 08 Aug 2007 17:51:34 +0200 Subject: twisted - locking threads when deferToThread is used In-Reply-To: <4866bea60708080710ma83a713p622c2997df812a6a@mail.gmail.com> References: <46B99CCB.1070304@iptel.org> <4866bea60708080709v797c5a67w158f6f988ef5c304@mail.gmail.com> <4866bea60708080710ma83a713p622c2997df812a6a@mail.gmail.com> Message-ID: <46B9E686.2050907@iptel.org> And here is the code: from twisted.internet import reactor, defer, threads from siptest import siptest_f from twisted.internet.threads import deferToThread test_opts = {'username':'test','transport':'udp','localport':'5085','password':'test'} domain = ['sip.1und1.de', 'sip.babble.net'] class Getter: def gotResults(self, domain, test_opts): if len(domain) != 0: self.d.callback(siptest_f(domain, test_opts)) else: self.d.errback(ValueError("You used an odd number!")) def _print(self, r, domain): return domain, r def getServerResponse(self, domain, test_opts): self.d = threads.deferToThread(self.gotResults, domain, test_opts) self.d.addCallback(self._print, domain) return self.d def printData(d): print d def printError(failure): import sys sys.stderr.write(str(failure)) def test(): for dom in domain: g = Getter() d = g.getServerResponse(dom, test_opts) d.addCallback(printData) d.addErrback(printError) if __name__ == '__main__': test() reactor.run() From aine_canby at yahoo.com Tue Aug 21 05:10:36 2007 From: aine_canby at yahoo.com (aine_canby at yahoo.com) Date: Tue, 21 Aug 2007 02:10:36 -0700 Subject: The folder a script is executed in Message-ID: <1187687436.476773.276550@22g2000hsm.googlegroups.com> Hi, How do I find out what folder a script is in while it is executing? For example, for the file "C:/folder/script.py" contain the following two lines of code - myLocation = GetMyLocation() print myLocation >> C:/folder Thanks, Aine. From zyzhu2000 at gmail.com Mon Aug 20 16:22:48 2007 From: zyzhu2000 at gmail.com (beginner) Date: Mon, 20 Aug 2007 20:22:48 -0000 Subject: 'REPL' style IDE In-Reply-To: <1187638768.783508.327010@r34g2000hsd.googlegroups.com> References: <1187632249.748945.158910@i13g2000prf.googlegroups.com> <1187633038.373751.244700@i38g2000prf.googlegroups.com> <1187638768.783508.327010@r34g2000hsd.googlegroups.com> Message-ID: <1187641368.230780.167030@x35g2000prf.googlegroups.com> On Aug 20, 2:39 pm, Jeff wrote: > python-mode in Emacs. Yeah, but I don't know anything about Emacs and as far as I know it is pretty complicated. From bj_666 at gmx.net Mon Aug 6 14:08:33 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Aug 2007 18:08:33 GMT Subject: Something in the function tutorial confused me. References: <1186420642.112170.78940@w3g2000hsg.googlegroups.com> <1186422680.103021.105230@l70g2000hse.googlegroups.com> Message-ID: <5hp6d1F3kl28iU4@mid.uni-berlin.de> On Mon, 06 Aug 2007 10:51:20 -0700, Lee Fleming wrote: > why isn't the y in def f (x, y = []): something > garbage-collected? `y` is a name. Only objects are garbage collected. There is no `y` in that ``def`` in the sense that a local name `y` exists when the ``def`` is executed. The line just says there will be a local name `y` if the function `f()` is executed and that local name will be bound to the given object. Which happen to be a list. This list is referenced by the function object, so it won't get garbage collected, and it is bound to a local name `y` every time the function is called. It is always the very same list object. And if you mutate it, this will be visible to other calls to the function. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Mon Aug 13 01:31:31 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 13 Aug 2007 02:31:31 -0300 Subject: Pausing and Unpausing Threads References: <1186883176.319755.304970@d55g2000hsg.googlegroups.com> <13bulsklq359q8f@corp.supernews.com> <1186950645.886995.56060@w3g2000hsg.googlegroups.com> <1186965947.914607.222260@o61g2000hsh.googlegroups.com> Message-ID: En Sun, 12 Aug 2007 21:45:47 -0300, Aaron J. M. escribi?: > Uhg, I thought of something I didn't consider before: how to cleanly > end the Server/DirectedControl(l)er process. Use the same Queue; put a special kind of Action, or just a None object, to tell the thread that there are no more things to process. From the main thread, you can join() the others, waiting for them to finish. -- Gabriel Genellina From koje_je_ono_bilo_pitanje at bla.bla Tue Aug 28 12:27:31 2007 From: koje_je_ono_bilo_pitanje at bla.bla (Boris Ozegovic) Date: Tue, 28 Aug 2007 18:27:31 +0200 Subject: localhost, ?! Message-ID: Three machines, one at my home, other two at my job, in every machine there is Win XP SP2 and Python 2.5 At home: urllib2.urlopen("http://localhost"), everything is ok At job: urllib2.urlopen("http://localhost") raise BadStatusLine(line), after half a minute. urllib2.urlopen("http://127.0.0.1") HTTP Error 503: Service Unavailable, immediately. Anybody have slightest clue wthat is going on? :-/ If I use urllib, then localhost works on every machine, and urllib2 works on every machine when retreiving URLs outside localhost. From mike at netadv.net Fri Aug 17 13:37:46 2007 From: mike at netadv.net (mike) Date: Fri, 17 Aug 2007 17:37:46 -0000 Subject: help on object programing In-Reply-To: <1187370429.041002.205500@d55g2000hsg.googlegroups.com> References: <1187370429.041002.205500@d55g2000hsg.googlegroups.com> Message-ID: <1187372266.757525.16470@q3g2000prf.googlegroups.com> On Aug 17, 11:07 am, yadin wrote: > class big(self): > > x = 32 > list = [] > def inside (self): > > class small(self): # a new class defined inside the first > > y = 348 > list.append(y) # send the value to first list > list.append(x) > > print list > > how can i define my variables so that there are valid outside the > class??? Well, first you have to create an instance of the class big: bigInstance = big(); then to get to bigInstance's list you do bigInstance.list and you can get to the list: print bigInstance.list; but the list will be empty. check out the dive into python book to understand it object oriented programming a little more. http://www.diveintopython.org/ From carsten at uniqsys.com Mon Aug 20 14:31:54 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 20 Aug 2007 14:31:54 -0400 Subject: str().join() isn't working In-Reply-To: <496954360708201116x5507358cr2f81710a62f2403e@mail.gmail.com> References: <496954360708200905i2100b32ag5983ab729e5d216f@mail.gmail.com> <496954360708201116x5507358cr2f81710a62f2403e@mail.gmail.com> Message-ID: <1187634714.3398.33.camel@dot.uniqsys.com> On Mon, 2007-08-20 at 13:16 -0500, Robert Dailey wrote: > here is a more realized example of the lists I'm trying to join: > > > _user_includes = [ > "../src", > # [snip] > ] > > _system_includes = [ > "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include", > # [snip] > ] > includes = space.join ( system._user_includes ) + " " + space.join( > system._system_includes ) > The above does not work. The interpreter states: "TypeError: sequence item > 0: expected string, list found". I'm not sure what this means. Can anyone > help me figure out what I'm doing wrong? Thanks. The error message means that join() expected the list to contain strings, but it found a list instead. There must be something else happening that you're not telling us. Running that join expression on the lists you quoted works just fine. Either the lists contain something other than what you claim, or the expression you're using is different in reality. We can't help you if you don't post the code you're running. HTH, -- Carsten Haese http://informixdb.sourceforge.net From shawn.o.weekly at gmail.com Tue Aug 7 09:36:30 2007 From: shawn.o.weekly at gmail.com (bhamdeveloper) Date: Tue, 07 Aug 2007 13:36:30 -0000 Subject: can't import SimpleXMLRPCDisptacher from SimpleXMLRPCServer In-Reply-To: <1186423276.861160.63610@g4g2000hsf.googlegroups.com> References: <1186423276.861160.63610@g4g2000hsf.googlegroups.com> Message-ID: <1186493790.984351.71610@o61g2000hsh.googlegroups.com> On Aug 6, 1:01 pm, bhamdeveloper wrote: > from my server I can't import SimpleXMLRPCDispatcher. please seehttp://intertubewaypoint.com/metaweblog/for the stacktrace/error > message. This onle happens on my server; I am trying to integrate the > metaweblog api into my blog and it is barfing when trying to get that > dispatcher. Anyone seen this and have a quick fix? fixed, I was doing something stupid From paul at boddie.org.uk Fri Aug 31 09:44:32 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 31 Aug 2007 06:44:32 -0700 Subject: pure python for sms In-Reply-To: References: Message-ID: <1188567872.672327.245590@50g2000hsm.googlegroups.com> On 31 Aug, 15:36, Gerardo Herzig wrote: > Neil Hodgson wrote: > > This is likely to cost some money similar to sending an SMS from a > >'phone. [...] > Well, im not triyng to send a SMS `FROM' a cellphone, im trying to send > a SMS `TO' a cellphone. Yes, but he did write "similar to", meaning that regardless of how the message is prepared, sending it may cost someone some money - the typical "financial effect" when you send a message from an actual telephone. > Here (in Argentina) are several sites who lets you send a sms for free. You also can receive > SMS responses via this pagehttp://sms.personal.com.ar/Mensajes/msn.htm I guess you're thinking about a library like SMSLib: http://smslib.org/ This seems to combine the two most obvious ways of sending such messages: communicate with a device already located on the GSM network; communicate with a gateway which relays messages to the GSM network. > While my tries using this page via urllib failed, i dont want to depend > on an external page anyway. The python class you send to me looks like > a pay site (if not, i dont see why the tokenpay() and getbalance() > methods :) > > I was also avaiable to send a sms in the form of an plain email > __cellphone_number at i_used_to_be_cool_smtp.com, but it not seems to work > this way no longer. Again, i dont want to do it that way anyway. Yes, both of the above (use of a Web site or an e-mail relay) rely on existing services. If you don't want to do that, you'll need to connect directly to your own GSM-capable device, I imagine. > Thats why im looking for a python implementation of that funcionality. I don't know how well SMSLib works with Jython or whether you could take a PyLucene-like approach and wrap it for CPython using SWIG or some other wrapper technology in conjunction with gcj, but that's one approach. Another is to look into libraries which communicate with mobile devices: I extended one called t616hack [1] and made it almost capable of telling my T610 telephone to send messages, but another candidate would be python-gammu [2]. A while back someone stumbled across a GSM hardware module which has embedded Python as a feature [3], but I imagine that a lot of GSM-capable hardware uses AT-like commands to support such activities. Of course, I've probably covered an area that you're not directly interested in, but someone has to provide a link to the GSM network, either in the network infrastructure or by using some kind of GSM device. If you're not a GSM network operator then it's likely that you're either going to need to deal with a network operator, perhaps indirectly, or you'll need to join the GSM network with a suitable device in the "normal" way. Paul [1] http://www.python.org/pypi/t616hack [2] http://cihar.com/gammu/python/ [3] http://www.telit.co.it/product.asp?productId=113 From ricaraoz at gmail.com Tue Aug 21 20:23:25 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 21 Aug 2007 21:23:25 -0300 Subject: IDE for Python In-Reply-To: <1187698999.545439.322600@k79g2000hse.googlegroups.com> References: <1187698999.545439.322600@k79g2000hse.googlegroups.com> Message-ID: <46CB81FD.5070101@bigfoot.com> king kikapu wrote: > On Aug 21, 12:00 pm, Joel Andres Granados > wrote: >> Hello list: >> >> I have tried various times to use an IDE for python put have always been >> disapointed. > > > I have also tried a lot of them (IDEs) in the last year. I was finally > happy with Eclipse/Pydev but i was always wanted a more "true" IDE for > Python. > I think i found it in Eric4 http://www.die-offenbachs.de/eric/index.html > You can download from here http://www.riverbankcomputing.co.uk/pyqt/download.php > (binary installer for Windows that contains Eric and PyQt) > and have a look at it! > Hi, Do you know if for in-house development a GPL license applies? (Qt4 and/or Eric4). From __peter__ at web.de Thu Aug 23 17:53:53 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 23 Aug 2007 23:53:53 +0200 Subject: comparing two lists References: Message-ID: Ladislav Andel wrote: > Peter Otten wrote: >> Ladislav Andel wrote: >> >> >>> what would be the most efficient way to do following? >>> >>> I have a list of dictionaries taken from DB e.g. >>> dblist = [{'id:1, 'host':'google.com','ip_address':'1.2.3.4'}, >>> {'id:3, 'host':'yahoo.com','ip_address':'5.6.7.8'}, >>> {'id:9, 'host':'msn.com','ip_address':'11.3.2.3'}] >>> >>> and list of object instances in memory(it's just for example) >>> which are looping within itself and testing particular hosts >>> >>> memlist = [,] >>> memlist[0].id is 1 and memlist[0].host is google.com etc. >>> memlist[1].id is 9 and memlist[1].host is msn.com etc. >>> >>> Now I want to add a new instance to memlist since id=3(in dblist) is not >>> in memlist. >>> How would you iterate through it and insert a new instance? >>> >>> The result should be: >>> memlist = [,, ] >>> memlist[0].id is 1 and memlist[0].host is google.com etc. >>> memlist[1].id is 3 and memlist[1].host is yahoo.com etc. >>> memlist[2].id is 9 and memlist[2].host is msn.com etc. >>> >> >> You should replace the memlist with a dictionary using (host, id) tuples >> as the keys. Here's an example that uses a set but requires you to modify >> the class: >> >> dblist = [{'id':1, 'host':'google.com','ip_address':'1.2.3.4'}, >> {'id':3, 'host':'yahoo.com','ip_address':'5.6.7.8'}, >> {'id':9, 'host':'msn.com','ip_address':'11.3.2.3'}] >> >> class Item(object): >> def __init__(self, id, host, **discarded): >> self._tuple = (id, host) >> def __hash__(self): >> return hash(self._tuple) >> def __eq__(self, other): >> return self._tuple == other._tuple >> def __repr__(self): >> return "Item(id=%r, host=%r)" % self._tuple >> >> items = set([Item(1, "google.com")]) >> for d in dblist: >> item = Item(**d) >> if item not in items: >> print "adding", item >> items.add(item) >> else: >> print item, "already there" >> >> > Thank you for this nice solution. I wouldn't be able to write it this > way at all Then think twice before you use it. The dictionary approach should be straightforward. > but what about removing from memlist if there is less items in dblist > than in items (instances)? > I will have to iterate over items(instances) and remove that one which > is not in dblist I guess. Yes, but again, if you use a dictionary instead of a list the lookup will be efficient. To follow up on my previous post: with sets there is a concise spelling: items &= set(Item(**d) for d in dblist) or even items.intersection_update(Item(**d) for d in dblist) if you don't mind object identity. Peter From korovev76 at gmail.com Tue Aug 7 03:30:27 2007 From: korovev76 at gmail.com (korovev76 at gmail.com) Date: Tue, 07 Aug 2007 00:30:27 -0700 Subject: parsing a dbIII file In-Reply-To: References: <1186469710.277542.246430@w3g2000hsg.googlegroups.com> Message-ID: <1186471827.183979.206700@r34g2000hsd.googlegroups.com> On 7 Ago, 09:21, Steve Holden wrote: > That's not a standard dBaseIII data file though, correct? It looks more > like something that was produced *from* a dBaseIII file. yeap... unfortunately it is not... > Good luck with your escape from COBOL! i'm not escaping by now... Actually I'd like to use cobol for the rest of my life (as a programmer) ;-) But thanx anyway! korovev From __peter__ at web.de Thu Aug 23 13:42:09 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 23 Aug 2007 19:42:09 +0200 Subject: comparing two lists References: Message-ID: Ladislav Andel wrote: > what would be the most efficient way to do following? > > I have a list of dictionaries taken from DB e.g. > dblist = [{'id:1, 'host':'google.com','ip_address':'1.2.3.4'}, > {'id:3, 'host':'yahoo.com','ip_address':'5.6.7.8'}, > {'id:9, 'host':'msn.com','ip_address':'11.3.2.3'}] > > and list of object instances in memory(it's just for example) > which are looping within itself and testing particular hosts > > memlist = [,] > memlist[0].id is 1 and memlist[0].host is google.com etc. > memlist[1].id is 9 and memlist[1].host is msn.com etc. > > Now I want to add a new instance to memlist since id=3(in dblist) is not > in memlist. > How would you iterate through it and insert a new instance? > > The result should be: > memlist = [,, ] > memlist[0].id is 1 and memlist[0].host is google.com etc. > memlist[1].id is 3 and memlist[1].host is yahoo.com etc. > memlist[2].id is 9 and memlist[2].host is msn.com etc. You should replace the memlist with a dictionary using (host, id) tuples as the keys. Here's an example that uses a set but requires you to modify the class: dblist = [{'id':1, 'host':'google.com','ip_address':'1.2.3.4'}, {'id':3, 'host':'yahoo.com','ip_address':'5.6.7.8'}, {'id':9, 'host':'msn.com','ip_address':'11.3.2.3'}] class Item(object): def __init__(self, id, host, **discarded): self._tuple = (id, host) def __hash__(self): return hash(self._tuple) def __eq__(self, other): return self._tuple == other._tuple def __repr__(self): return "Item(id=%r, host=%r)" % self._tuple items = set([Item(1, "google.com")]) for d in dblist: item = Item(**d) if item not in items: print "adding", item items.add(item) else: print item, "already there" Peter From steve at holdenweb.com Sun Aug 12 06:34:50 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 12 Aug 2007 06:34:50 -0400 Subject: Web based Reporting tool for Python In-Reply-To: <1186891194.582444.222010@r34g2000hsd.googlegroups.com> References: <1186460956.945148.162610@k79g2000hse.googlegroups.com> <1186547726.383996.291360@d55g2000hsg.googlegroups.com> <2007080808575016807-jon@turnthepageorg> <1186891194.582444.222010@r34g2000hsd.googlegroups.com> Message-ID: Madhu Alagu wrote: > On Aug 8, 4:57 pm, Jon Rosebaugh wrote: >> On 2007-08-07 23:35:26 -0500, Madhu Alagu said: >> >>> Thanking so much for all the informations and links.I would like to >>> use Mako Templates(www.makotemplates.org).Ilike to use simple and >>> python default module... >> Mako is an excellent template system, but you'll have a lot of work to >> do making it into a reporting system. > > > > Any reporting template in python ? > Dabo (www.dabodev.com) is certainly heading that way, but I am not sure how far it's got yet. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bignose+hates-spam at benfinney.id.au Tue Aug 28 20:58:27 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 29 Aug 2007 10:58:27 +1000 Subject: "Try:" which only encompasses head of compound statement References: <1188250535.607963.42540@22g2000hsm.googlegroups.com> <87wsvgfszm.fsf@benfinney.id.au> <13d7898odj2g19b@corp.supernews.com> <87fy24fdgf.fsf@benfinney.id.au> <1188345076.396437.111160@w3g2000hsg.googlegroups.com> Message-ID: <873ay3f970.fsf@benfinney.id.au> Jameson.Quinn at gmail.com writes: > In real life, I want to set some return values to sensible defaults > if the file doesn't exist, but I want the errors from inside the > block to trickle up as normal. Sure. Just be careful only to catch the exceptions that you do want to handle at that level of the code, and the others will propagate normally. > And yes, I can easily use a temporary variable for the open file, > but it really seems to me that this defeats the purpose of the > 'with' statement - if this were something more dangerous than a > file, I'd feel mighty leery of having it in a temporary variable > outside a 'with' for even a moment. You seem to be confused about one or both of "variables" (which Python doesn't really have) and the 'with' statement. When you write:: input_file = open("foo.txt") with input_file: # do stuff there's no "temporary variable". You've merely bound the name 'input_file' to the file object; it's the same file object as is then used in the 'with' statement. You could bind a dozen other names to the object and it would still be the same file object. So, when the 'with' block exits, the context manager will close the file object, no matter how many names you bind to it. > So, the options are: > -temporary variable - could this EVER be more dangerous than the with > statement (KeyboardInterrupt which is later caught and handled?) Since it's not a "temporary variable" but rather just a way to refer to the file object, I don't see the issue you're describing. However you refer to it, that one file object will be closed when the 'with' block exits. > -'tunnel' internal exceptions past the try by wrapping them in a > TunnelException and then unwrapping them with a containing try block. > > The second looks like a hack to me Yes, it is. Catch the exceptions you want to handle, let the rest propagate normally. The context manager created by the 'with' statement will handle closing the file *and* propagate the exception normally. > and the first still feels dangerous. If it's still that way, perhaps you could be more explicit about what danger you think exists? -- \ "Are you pondering what I'm pondering?" "I think so, Brain, but | `\ pants with horizontal stripes make me look chubby." -- _Pinky | _o__) and The Brain_ | Ben Finney From kyosohma at gmail.com Mon Aug 6 13:25:15 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 06 Aug 2007 17:25:15 -0000 Subject: Tkinter or wxpython? In-Reply-To: <46B73DE4.6040405@codebykevin.com> References: <1186410331.905174.21370@q3g2000prf.googlegroups.com> <7xps204tin.fsf@ruckus.brouhaha.com> <46B73DE4.6040405@codebykevin.com> Message-ID: <1186421115.402000.88080@x35g2000prf.googlegroups.com> On Aug 6, 10:27 am, Kevin Walzer wrote: > Paul Rubin wrote: > > > Tkinteger (dang, I always end up typing it that way, I won't even > > bother fixing the error) is easy to use for simple gui's, and it's > > part of the standard python distro which for me is a big advantage (no > > extra crap to download). However, the widget set is rather ugly and > > doesn't blend in well with anyone's native widgets; the widget > > selection itself is rather narrow, and I think kyosohma may be right > > that it doesn't scale well to complex gui's. I've looked at the code > > for IDLE's gui and it's terrifying. > > It's entirely possible to make sophisticated GUI's in Tkinter, but you > are right, most people don't. Part of the issue is that Tkinter > developers haven't kept up with what's going on in Tk and instead use > outdated, ugly widget sets like Tix, PMW, and so on. Making use of the > available wrappers for current Tk libraries such as BWidgets, Tile, > Tablelist, TkTreeCtrl, and so on allows you to make UI's every bit as > polished as what comes with wxPython: tree views, multi-column lists, > notebook tabs, comboboxes, etc., with platform-specific theming > (XP/Vista, Aqua/OS X, and X11). > > For more references, see: > > http://tkinter.unpythonic.net/wiki/TileWrapperhttp://tkinter.unpythonic.net/wiki/TableListWrapperhttp://tkinter.unpythonic.net/wiki/TableListTileWrapperhttp://tkinter.unpythonic.net/wiki/PyLocatehttp://tkinter.unpythonic.net/wiki/PyLocateTilehttp://tkinter.unpy.net/bwidget/http://tkinter.unpy.net/wiki/NoteBookhttp://klappnase.zexxo.net/TkinterTreectrl/index.html > > > > I tried the PMW widget toolkit. It was ok, but it seemed kind of buggy. I found out about Tix on a forum of some sort. When I tried to find out how to get it and use it, all I found was conflicting information. I finally got it downloaded only to find I had to compile it and I didn't have the right version of TCL. So I switched to wxPython then. Months later I found out that Tix is now included with Python. I still don't know how to use it though. As with most external Tkinter widget sets, Tix doesn't have examples. The docs look less inviting than man pages...but I realize that's probably just me. I just don't like man pages much. Thanks for the info though. You never know when you might need another toolkit for a specialized job. Mike From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Aug 30 04:43:57 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 30 Aug 2007 10:43:57 +0200 Subject: list index() In-Reply-To: <878x7te9h4.fsf@benfinney.id.au> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <46d674c2$0$417$426a34cc@news.free.fr> <878x7te9h4.fsf@benfinney.id.au> Message-ID: <46d68343$0$401$426a34cc@news.free.fr> Ben Finney a ?crit : > Bruno Desthuilliers writes: > >> What's with using your brain instead of whining ? > > Now now, no need for snappiness. If you don't feel a constructive > response is merited, please ignore. Yes, you're right. Sorry. From rozniy at gmail.com Tue Aug 7 05:13:38 2007 From: rozniy at gmail.com (rozniy) Date: Tue, 07 Aug 2007 02:13:38 -0700 Subject: How to use C enum in Python CTypes? In-Reply-To: <5hqgogF3ldifeU1@mid.uni-berlin.de> References: <1186462639.872254.25660@z24g2000prh.googlegroups.com> <5hqgogF3ldifeU1@mid.uni-berlin.de> Message-ID: <1186478018.409193.188130@e9g2000prf.googlegroups.com> On Aug 7, 2:11 pm, Marc 'BlackJack' Rintsch wrote: > On Tue, 07 Aug 2007 04:57:19 +0000, rozniy wrote: > > typedef enum olss_tag > > { > > OLSS_AD, > > OLSS_DA, > > OLSS_DIN, > > OLSS_DOUT, > > OLSS_SRL, > > OLSS_CT > > } > > OLSS; > > > I managed to fudge the HDEV, UINT and PHDASS types as CTypes c_long(), > > but I am not sure how translate a C enum into Python... > > > This site > >http://python.net/crew/theller/ctypes/tutorial.html#bugs-todo-and-non... > > > says that enumeration types is not implemented, > > "Enumeration types are not implemented. You can do it easily yourself, > > using c_int as the base class." > > I would just define constants: > > (OLSS_AD, > OLSS_DA, > OLSS_DIN, > OLSS_DOUT, > OLSS_SRL, > OLSS_CT) = map(ctypes.c_int, xrange(6)) > > Ciao, > Marc 'BlackJack' Rintsch- Hide quoted text - > > - Show quoted text - Wouldn't that assign integer values 0 to 5 to the things? I don't know if it'll give me the correct results. From zhushenli at gmail.com Wed Aug 29 05:09:55 2007 From: zhushenli at gmail.com (Davy) Date: Wed, 29 Aug 2007 02:09:55 -0700 Subject: How to parse this line of code manually In-Reply-To: <1188300534.952616.109760@o80g2000hse.googlegroups.com> References: <1188270013.785762.9360@z24g2000prh.googlegroups.com> <1188271385.875677.78560@i38g2000prf.googlegroups.com> <1188300534.952616.109760@o80g2000hse.googlegroups.com> Message-ID: <1188378595.303053.186900@e9g2000prf.googlegroups.com> On Aug 28, 7:28 pm, Dustan wrote: > On Aug 28, 2:59 am, "A.T.Hofkamp" wrote: > > > > > > > On 2007-08-28, Davy wrote: > > > > On Aug 28, 11:00 am, Davy wrote: > > >> Hi all, > > > >> It is well known that Python is appreciated for its merit of concise. > > >> However, I found the over concise code is too hard to understand for > > >> me. > > > >> Consider, for instance, > > >> def known_edits2(word): > > >> return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in > > >> NWORDS) > > > >> Shall I understand the code in set() as > > >> for e2 in edits1(e1) { > > >> if e2 in NWORDS { > > >> for e1 in edits1(word) { > > >> e2 > > >> } > > >> } > > > >> } > > > > [SNIP] > > > Hi all, I figured it myself. It is left to righ parse, right? > > > So the above one is like > > > for e1 in edits1(word) { > > > for e2 in edits1(e1) { > > > if e2 in NWORDS { > > > push e2 to set > > > } > > > } > > > } > > > This is correct, although I am not sure what language you are using here, it > > looks like a strange mix of Python and C to me. > > > >> Any suggestions are welcome! > > > The idea is known as List comprehension (for lists, obviously), and comes from > > functional programming, Bird & Wadler used it in their book. > > > The notation is very close to mathematics: > > > { e2 | e1: edits(word), e2: edits(e1) in NWORDS } > > > or in LaTeX: > > > $\{ e_2 | \forall e_1: \mathrm{edits}(\mathrm{words}), > > \forall e_2: \mathrm{edits}(e_1) \in \mathrm{NWORDS} \}$ > > > :-) > > > (which in words is something like: collect values e2, where e1 comes from > > 'edits(word)', e2 comes from 'edits(e1)', and e2 in NWORDS) > > For more examples:http://docs.python.org/tut/node7.html#SECTION007140000000000000000 [SNIP] Hi Hofkamp and Dustan, Thank you for your help :) Davy > > A 'list comprehension' with parentheses instead of square-brackets > creates a generator instead of a list, which can be more memory- > efficient and allows for lazy evaluation.- Hide quoted text - > > - Show quoted text - From vedrandekovic at v-programs.com Thu Aug 23 02:42:52 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Wed, 22 Aug 2007 23:42:52 -0700 Subject: redirect or cover .bat log In-Reply-To: <1187810295.951965.239300@m37g2000prh.googlegroups.com> References: <1187764689.836375.212730@z24g2000prh.googlegroups.com> <5j26bvF3s7lbpU2@mid.uni-berlin.de> <1187767578.925671.107000@q4g2000prc.googlegroups.com> <5j2br6F3r2avsU1@mid.uni-berlin.de> <1187787876.962883.66970@r34g2000hsd.googlegroups.com> <1187791309.427046.22400@q3g2000prf.googlegroups.com> <1187810295.951965.239300@m37g2000prh.googlegroups.com> Message-ID: <1187851372.042098.297240@q4g2000prc.googlegroups.com> On 22 kol, 21:18, vedrandeko... at v-programs.com wrote: > On 22 kol, 16:01, Gabriel Genellina wrote: > > > > > On 22 ago, 10:04, vedrandeko... at v-programs.com wrote: > > > > > >> > e.g I need run my my_scripts_setup.bat that contain: > > > > > >> > python myscript_setup.py py2exe > > > > > >> > Can I cover or redirect log of that process into my wx program? > > > > >> > I'am using Windows XP SP2, and Python 2.5. > > > Try the subprocess module. For the single line command you posted > > earlier, you don't even need the bat file: > > > import subprocess > > p = subprocess.Popen(["python", "myscript_setup.py", "py2exe"], > > stdout=subprocess.PIPE, stderr=subprocess.STDOUT) > > p.wait() > > output_from_process = p.stdout.readlines() > > > This would be fine if executing the script takes relatively a short > > time and doesn't generate so many output lines; there are other > > examples in the subprocess module documentation > docs.python.org/lib/module-subprocess.html> > > > -- > > Gabriel Genellina > > Hi, > > This works fine. > Thanks! Hi, This,works fine except this last line: output_from_process = p.stdout.readlines() I get an error: p has not attribute stdout Regards, Vedran From DustanGroups at gmail.com Mon Aug 20 07:35:04 2007 From: DustanGroups at gmail.com (Dustan) Date: Mon, 20 Aug 2007 11:35:04 -0000 Subject: Where we need to use Python ? In-Reply-To: <1187596936.136499.200280@l22g2000prc.googlegroups.com> References: <1187596936.136499.200280@l22g2000prc.googlegroups.com> Message-ID: <1187609704.907035.297430@a39g2000hsc.googlegroups.com> On Aug 20, 3:02 am, gperu... at gmail.com wrote: > Hi > > Iam new to Python > I know Perl, JScript,C,C++,Java > But i want to know where excatly this python come in to picture > > And Is it a interpreted language or a programming language > It comes in which category > > I very keen to know this please tell > > Regards > Ganesh P http://www.python.org From lasses_weil at klapptsowieso.net Fri Aug 31 18:41:53 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sat, 01 Sep 2007 00:41:53 +0200 Subject: Question involving a Python app... In-Reply-To: References: <1188571968.529938.55770@i38g2000prf.googlegroups.com> Message-ID: <46d89931$0$7685$9b4e6d93@newsspool2.arcor-online.net> Simon Brunning wrote: > On 8/31/07, sberry wrote: >> So, how do I create an executable (on Windows) >> to install the program so it will run without the aforementioned >> framework being installed? > > Check out py2exe. > Uhm, just an idea ... Can't we (that is, someone else) set up a reply-bot that spots FAQs and post the appropriate FGAs? /W From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Aug 10 10:29:07 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 10 Aug 2007 16:29:07 +0200 Subject: wxPython before MainLoop References: <13bl9a75laqcm70@corp.supernews.com> <13bnh5bs4b9h427@corp.supernews.com> Message-ID: <5i3b1jF3n5bdtU1@mid.individual.net> [david] wrote: > I'm disappointed that I didn't get a wxPython solution. > > If the only way to get wxPython to correctly handle > this simple task is to code around it, LOL -- did you try coding this app with native windows means, like MFC? You will have *exactly* the same problem, and *exactly* for the same reason. The organisation of wxWidgets (and thus, wxPython) is very near to Windows GUI coding philosophy. > I don't think wxPython is really ready for Windows. I suggest you first went getting experience with other GUI libraries before you make such statements. Also, wxPython is a thin wrapper around wxWidgets C++ library which is widely used for Windows apps. And with wxWidgets, you'd *also* have the same problem. > Bjoern, you're wrong. The GUI needs to be displayed > for the user to analyse. A delay between display and > readiness is much better than a delay before display > or a delay with the GUI half-drawn. This may be, but it strongly depends on the application itself. > Mike, the screen does display correctly, it's just > that in Windows, screen updates are not processed > while the application is busy. That's the matter in just about *every* GUI framework using an event loop. And I don't know any that doesn't. Thus, there are two widely used standard solutions: * use a worker thread, or * call a "process all pending events now" function repeatedly during the work (here: wx.Yield, wx.SafeYield, wx.YieldIfNeeded). Regards, Bj?rn -- BOFH excuse #92: Stale file handle (next time use Tupperware(tm)!) From steve at holdenweb.com Thu Aug 23 23:56:35 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 23 Aug 2007 23:56:35 -0400 Subject: optparse - required options In-Reply-To: References: <496954360708201251r137dfaedqe632361891eae343@mail.gmail.com> <46C9F7D1.9040506@jayloden.com> <496954360708201353v19ea266cr50f144d1d71d5912@mail.gmail.com> <46CA0814.6050200@jayloden.com> Message-ID: Steven Bethard wrote: > Omari Norman wrote: >> On Mon, Aug 20, 2007 at 05:31:00PM -0400, Jay Loden wrote: >>> Robert Dailey wrote: >>>> Well, I don't know what is wrong with people then. I don't see how >>>> required arguments are of bad design. >>> I tend to agree...while "required option" may be an oxymoron in >>> English, I can think of quite a few scripts I've written myself (in >>> various languages) that needed at least some kind of user input to >>> operate. >> The idea with optparse is not that programs should not require certain >> information on the command line; rather, the idea is that this >> information should be positional arguments, not 'options'. >> >> That is, to use the compiler example: >> >> compiler file >> >> is preferred if a file argument is necessary. >> >> compiler --file file >> >> is not preferred. > > I agree with the optparse philosophy, but Practicality Beats Purity. > That's why I was convinced to add "required options" to argparse -- > there are too many applications that want that kind of interface. > *I* don't write applications with interfaces like that, but enough > people do that the use case should really be supported. > Well, here's to software producers who listen to their users! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From steve at holdenweb.com Thu Aug 30 06:59:28 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Aug 2007 06:59:28 -0400 Subject: Python doesn't see the directories I create In-Reply-To: <46d6856b$0$17674$426a74cc@news.free.fr> References: <46d6856b$0$17674$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > mr_gadget a ?crit : >> When I create a subfolder, python is not seeing it. Can someone please >> explain this behaviour ? I just started with python, read the tutorial over >> the weekend and am writing my very first script. So I may not be seeing >> something. Both os.path and glob.glob seem not to see a folder I created. >> Other sibling folders seem to work fine. On a whim I tried paths with \\ >> double slashes and that worked. But why should single slashes work for some >> folders and not for others ?? > Note you *didn't* try paths with double slashes, you merely correctly represented the paths with single slashes :-) > s/slash/antislash/g > > It's a very well known gotcha due to MS's choice to use the antislash as > path separator. In most languages - Python included - the antislash is > used for escape sequences (non-printable characters). '\r' is the escape > sequence for CR (carriage return). Doubling the antislash prevents > escaping. > > You can avoid all escaping by using raw strings: > > mypath = r"C:\enhancement\rawfiles\" > Please note that the above is a well-known syntax error. A string literal cannot end with a single backslash, as it escapes the closing quote. >>> mypath = r"C:\enhancement\rawfiles\" File "", line 1 mypath = r"C:\enhancement\rawfiles\" ^ SyntaxError: EOL while scanning single-quoted string >>> > Also and IIRC, using slash instead should also work, ie: > > mypath = r"C:/enhancement/rawfiles/" > That does indeed work in most situations, but ideally (i.e. for maximum code portability) paths should be constructed using os.path.join(), or collected from the environment somehow. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From google at mrabarnett.plus.com Fri Aug 31 13:03:47 2007 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 31 Aug 2007 10:03:47 -0700 Subject: strings (dollar.cents) into floats In-Reply-To: References: <877incd20i.fsf@benfinney.id.au> <46d75cf3$0$7698$9b4e6d93@newsspool2.arcor-online.net> <1188575044.874256.42960@50g2000hsm.googlegroups.com> Message-ID: <1188579827.947563.13880@50g2000hsm.googlegroups.com> On Aug 31, 5:28 pm, "Chris Mellon" wrote: > On 8/31/07, Steve Holden wrote: > > > sturlamolden wrote: > > > On 31 Aug, 02:12, Wildemar Wildenburger > > > wrote: > > > >> I've heard (ok, read) that several times now and I understand the > > >> argument. But what use is there for floats, then? When is it OK to use them? > > > > There are fractions that can be exactly represented by floats that > > > cannot be exactly represented by decimals. > > > Would you care to give an example? > > > > There are fractions that > > > can be exactly represented by decimals that cannot be exactly > > > represented by floats. > > > > Which one is better? Which do we prefer? > > > > What a float cannot do is to represent a decimal fractional number > > > (e.g. 1.1) exactly. If we need that, we cannot use floats. A notable > > > example is monetary computations, it covers 99% of the use for decimal > > > numbers in computers. For this reason, we should never use floats to > > > add 10 cents to a dollar. The use of decimals for monetary > > > calculations is mandatory. > > > That last sentence is patent nonsense, and completely untrue. Many > > satisfactory financial applications have been written using only > > floating-point arithmetic. Indeed I believe the accountant's Swiss army > > knife, the Excel spreadsheet, uses floating-point numbers exclusively. > > This is true, although Excel munges it's FP to provide "expected" results. > > It depends on what you consider a "financial" application though. > Excel, while in extremely broad use, is not used to implement any of > the systems which actually "define" money, like the back end financial > systems at banks and credit unions. > > In my experience, by far the most common method of calculating > financial numbers is actually using integer amounts, and then applying > well-defined rounding rules which I can't be bothered to look up the > name for. > > For what it's worth, the work that I do with money (which is > middleware doing data transport, not calculations or billing) uses > either string representations or fixed point. > > > What you say about floating-point have speed advantages is true, but you > > go too far in claiming that decimal arithmetic is mandatory for monetary > > calculations. That's about as sensible as saying that base 12 and base > > 20 arithmetic units were required to calculate in pounds, shillings and > > pence. > > I believe that to the degree that "real" accounting was done in those > currencies it did in fact use non-decimal bases. Just as people don't > use decimal time values (except us crazy computer folk), you're write > 1 pound 4 shillings, not 1.333... pounds. > FYI, 1 pound 4 shillings was 1.20 pounds; 1.333... pounds was 1 pound 6 shillings 8 pence. I think... From jonas.esp at googlemail.com Sat Aug 18 04:41:29 2007 From: jonas.esp at googlemail.com (Kless) Date: Sat, 18 Aug 2007 01:41:29 -0700 Subject: Encryption and hashing In-Reply-To: <7x1we1eoiy.fsf@ruckus.brouhaha.com> References: <1187377630.017794.36510@50g2000hsm.googlegroups.com> <1187392383.237609.97250@19g2000hsx.googlegroups.com> <7x1we1eoiy.fsf@ruckus.brouhaha.com> Message-ID: <1187426489.420964.132380@g4g2000hsf.googlegroups.com> On 18 ago, 00:20, Paul Rubin wrote: > Kless writes: > > So it haven't Twofish, Serpent, neither Whirlpool. Neither many others. > > Unless you have an interoperability requirement or some other specific > issue, you should stick with AES and the SHA2 family. Don't make your > own cipher selections unless you know completely what you're doing. > This is especially the case for business applications in the US, since > AES and SHA are US federal standards and if you use them and something > goes wrong with them, you can at least say you followed the standard. > If you use anything else, you will have more to answer for. Well, I only know that I choose the best public cryptographic algorithms. SHA-2 has been designed by the National Security Agency (NSA), and I'm sure that many people trust on the NSA so that every people make its election. But I'm sure that many people will avoid use algorithms recommend by the governement. And I don't know why :P, they always say the truth and we must trust on them. I'm sure that having great experts on cryptography they are not bee able of put a backdoor indetectable or better to debilitate the algorithm so that it is easier to break it. From george at nospam.invalid Sun Aug 19 16:13:14 2007 From: george at nospam.invalid (George) Date: Sun, 19 Aug 2007 16:13:14 -0400 Subject: Latest models of Gibson guitars In-Reply-To: <1187548916.909340.37420@k79g2000hse.googlegroups.com> References: <1187544898.289948.322160@22g2000hsm.googlegroups.com> <1187548916.909340.37420@k79g2000hse.googlegroups.com> Message-ID: vedrandekovic at v-programs.com wrote: > On 19 kol, 19:34, mobile... at gmail.com wrote: >> Reviews of latest models of best guitars, fender, gibson, yamaha, and >> many more, with pictures and prices. >> >> http://spam-guitars.blogspot.com/ >> >> And if you want to win a free guitar go here >> >> http://spamguitars.blogspot.com/ > > Hello, > > This is a newsgroup of programming language Python, stop with this! > > Regards, > Vedran > Thank Google for it. They own blogspot and officially encourage their users to look for click revenue. Then the users spam newsgroups using Google, the spammers friend. From cousinstanley at gmail.com Wed Aug 1 16:28:39 2007 From: cousinstanley at gmail.com (Cousin Stanley) Date: Wed, 01 Aug 2007 15:28:39 -0500 Subject: access the name of my method inside it References: <1185959202.302467.276080@x35g2000prf.googlegroups.com> <5hb1ebF3inuf2U6@mid.uni-berlin.de> <1185973639.234450.305690@g12g2000prg.googlegroups.com> Message-ID: <1186000119_6209@sp12lax.superfeed.net> >> > def my_method(): >> > >> > # do something >> >> > # how do I get the name of this method >> > # which is my_method here? >> >> Why do you need this? There are ways but those >> are not really good for production code. >> > > I am going to use this in Django. I am trying to implement > a permission here, where in the database store the methods > that the user are allowed to execute. > > for example if the method is def create_event() : > the method will look for create_event in the database > to see if it allow to be execute. james .... Perhaps a simple-minded hard-coded solution might work .... def permission_check( name ) : permission = DB.permission_check( name ) if not permission : print 'No Execute Permission for %s ' % name sys.exit( -1 ) def my_method() : permission_check( "my_method" ) .... -- Stanley C. Kitching Human Being Phoenix, Arizona ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From grante at visi.com Fri Aug 24 21:14:33 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 25 Aug 2007 01:14:33 -0000 Subject: py2exe/distutils: how to include a tree of files? References: <13cuhdr58m5one7@corp.supernews.com> <13cukd39lgsfgb4@corp.supernews.com> <1188000252.290854.289870@q4g2000prc.googlegroups.com> Message-ID: <13cv0jpdot6fo20@corp.supernews.com> On 2007-08-25, Carl Banks wrote: > On Aug 24, 5:46 pm, Grant Edwards wrote: >> On 2007-08-24, Grant Edwards wrote: >> >> > I'm packaging up a python program and need to include an entire >> > directory tree in the distribution. >> >> I've cobbled together something using package_dir/package_data >> and os.path.walk(), but it seems like a bit of a kludge... > > "data_files" is documented in the official distutils > documentation. It took quite a while, but I eventually found it. Having the documentation split up into dozens and dozens of small pages sure makes it hard to find things. I don't really understand what the advantage for splitting up documentation into screen-sized chunks is supposed to be -- all the web browsers I've ever seen can scroll. One page per module or chapter sure would make it easier to search... > (Yes, in regular distutils you do have to pretty much walk the data > directories to get your data.) That's what I ended up doing. Fortunately os.walk() makes it fairly easy. :) -- Grant Edwards grante Yow! Nipples, dimples, at knuckles, NICKLES, visi.com wrinkles, pimples!! From james.p.news at gmail.com Wed Aug 22 15:28:19 2007 From: james.p.news at gmail.com (james.p.news at gmail.com) Date: Wed, 22 Aug 2007 19:28:19 -0000 Subject: libgmail failure In-Reply-To: References: <1187730447.621592.93740@q4g2000prc.googlegroups.com> Message-ID: <1187810899.496022.314240@z24g2000prh.googlegroups.com> On Aug 22, 10:26 am, James Stroud wrote: > james.p.n... at gmail.com wrote: > > Hey all, > > > I've been using libgmail to send out automated notification emails for > > my company's nightly regression testing. Last night these emails > > started failing, though the python code has not changed. I updated to > > the latest libgmail, but that isn't helping. I've logged in to the > > email account directly, and the account is still working fine. > > > The error I get is "HTTP Error 400: Bad Request" when using > > gmailAccount.login(). This doesn't throw an exception, just prints > > the error. The code crashes outright when it tries to send mail. > > > This code has been up and running for several months and just started > > failing last night. Does anyone have an idea what's going on? > > > The code and error follow (fairly short :-) > > > Thanks much, > > James > > Have you thought about spoofing explorer? Always spoof explorer. > > James I have not heard of this. How do you spoof IE in libgmail? Thanks much, James From kbk at shore.net Sat Aug 18 21:58:40 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Sat, 18 Aug 2007 21:58:40 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200708190158.l7J1weEW020776@hampton.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 417 open (+13) / 3855 closed ( +0) / 4272 total (+13) Bugs : 1069 open ( +4) / 6800 closed (+10) / 7869 total (+14) RFE : 262 open ( -1) / 296 closed ( +1) / 558 total ( +0) New / Reopened Patches ______________________ Replacing char* with const char* (2007-08-12) http://python.org/sf/1772673 opened by eXt [python-mode] Properly highlight lambda with no arguments (2007-08-12) http://python.org/sf/1772721 opened by Michal Kwiatkowski -q (quiet) option for python interpreter (2007-08-13) http://python.org/sf/1772833 opened by Marcin Wojdyr Decimal and long hash, compatibly and efficiently (2007-08-13) http://python.org/sf/1772851 opened by Mark Dickinson Remove references to _xmlrpclib from xmlrpclib.py (2007-08-14) http://python.org/sf/1773632 opened by Alan McIntyre Unify __builtins__ -> __builtin__ (2007-08-15) http://python.org/sf/1774369 opened by Christian Heimes Add Checkbutton get() and set(value) (2007-08-14) http://python.org/sf/1774370 opened by Graham Horler Make it possible to use SVK to develop Python (2007-08-14) http://python.org/sf/1774414 opened by Collin Winter Override flags set by IOBase in io.StringIO (2007-08-15) http://python.org/sf/1774828 opened by Alexandre Vassalotti Convert str to bytes in io.BytesIO.__init__ (2007-08-15) http://python.org/sf/1774833 opened by Alexandre Vassalotti zipfile: Allow reading duplicate filenames (2007-08-15) http://python.org/sf/1775025 opened by Graham Horler utt-32 codecs (2007-08-16) http://python.org/sf/1775604 opened by Walter D?rwald Minor corrections to smtplib (2007-08-17) http://python.org/sf/1776581 opened by Alan McIntyre New / Reopened Bugs ___________________ urllib2 hangs with some documents. (2007-08-12) http://python.org/sf/1772481 opened by Creature dir() on traceback objects returns an empty list (2007-08-11) CLOSED http://python.org/sf/1772489 opened by Collin Winter exec() doesn't take an open file (2007-08-12) CLOSED http://python.org/sf/1772686 opened by Neal Norwitz chr(128) in u'only ascii' -> TypeError with misleading msg (2007-08-13) http://python.org/sf/1772788 opened by Pekka Laukkanen Using telnetlib fails with unicode strings containing only a (2007-08-13) http://python.org/sf/1772794 opened by Pekka Laukkanen Py Lib Ref, 3.6.1 String Methods startswith() typo (2007-08-13) CLOSED http://python.org/sf/1772890 opened by arxaaron xmlrpclib crash when PyXML installed (2007-08-13) http://python.org/sf/1772916 opened by lplatypus Binding fails (2007-08-15) http://python.org/sf/1774736 opened by Ali Gholami Rudi Not exiting when running tests (2007-08-15) http://python.org/sf/1774840 opened by Jos? Pablo "Pupeno" Fern?ndez Display CallTips for classes using metaclasses. (2007-08-16) http://python.org/sf/1775388 opened by Noam Raphael Buffer overflow when listing deeply nested directory (2007-08-17) http://python.org/sf/1776160 opened by Bj?rn Lindqvist glob.glob inconsistent (2007-08-18) http://python.org/sf/1776674 opened by norbidur tempfile.TemporaryFile differs between platforms (2007-08-18) http://python.org/sf/1776696 opened by Kenneth Loafman memoryview('test') is causing a segfault (2007-08-19) http://python.org/sf/1777057 opened by Christian Heimes Bugs Closed ___________ ERROR - Microsoft Visual C++ Runtime Library (2007-05-18) http://python.org/sf/1721161 closed by gbrandl dir() on traceback objects returns an empty list (2007-08-11) http://python.org/sf/1772489 closed by collinwinter words able to decode but unable to encode in GB18030 (2007-08-09) http://python.org/sf/1770551 closed by perky exec() doesn't take an open file (2007-08-12) http://python.org/sf/1772686 closed by bcannon Py Lib Ref, 3.6.1 String Methods startswith() typo (2007-08-13) http://python.org/sf/1772890 closed by gbrandl decimal.Decimal("trash") produces informationless exception (2007-08-08) http://python.org/sf/1770009 closed by facundobatista mark deprecated modules in indexes (2003-10-02) http://python.org/sf/816725 closed by gbrandl Python function/method/constant names as HTML-tag IDs (2005-07-24) http://python.org/sf/1243945 closed by gbrandl Collapse distutils docs (2005-12-07) http://python.org/sf/1375258 closed by gbrandl some section links (previous, up, next) missing last word (2006-09-15) http://python.org/sf/1559142 closed by gbrandl RFE Closed __________ -q (quiet) option for python interpreter (2007-05-30) http://python.org/sf/1728488 closed by wojdyr From jjl at pobox.com Tue Aug 7 17:38:10 2007 From: jjl at pobox.com (John J. Lee) Date: Tue, 07 Aug 2007 21:38:10 GMT Subject: Misleading wikipedia article on Python 3? References: <87bqdlswbn.fsf@pobox.com> <46b611c4$0$24872$9b622d9e@news.freenet.de> <877io9soa1.fsf@pobox.com> <46B63F0E.8030208@v.loewis.de> <87y7gpr33a.fsf@pobox.com> <87lkcnoydy.fsf@pobox.com> <46b8e0a2$0$12255$9b622d9e@news.freenet.de> Message-ID: <87d4xzowjh.fsf@pobox.com> "Martin v. L?wis" writes: >> Do you *really* think that projects will fall 50-50 into the "yes" and >> "no" camps, as you seem to imply -- after all, if you thought that one >> case was more common, why wouldn't you mention which it was? > > I know you didn't ask me this time, but I answer anyway: I don't know. > > I *really* think that only experience can tell, and that any kind of > prediction on that matter is futile FUD (as FUD, it might be successful, > of course). I do so using all my skill and judgment. Only when people > actually start to try porting, list specific issues that they actually > ran into (rather than listing issues they anticipate to run into), > only then I can make guesses as to what the common case will be. [...] By this criterion, Guido himself is engaging in FUD, as near as I can tell (of course, I don't believe he is doing that; I also can't believe that the effective requirements for the project are quite as decoupled from source compatibility considerations as has sometimes been implied by some of those working on the project). John From carsten at uniqsys.com Thu Aug 2 08:28:46 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 02 Aug 2007 08:28:46 -0400 Subject: frequency analysis of a DB column In-Reply-To: References: <1186021313.413443.184060@i38g2000prf.googlegroups.com> Message-ID: <1186057726.3388.6.camel@dot.uniqsys.com> On Thu, 2007-08-02 at 00:38 -0300, Gabriel Genellina wrote: > I'd start with: > > select column, count(column), min(column), max(column) > from table > group by column > order by count(column) desc What's the point of including min(column) and max(column)? They're always going to be equal to column. -- Carsten Haese http://informixdb.sourceforge.net From lionchao at gmail.com Wed Aug 22 15:34:21 2007 From: lionchao at gmail.com (Eric CHAO) Date: Wed, 22 Aug 2007 20:34:21 +0100 Subject: way to define static method Message-ID: I think Python uses a very strange way to define static method in a class. Why not make it like this? class MyClass: def my_static_method(self): # self should be None as it's a static method # just ignore self I'm a newcomer so maybe it's quite naive. But I just wonder why it is designed like this. Thanks. From sbellon at sbellon.de Sat Aug 11 10:04:49 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Sat, 11 Aug 2007 16:04:49 +0200 Subject: Destruction of generator objects References: <20070808002852.6228ae91@cube.tz.axivion.com> <1186613044.494852.306970@q75g2000hsh.googlegroups.com> <20070809011441.05d7dfb6@cube.tz.axivion.com> <1186819365.988117.232230@g4g2000hsf.googlegroups.com> <20070811121630.1b010eab@cube.tz.axivion.com> <1186831173.814193.235420@o61g2000hsh.googlegroups.com> <20070811140017.22a11f82@cube.tz.axivion.com> <1186834823.389706.137980@r34g2000hsd.googlegroups.com> <20070811145033.18c70c0c@cube.tz.axivion.com> <5i5qheF3ml00gU2@mid.uni-berlin.de> Message-ID: <20070811160449.2237e3f9@cube.tz.axivion.com> On Sat, 11 Aug, Marc 'BlackJack' Rintsch wrote: > On Sat, 11 Aug 2007 14:50:33 +0200, Stefan Bellon wrote: > > But then, even when terminating the interpreter, __del__ is not > > called. > > Because that is not guaranteed by the language reference. The reason > why it is a bad idea to depend on `__del__` for important resource > management. Ok, but then we are back to my initial question of whether the destroy of def get_data(obj): iter = make_iter(obj) while more(iter): yield next(iter) destroy(iter) can be guaranteed somehow in Python 2.4 while it can be done in Python 2.5 like follows: def get_data(obj): iter = make_iter(obj) try: while more(iter): yield next(iter) finally: destroy(iter) And then the answer is: no, it cannot be done in 2.4 (like Alex Martelli already said ;-) -- Stefan Bellon From joevans at gmail.com Sun Aug 26 16:12:30 2007 From: joevans at gmail.com (Jason Evans) Date: Sun, 26 Aug 2007 13:12:30 -0700 Subject: Parser Generator? In-Reply-To: References: <1187834836.115735.111160@e9g2000prf.googlegroups.com> Message-ID: <1188159150.755231.239390@o80g2000hse.googlegroups.com> On Aug 24, 1:21 pm, "Jack" wrote: > "Jason Evans" wrote in message > > http://www.canonware.com/Parsing/ > > Thanks Jason. Does Parsing.py support Unicode characters (especially CJK)? > I'll take a look. Parsers typically deal with tokens rather than individual characters, so the scanner that creates the tokens is the main thing that Unicode matters to. I have written Unicode-aware scanners for use with Parsing-based parsers, with no problems. This is pretty easy to do, since Python has built-in support for Unicode strings. Jason From steve at holdenweb.com Sun Aug 12 22:06:00 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 12 Aug 2007 22:06:00 -0400 Subject: Ligmail bug? In-Reply-To: References: <20070812005057.GA15805@ob41.org> <20070812182439.GA2427@ob41.org> <46BEE9B8.8080904@holdenweb.com> Message-ID: <46BFBC88.2010400@holdenweb.com> Ed Leafe wrote: > On Aug 12, 2007, at 7:06 AM, Steve Holden wrote: > >> [Please reply via the list when a response is made via the list. >> You may >> now have detached the follow-ups from your original question, but at >> least if you use the list there's a chance someone else will help >> you if >> I give up or don't have time. Note I have sent this response to the >> list; you are Cc'd to make sure you pick it up even though it may not >> appear in the same thread.] > > I've seen others comment on this, so I'll throw in my 2 cents. > > The default behavior for this list should be to reply to the list, > as you have pointed out. Yet for some unfathomable reason, the > keepers of the list have set it up to default to reply to the > original sender. This is nothing short of stupid, and I cast my vote > (if I even have one) for changing this default to a more intelligent > one, if for no other reason than to not have to constantly read > comments like this chiding someone for acting in a predictable fashion. > Since I subscribe to the newsgroup rather than to the mailing list I don't see that behavior. It's by far the most convenient way to interact with c.l.py, and gmane.org makes it easy to do so with Firefox or Outlook Express. I've never really understood why Outlook doesn't include an NNTP client. I presume Apple Mail (which appears in your headers) doesn't act as a newsreader either? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From arkanes at gmail.com Fri Aug 17 20:30:46 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 17 Aug 2007 19:30:46 -0500 Subject: wxPython in C++ app using wxWidgets In-Reply-To: References: Message-ID: <4866bea60708171730l1c2a58f9h87ce58bb375642ea@mail.gmail.com> On 8/17/07, Marcin Kalicinski wrote: > I have an application written in C++ that uses wxWidgets for GUI. I use > embedded Python for scripting inside of this application. I want to use > wxPython to add GUI to my scripts - because my C++ App uses wxWidgets I > thought it to be easy. The problem is that wxPython knows nothing about > wxApp/wxFrame objects created in my C++ application, and insists (by giving > me asserts) that I create another wxApp object for wxPython inside my > scripts. Obviously, this is not what I want. I want the scripts to use the > same wxApp/wxFrame object that my C++ application already created. More > specifically, I want to create dialogs in wxPython that will have my > application wxFrame as parent. > > I'm stuck. Any help appreciated. > I've never done this, but there's a sample in the wxPython source distribution (I don't think it's in the packaged versions). You can see it in SVN at http://svn.wxwidgets.org/viewvc/wx/wxPython/trunk/samples/embedded/ If you have questions the sample doesn't answer, or if it doesn't work for you, ask on the wxpython-users list instead of this one. From timid.gentoo at gmail.com Sun Aug 12 22:24:18 2007 From: timid.gentoo at gmail.com (_spitFIRE) Date: Sun, 12 Aug 2007 21:24:18 -0500 Subject: which IDE is highly recommended in Windows OS In-Reply-To: <1186970945.403792.51790@d55g2000hsg.googlegroups.com> References: <1186970945.403792.51790@d55g2000hsg.googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Ge Chunyuan wrote: > hi Group: > > I am a new comer for Python, I wonder which IDE is recommended in > Windows OS. > Can anyone give some suggestion. > > > Thanks indeed > Ge Chunyuan > - - Stani's Python Editor (http://www.softpedia.com/get/Programming/Coding-languages-Compilers/Stanis-Python-Editor.shtml) - - Black Adder (http://www.thekompany.com/products/blackadder/) - - Zeus (http://www.zeusedit.com/python.html) - - PyScripter (http://mmm-experts.com/Products.aspx?ProductId=4) - - ActivePython (http://www.activestate.com/) - - IDLE (http://www.python.org/idle/doc/idle2.html) and depending on how you define IDEs, you can also decide whether or not to include, the following - - emacs - - vim - - scite ... - -- _ _ _]{5pitph!r3}[_ _ _ __________________________________________________ ?I'm smart enough to know that I'm dumb.? - Richard P Feynman -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGv8DSA0th8WKBUJMRAqGcAJ9hhMp3tyS7XmBZT2+fol/A69j4jwCfXNya xQTmmDlDF5BAfiWkrSW3TuQ= =902n -----END PGP SIGNATURE----- From buzzard at urubu.freeserve.co.uk Tue Aug 21 14:18:18 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Tue, 21 Aug 2007 19:18:18 +0100 Subject: confused about why i get a type error when i call an object's method In-Reply-To: <1187719631.092657.158410@d55g2000hsg.googlegroups.com> References: <1187719631.092657.158410@d55g2000hsg.googlegroups.com> Message-ID: pepper at rumbalski.com wrote: > I'm confused about why i get a type error when i call an object's > method. Here's the example code: > >>>>class Foo: > > def __init__(self): > self.foo = [] > def foo(self): > print "in foo!" > > > >>>>f = Foo() >>>>dir(f) > > ['__doc__', '__init__', '__module__', 'foo'] > >>>>f.foo() > > > Traceback (most recent call last): > File "", line 1, in > f.foo() > TypeError: 'list' object is not callable > > Because f.foo is a list and you're trying to call it. You need different names for the list and the method (both self.foo above). Duncan From cncprgr at gmail.com Fri Aug 31 23:00:48 2007 From: cncprgr at gmail.com (dc) Date: Fri, 31 Aug 2007 20:00:48 -0700 Subject: Python weather application In-Reply-To: <1188513685.528316.4770@l22g2000prc.googlegroups.com> References: <1188503143.724438.309580@x40g2000prg.googlegroups.com> <1188513685.528316.4770@l22g2000prc.googlegroups.com> Message-ID: <1188615648.362001.323770@50g2000hsm.googlegroups.com> On Aug 30, 5:41 pm, Zentrader wrote: > On Aug 30, 12:45 pm, seancron wrote: > > > > > Does anybody have any suggestions for getting started on desigining a > > desktop weather application in Python? > > > I've been looking for access to weather data and while I have found > > several including the weather.com service I've decided to use the > > Yahoo! Rss Weather feed since it doesn't have a license like the > > weather.com service does. However one problem I have with it is that > > it only accepts zip codes or locations ids. So if a user was to enter > > the name of the city instead of those two there would be an error. I > > could make it so they could only enter in the location code or zip > > code but I would really prefer to have it be automatically corrected. > > Does anyone have ideas on how to go about this or have an other > > suggestions? > > > Thanks, > > Sean > > Use a dictionary to convert from the city chosen to the zip/location > code to use at Yahoo. You can purchase/subscribe a zip code database and then use that as a reverse look-up for your user entering a city. try the postal service website for the database info. From arkanes at gmail.com Thu Aug 30 16:25:46 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 30 Aug 2007 15:25:46 -0500 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188504811.019632.186580@x35g2000prf.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> <1188430887.481586.106760@l22g2000prc.googlegroups.com> <1188504811.019632.186580@x35g2000prf.googlegroups.com> Message-ID: <4866bea60708301325x2c424bf6yec59a7b304035fab@mail.gmail.com> On 8/30/07, Russ wrote: > > > PEP 316 introduces new syntax for a limited use feature. That's pretty > > much a no-starter, in my opinion, and past experience tends to bear > > that out. Furthermore, it predates decorators and context managers, > > which give all the syntax support you need and let you move the actual > > DBC features into a library. I can't remember if I mentioned this > > before but I believe that Philip Ebys PEAK toolkit has some stuff you > > could use for DBC. > > I don't see how you can avoid adding some new syntax, given that > Python does not > currently have syntax for specifying invariants and pre- and post- > conditions. And if I am > not mistaken, the new syntax would appear only in doc strings, not in > the regular Python > code itself. We're not really talking here about changing the core > Python syntax itself, > so I don't see it as a "non-starter." Anyone who chooses not to use > would be completely > unaffected. > I misread the pep as adding the identifiers into the actual python syntax, not in the docstring. All the more reason to implement it as a library, then. I actually think that decorators and context managers would be nicer than special docstring syntax, but I recognize the benefit of the doctest style approach. > As far as I can tell, Terence Way has done a nice job of implementing > design by contract for > Python, but perhaps a better approach is possible. The advantage of > making part of the > core Python distribution is that it would get vetted more thoroughly. > Things get vetted *before* they get added to the core, not after. From Shawn at Milochik.com Mon Aug 20 11:22:43 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Mon, 20 Aug 2007 11:22:43 -0400 Subject: Newbee Question In-Reply-To: <1187622390.854759.162320@q3g2000prf.googlegroups.com> References: <1187621470.484615.7010@i13g2000prf.googlegroups.com> <1187622390.854759.162320@q3g2000prf.googlegroups.com> Message-ID: <2dc0c81b0708200822k337c2ad2pe8f0dbc3717365b@mail.gmail.com> > I like to write code, so it's not a big deal when it's something so > simple. Still, that is beyond dumb! Nice code, by the way. > > Mike Yeah, it was fun to write anyway. Thanks for the compliment on the code. I still consider myself a Python newbie, so it's good to know I'm not trying to write it like Perl or VBScript anymore. ^_^ Shawn From dstromberg at datallegro.com Wed Aug 15 19:26:39 2007 From: dstromberg at datallegro.com (Dan Stromberg - Datallegro) Date: Wed, 15 Aug 2007 16:26:39 -0700 Subject: "Variable variable name" or "variable lvalue" References: <1187199722.618893.281170@r29g2000hsg.googlegroups.com> Message-ID: On Wed, 15 Aug 2007 10:42:02 -0700, mfglinux wrote: > Hello to everybody > > I would like to know how to declare in python a "variable name" that > it is in turn a variable > In bash shell I would wrote sthg like: > > for x in `seq 1 3` > do > M$i=Material(x) #Material is a python class > done > > Why I need this? Cause I have a python module that obliges me to build > a variable called Period, which should have a variable name of > summands (depends on the value of x) > > #Let's say x=3, then Period definition is > Period=Slab(Material1(12.5)+Material2(25)+Material3(12.5)) #Slab is a > python class > > I dont know how to automatize last piece of code for any x > > thank you > > Marcos It sounds to me like you want python's "eval", based on my understanding of how that bash code should work. It's not that different from eval in bash, though in python you'd need it; in bash you don't in this case. So you could probably do something like (untested): for x in xrange(1,4): eval 'M%d=Material(x)' % x From ghirai at ghirai.com Tue Aug 14 14:10:43 2007 From: ghirai at ghirai.com (Ghirai) Date: Tue, 14 Aug 2007 21:10:43 +0300 Subject: curses library Message-ID: <20070814211043.286b8aa6.ghirai@ghirai.com> Hello list, I need to write a console application. Are there any wrappers around curses/ncurses? Or any other similar libraries? Thanks. -- Regards, Ghirai. From semanticist at gmail.com Fri Aug 17 11:53:07 2007 From: semanticist at gmail.com (Miles) Date: Fri, 17 Aug 2007 11:53:07 -0400 Subject: Getting the result of a process after exec*() In-Reply-To: <1187361196.184025.234020@k79g2000hse.googlegroups.com> References: <1187361196.184025.234020@k79g2000hse.googlegroups.com> Message-ID: On 8/17/07, AndrewTK wrote: > The problem for me is this: once an external process is called via > exec*() the script has effectively fulfilled its task. Is there any > way one can process a file with an external process and continue > further processing in Python; /once the external processing is > completed/? Assuming you're looking at the docs for the os module, instead of the exec*() functions, check out the spawn*() functions, or, to use a subshell, system(). Better yet, take a look at the subprocess module: http://docs.python.org/lib/module-subprocess.html -Miles From thushianthan15 at gmail.com Wed Aug 22 12:13:37 2007 From: thushianthan15 at gmail.com (thushianthan15 at gmail.com) Date: Wed, 22 Aug 2007 09:13:37 -0700 Subject: Python for web development ... Message-ID: <1187799217.054726.109380@z24g2000prh.googlegroups.com> Hi everyone, I have to do a web based application for my final year project. Since, i am only familiar with basic HTML and Java Script, i am totally new to this one. My friends are using LAMP (P->PHP). But i want to use Python. Is it possible to use Python with Apache and MySQL. Is it possible ? Any websites/books ? Thank you From chris.hulan at gmail.com Tue Aug 28 08:41:26 2007 From: chris.hulan at gmail.com (ChrisHulan) Date: Tue, 28 Aug 2007 12:41:26 -0000 Subject: Biased random? In-Reply-To: References: Message-ID: <1188304886.108882.74000@57g2000hsv.googlegroups.com> On Aug 27, 4:42 pm, Ivan Voras wrote: > Hi, > > I have a list of items, and need to choose several elements from it, > "almost random". The catch is that the elements from the beginning > should have more chance of being selected than those at the end (how > much more? I don't care how the "envelope" of probability looks like at > this point - can be linear). I see that there are several functions in > Python standard libraries for various distribution, but is there an easy > pythonic way to make them do what I need? Not sure how pythonic it is...but a simple(?) way to increase the chances for particular elements is to introduce copies. For example given [1,2,3], you can increase the chances of selecting '1' by changing the list to [1,1,2,3]. Cheers Chris From rdm at rcblue.com Sun Aug 12 20:01:19 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 12 Aug 2007 17:01:19 -0700 Subject: A dumb question about a class In-Reply-To: References: Message-ID: <20070813000128.F00771E400B@bag.python.org> At 03:35 PM 8/12/2007, Steven Bethard wrote: >Note that if you just want to iterate over all the primes, there's no >need for the class at all. Simply write:: > > for prime in iter_primes(): Even if I want to test only 1 integer, or want the list of primes in a certain interval, I don't need the class at all: ==================================== import itertools def iter_primes(): # an iterator of all numbers between 2 and +infinity numbers = itertools.count(2) # generate primes forever while True: # get the first number from the iterator (always a prime) prime = numbers.next() yield prime # remove all numbers from the (infinite) iterator that are # divisible by the prime we just generated numbers = itertools.ifilter(prime.__rmod__, numbers) def listPrimes(n,m): """ Returns the list of primes in closed interval [n,m] """ primes = [] for prime in iter_primes(): if prime > m: return primes if n <= prime <= m: primes.append(prime) ============================================ Thanks for your help. I didn't learn much about classes, but appreciated your iter_primes() a lot! Dick Moores From gnewsg at gmail.com Tue Aug 28 21:21:12 2007 From: gnewsg at gmail.com (billiejoex) Date: Tue, 28 Aug 2007 18:21:12 -0700 Subject: tempfile.mkstemp and os.fdopen In-Reply-To: References: <1188323759.955043.317630@19g2000hsx.googlegroups.com> Message-ID: <1188350472.508625.18780@50g2000hsm.googlegroups.com> Thanks all. Another question: I have to open file for writing ('wb') but I noticed that both tempfile.mkstemp() and os.fdopen() accept a "mode" argument. It's not clear *when* do I have to specify such mode. When using tempfile.mkstemp? >>> fileno, name = tempfile.mkstemp(text=False) >>> fd = os.fdopen(fileno) ...or when using os.fdopen()? >>> fileno, name = tempfile.mkstemp() >>> fd = os.fdopen(fileno, mode='wb') Moreover, what happens if I specify "text" mode when using mkstemp and "binary" mode when using fdopen? >>> fileno, name = tempfile.mkstemp(text=True) >>> fd = os.fdopen(fileno, 'wb') PS - I think that tempfile.mkstemp docstring should be enhanced to cover such and other questions (e.g. I find reasonable that every user using tempfile.mkstemp() should use also os.fdopen() in conjunction but this isn't mentioned). From tooru_honda at fast-mail.org Sat Aug 25 23:30:45 2007 From: tooru_honda at fast-mail.org (tooru honda) Date: Sun, 26 Aug 2007 11:30:45 +0800 Subject: Does shuffle() produce uniform result ? References: Message-ID: By incorporating Alex's code, I got another performance boost of 20%. It is mostly due to Alex's more efficient implementation of block random than my own version. -tooru honda Below is the code I have now: from binascii import hexlify from os import urandom class rcRandomC(random.SystemRandom): def __init__(self): random.SystemRandom.__init__(self) def rand2(): while True: randata = urandom(2*1024) for i in xrange(0, 2*1024, 2): yield int(hexlify(randata[i:i+2]),16) # integer in [0,65535] self.rand2_M = rand2().next # modified from random._randbelow def randrange(self,startN,stopN): """Choose a random integer from range(startN, stopN). widthN<=65536 """ widthN=stopN-startN left_over_N=65536%widthN upper_bound_N= 65535-left_over_N random_number=self.rand2_M() while random_number>upper_bound_N: random_number=self.rand2_M() r = random_number%widthN return startN+r def shuffle(self, x): """x, random=random.random -> shuffle list x in place; return None. """ randrange=self.randrange for i in reversed(xrange(1, len(x))): # pick an element in x[:i+1] with which to exchange x[i] j = randrange(0,i+1) x[i], x[j] = x[j], x[i] From ehsan.khoddam at gmail.com Fri Aug 3 14:48:40 2007 From: ehsan.khoddam at gmail.com (Ehsan) Date: Fri, 03 Aug 2007 11:48:40 -0700 Subject: downloading files Message-ID: <1186166920.757662.269340@o61g2000hsh.googlegroups.com> I foundd this code in ASPN Python Cookbook for downloading files in python but when it finished downloading files the files became corrupted and didn't open, the files in internet havn't any problem: def download(url,fileName): """Copy the contents of a file from a given URL to a local file. """ import urllib webFile = urllib.urlopen(url) localFile = open(fileName, 'w') localFile.write(webFile.read()) webFile.close() localFile.close() download('http://www.2shared.com/download/1839752/cd520048/ xpersia14.3gp?tsid=20070803-143313-49566ea2', 'xpersia4.3gp' ) From jon at turnthepage.org Tue Aug 7 16:55:35 2007 From: jon at turnthepage.org (Jon Rosebaugh) Date: Tue, 7 Aug 2007 15:55:35 -0500 Subject: Web based Reporting tool for Python References: <1186460956.945148.162610@k79g2000hse.googlegroups.com> Message-ID: <2007080715553575249-jon@turnthepageorg> On 2007-08-06 23:29:16 -0500, Madhu Alagu said: > Hi > I am looking template based report tools for python.It has the ability > to deliver rich content onto the screen, to the printer or into PDF, > HTML, XLS, CSV and XML files. I don't think this has been implemented in Python because it's a pretty boring thing to do, and things like JasperReports (in Java) and Crystal Reports already have the market pretty well tied up. What my company did was to use JasperReports via a web service we set up. From tenax.raccoon at gmail.com Sun Aug 19 12:40:46 2007 From: tenax.raccoon at gmail.com (Jason) Date: Sun, 19 Aug 2007 16:40:46 -0000 Subject: How to setup pyOpenGL3.0.a6 for window xp? In-Reply-To: <1187397743.937458.301590@q3g2000prf.googlegroups.com> References: <1187395670.267971.88750@q4g2000prc.googlegroups.com> <1187397743.937458.301590@q3g2000prf.googlegroups.com> Message-ID: <1187541646.185788.15310@k79g2000hse.googlegroups.com> On Aug 17, 6:42 pm, Carl Banks wrote: > Windows comes with OpenGL libraries. However, before you can use > OpenGL you'll need a package that can provide an OpenGL context, which > PyOpenGL doesn't do (easily). > > PyGame is the typical choice for most uses. If all you need is a > simple window to draw on, this is the package you want. > > However, it doesn't (easily) work with common GUIs like GTK and Wx. > If you want to use use OpenGL in a GUI app, then you'll want to find > an "OpenGL canvas widget" for that GUI. > > Carl Banks Sorry Carl, but I'm a bit confused with your third paragraph. Do you mean that PyGame doesn't work easily with Wx/GTK, or that OpenGL doesn't work easily with Wx/GTK? If it's the second, then I must disagree. wxPython comes with an OpenGL widget in the "wx.glcanvas" module. The widget only requires PyOpenGL. The wxPython Demo shows how to set up and program the widget quite easily. Another example is at: "http:// aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325392". Unfortunately, I don't have much experience with PyGTK. Their FAQ does indicate that you need an extension to add OpenGL support. --Jason From jarausch at igpm.rwth-aachen.de Wed Aug 1 03:41:52 2007 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Wed, 01 Aug 2007 09:41:52 +0200 Subject: split a string of space separated substrings - elegant solution? In-Reply-To: <1185941803.577841.178550@l70g2000hse.googlegroups.com> References: <46af9beb$0$14242$ba620e4c@news.skynet.be> <1185941803.577841.178550@l70g2000hse.googlegroups.com> Message-ID: <46B03940.8020105@igpm.rwth-aachen.de> Many thanks to all of you! It's amazing how many elegant solutions there are in Python. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From knjaz0 at gmail.com Tue Aug 14 17:47:07 2007 From: knjaz0 at gmail.com (knjaz) Date: Tue, 14 Aug 2007 14:47:07 -0700 Subject: Air conditioners for cars Message-ID: <1187128027.172562.125190@g4g2000hsf.googlegroups.com> Everything you need to know about car air conditioners... http://car-air-conditioning.blogspot.com/ From mikael at isy.liu.se Wed Aug 15 12:44:30 2007 From: mikael at isy.liu.se (Mikael Olofsson) Date: Wed, 15 Aug 2007 18:44:30 +0200 Subject: Combinatorial of elements in Python? In-Reply-To: <9e2f512b0708150651g7a9834cdm2db874d84804e362@mail.gmail.com> References: <9e2f512b0708142203m782b0e10s817fb4d061ba0e46@mail.gmail.com> <46C2F538.8000900@isy.liu.se> <9e2f512b0708150651g7a9834cdm2db874d84804e362@mail.gmail.com> Message-ID: <46C32D6E.7070804@isy.liu.se> Sebastian Bassi wrote: > Hello, could you do it for an indefinite number of elements? You did > it for a fixed (2) number of elements. I wonder if this could be done > for all members in a dictionary. What is unclear here is in what order the keys should be visited. The following assumes that the keys should be considered in alphanumeric order. >>> def combine(d): if not d: return [] elif len(d)==1: return d.values()[0] else: keys = d.keys() keys.sort() leftKeys = keys[0:len(keys)//2] rightKeys = keys[len(keys)//2:] leftDict = dict((key,d[key]) for key in leftKeys) rightDict = dict((key,d[key]) for key in rightKeys) return [x+y for x in combine(leftDict) for y in combine(rightDict)] >>> A={'field1':['a','A'],'field2':['b','B'],'field3':['c','C'],'field4':['d','D']} >>> combine(A) ['abcd', 'abcD', 'abCd', 'abCD', 'aBcd', 'aBcD', 'aBCd', 'aBCD', 'Abcd', 'AbcD', 'AbCd', 'AbCD', 'ABcd', 'ABcD', 'ABCd', 'ABCD'] HTH again /MiO From steve at holdenweb.com Sun Aug 12 13:54:13 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 12 Aug 2007 13:54:13 -0400 Subject: Regular Expression Grouping In-Reply-To: <1186939262.144073.182450@z24g2000prh.googlegroups.com> References: <1186939262.144073.182450@z24g2000prh.googlegroups.com> Message-ID: linnewbie at gmail.com wrote: > Fairly new to this regex thing, so this might be very juvenile but > important. > > I cannot understand and why 'c' constitutes a group here without being > surrounded by "(" ,")" ? > >>>> import re >>>> m = re.match("([abc])+", "abc") >>>> m.groups() > ('c',) > > Grateful for any clarity. > What's happening there is that the same group is being used three times to complete the match, but a group can only be represented once in the output, so you are seeing the last substring that the group matched. Contrast with: >>> m = re.match("([abc]+)", 'abc') >>> m.groups() ('abc',) >>> I don't *think* there's any way to introduce a variable number of groups into your match, but I don't use re's that much so someone may be able to help if that's what you want. Is it? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bdesth.quelquechose at free.quelquepart.fr Thu Aug 30 06:54:10 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 30 Aug 2007 12:54:10 +0200 Subject: Pivy problem and some other stuff In-Reply-To: <1188501707.593319.23330@m37g2000prh.googlegroups.com> References: <1188501707.593319.23330@m37g2000prh.googlegroups.com> Message-ID: <46d73fde$0$421$426a74cc@news.free.fr> azrael a ?crit : > Hy Guys > > Did anyone manage to install and use Pivy. I'm trying it and cant come > closer to the goal I get the message: > Please set the COIN3DDIR environment variable to your Coin root > directory! ** Aborting ** > > Familiar to anyone? > I don't even know what Pivy is, but it obviously wants you to set an environment variable (how you do so depends on your environment - on most linux distros, and AFAIK on most unix systems, it's usually done in your ~/.bash_profile file) named COIN3DIR and pointing to a directory !-) From gherzig at fmed.uba.ar Thu Aug 16 16:16:23 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Thu, 16 Aug 2007 17:16:23 -0300 Subject: advice about `correct' use of decorator Message-ID: <46C4B097.4080309@fmed.uba.ar> Hi all. I guess i have a conceptual question: Im planing using a quite simple decorator to be used as a conditional for the execution of the function. I mean something like that: @is_logued_in def change_pass(): bla bla And so on for all the other functions who needs that the user is still loged in. where obviosly the is_logued_in() function will determine if the dude is still loged in, and THEN execute change_pass(). If the dude is not loged in, change_pass() is NOT executed at all. Instead, it will be redirected to the `login' screen. Something in my mind tells me that this is not the pythonic way...But i like the idea, so please tell me that im in the right way :) Cheers. Gerardo From no_mail at someprovider.it Thu Aug 30 05:19:45 2007 From: no_mail at someprovider.it (lupino) Date: Thu, 30 Aug 2007 11:19:45 +0200 Subject: Python doesn't see the directories I create References: Message-ID: <20070830111945.58edf6a4@localhost> Ciao mr_gadget, > When I create a subfolder, python is not seeing it. Can someone please > explain this behaviour ? I just started with python, read the tutorial over > the weekend and am writing my very first script. So I may not be seeing > something. Both os.path and glob.glob seem not to see a folder I created. > Other sibling folders seem to work fine. On a whim I tried paths with \\ > double slashes and that worked. But why should single slashes work for some > folders and not for others ?? Instead of relying on your own error-prone ability of using forward and back slashes as path separators, try to get as much as possible from python. ;) You can use os.sep as a cross-platform path separator, instead of forward slashes or escaped back slashes. Moreover you can use the os.path.join function to let python take care of your problem. :) >>> os.path.join("C:", "Programs", "MySubFolder") 'C:/Programs/MySubFolder' HTH, -- [ Andrea Spadaccini - a.k.a. lupino3 - GLUGCT - from Catania - ICQ : 91528290 ] [ GPG ID: 5D41ABF0 - key on keyservers - Debian GNU / Linux - Kernel 2.6.18.4 ] [ Linux Registered User 313388 - a(dot)spadaccini(at)catania(dot)linux(dot)it ] [ Computers are high-speed idiots, programmed by low-speed idiots ] From steve at holdenweb.com Thu Aug 9 09:17:08 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 09 Aug 2007 09:17:08 -0400 Subject: check if regeular expression has results In-Reply-To: <1186664302.050036.302670@g4g2000hsf.googlegroups.com> References: <1186664302.050036.302670@g4g2000hsf.googlegroups.com> Message-ID: shahargs at gmail.com wrote: > Hi, > I'm looking for the best way to check if regular expression return > true (it's mean - there is a match). for example, i want "if" that > check if this regular expression: .*born.*to.* has a match. > > What's the way to do that simply? > A failed match returns None. A successful match returns a match object. So the easiest way to check for a successful match is pat = re.compile(...) .... m = pat.match(some_string) if m: ... you got a match ... else: ... you didn't ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From digitalplusmail at gmail.com Wed Aug 15 10:28:46 2007 From: digitalplusmail at gmail.com (Lepi Duja) Date: Wed, 15 Aug 2007 14:28:46 -0000 Subject: Free Air Conditioners!!!!! Message-ID: <1187188126.751546.129520@w3g2000hsg.googlegroups.com> Air conditioning http://airconditionerslinks.blogspot.com/ From gagsl-py2 at yahoo.com.ar Sun Aug 19 14:40:45 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 19 Aug 2007 11:40:45 -0700 Subject: ctypes and unsigned char* In-Reply-To: <1187545486.797017.308720@a39g2000hsc.googlegroups.com> References: <1187545486.797017.308720@a39g2000hsc.googlegroups.com> Message-ID: <1187548845.674582.69630@w3g2000hsg.googlegroups.com> On 19 ago, 14:44, "oliver.andr... at gmail.com" wrote: > Hi, > > can anybody with ctypes experience tell me, how to handle a C function > that returns an unsigned char*? Obviously it is not a restype of > c_char_p. Being signed or unsigned is not important here. But you have to disambiguate "returns an unsigned char*" - the function returns a string of bytes (unsigned char), null- terminated. - the function returns a pointer to a single byte. In the first case, use a plain c_char_p - the individual "chars" are already unsigned in Python (that is, ord(xxx[i]) is always positive) In the second case, first define the pointer type: c_ubyte_p = POINTER(c_ubyte) your_function.restype = c_ubyte_p -- Gabriel Genellina From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Aug 13 16:15:19 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 13 Aug 2007 22:15:19 +0200 Subject: wxPython - drawing without paint event References: <1186710391.148396.113490@d30g2000prg.googlegroups.com> <1186738813.373909.96230@x35g2000prf.googlegroups.com> <1186796567.331348.42450@q3g2000prf.googlegroups.com> <5i5l0dF2lortaU1@mid.individual.net> <1186883988.585048.16590@m37g2000prh.googlegroups.com> <5i8befF3o5no1U1@mid.individual.net> <1186928595.014008.61950@b79g2000hse.googlegroups.com> <5i98bsF3nmbavU1@mid.individual.net> <1186951326.218981.17820@b79g2000hse.googlegroups.com> <1186966731.768800.81620@x40g2000prg.googlegroups.com> Message-ID: <5ibsenF3nq29uU2@mid.individual.net> kyosohma at gmail.com wrote: > While the book does have issues, it is better (in my opinion) than > the only published Tkinter book, although both books are now > outdated. Outdated to a certain limit. It's quite a bit more recent than those many tutorials around still today using "from wxpython.wx import *". > As with all programming, if you don't practice, you won't learn. True. Regards, Bj?rn -- BOFH excuse #103: operators on strike due to broken coffee machine From rcdailey at gmail.com Mon Aug 20 15:49:01 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 20 Aug 2007 14:49:01 -0500 Subject: str().join() isn't working In-Reply-To: <1187634895.387910.179500@m37g2000prh.googlegroups.com> References: <496954360708200905i2100b32ag5983ab729e5d216f@mail.gmail.com> <1187634895.387910.179500@m37g2000prh.googlegroups.com> Message-ID: <496954360708201249y1db0aa14qf0de14538fb51b9d@mail.gmail.com> Hi all, Thanks for your response. I figured out the issue. I was using list.append() to append another list, when I should have been using expand(). Sorry for the confusion. On 8/20/07, kyosohma at gmail.com wrote: > On Aug 20, 1:16 pm, "Robert Dailey" wrote: > > here is a more realized example of the lists I'm trying to join: > > > > _user_includes = [ > > "../src", > > "../resource", > > "../inc", > > "../src", > > "../data", > > "../gui", > > "../script", > > "../script/actions", > > "../gui/dispatch", > > "../gui/factories", > > "../gui/frames", > > "../gui/getters", > > "../gui/localization", > > "../gui/player", > > "../gui/setters", > > "../gui/utilities", > > "../sis", > > "../player", > > "../platform/ngi", > > "../../engine", > > "../../engine/audio/NGI", > > "../../engine/io", > > "../../engine/io\NGI", > > "../../engine/math", > > "../../engine/math/fixed", > > "../../engine/path/NGI", > > "../../engine/text/NGI", > > "../../engine/mem", > > "../../engine/text", > > "../../engine/observer", > > "../../sdk/tiny_xml", > > "../../sdk/zlib", > > "../../sdk/lpng", > > "../../sdk/IFDLib/Source/Precompile", > > "../../sdk/IFDLib/Source/CoreLib", > > "../../sdk/IFDLib/inc", > > "../../sdk/IFDLib/Source/UtilLib", > > "../../sdk/IFDLib/Source/GameLib", > > "../../sdk/IFDlib/Source/OSLib/_NGI", > > "../../sdk/stl-port/NGI", > > "../../sdk/mini-boost/NGI", > > "../../sdk/mini-boost/COMMON", > > ] > > > > _system_includes = [ > > "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include", > > "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include/osextensions/rga", > > "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include/osextensions/stdapis", > > "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/EPOC32/include/osextensions/stdapis/stlport", > > "../../../../../../Symbian/9.1/NGAGE_SDK_1.1/epoc32/include/variant" > > ] > > > > On 8/20/07, Robert Dailey wrote: > > > > > Hi, > > > > > First have a look at the following code: > > > > > In main.py: > > > ----------------------------------------------------------------------------------- > > > space = " " > > > > > includes = space.join ( system._user_includes ) + " " + space.join( > > > system._system_includes ) > > > > > In system.py: > > > ----------------------------------------------------------------------------------- > > > _user_includes = [ > > > ] > > > > > _system_includes = [ > > > ] > > > > > The above does not work. The interpreter states: "TypeError: sequence item > > > 0: expected string, list found". I'm not sure what this means. Can anyone > > > help me figure out what I'm doing wrong? Thanks. > > > > > PS: I've also tried putting strings in the lists above just to make sure > > > that them being empty wasn't the problem. I got no different results. > > When you use join, you join the items in the list with each other to > form one long string. In your statement, your script tries to > concatenate 2 lists to each other before it does the join, which is > impossible in Python. The "+" operator is only for addition and for > two or more strings. > > See http://www.faqs.org/docs/diveintopython/odbchelper_join.html for > more information on joins. > > Mike > > -- > http://mail.python.org/mailman/listinfo/python-list > From CarpeSkium at gmail.com Thu Aug 2 06:43:21 2007 From: CarpeSkium at gmail.com (CarpeSkium at gmail.com) Date: Thu, 02 Aug 2007 10:43:21 -0000 Subject: Use variable in regular expression Message-ID: <1186051401.122847.114690@d55g2000hsg.googlegroups.com> I know I can use a variable in regular expressions. I want to use a regex to find something based on the beginning of the string. I am using yesterday's date to find all of my data from yesterday. Yesterday's date is 20070731, and assigned to the variable "yesterday_date". I want to loop thru a directory and find all of the yesterday's data ONLY IF the feature class has the date at the BEGINNING of the filename. Sample strings: 20070731_test1 Copy20070731_test1 20070731_test2 Copy20070731_test2 20070731_test3 Copy20070731_test3 I don't want the one's that start with "Copy". I can't figure out the syntax of inserting the "^" into the regex. I've tried all of the following, with no luck: re.compile(^yesterday_date) re.compile(r'^yesterday_date') re.compile(r'^[yesterday_date]') re.compile(r'[^yesterday_date]') I don't know what I'm doing and I'm just guessing at this point. Can anyone help? Thanks. Mark From larry.bates at websafe.com Tue Aug 14 08:06:06 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 14 Aug 2007 07:06:06 -0500 Subject: Drawing a graph In-Reply-To: References: Message-ID: <46C19AAE.4010009@websafe.com> Ghirai wrote: > Hello list, > > I need to draw a graph, 2 axes, 2D, nothing fancy. > One of the axes is time, the other one is a series of integers. > > I don't care much about the output format. > > Are there any specialized libraries for this, or should i use PIL? > > Thanks. > ReportLab graphics works for me. www.reportlab.org -Larry From hg at nospam.org Sun Aug 26 18:47:26 2007 From: hg at nospam.org (hg) Date: Sun, 26 Aug 2007 22:47:26 GMT Subject: ANN: SCF released GPL Message-ID: <2qnAi.21495$eY.19028@newssvr13.news.prodigy.net> Dear all, I am releasing much of my work including SCF (Cross platform Smart Card library & Tools written in Python) to the GPL license. If interested, go to http://www.SnakeCard.com/Source.html I am moving the doc to doxygen and cleaning up the code, so what you'll see there will change in the course of the next few weeks - basically can only get meaningful info on the classes hierarchy at this stage. I am looking for a free subversion server resource to put the code ... if you know of any. Some of the work there will be windows-only related (GINA, activeX components ... and not coded in Python) and the applets JavaCard and BasicCard ... I'm releasing these during the next few days. Regards, hg From zyzhu2000 at gmail.com Mon Aug 20 13:50:49 2007 From: zyzhu2000 at gmail.com (beginner) Date: Mon, 20 Aug 2007 17:50:49 -0000 Subject: 'REPL' style IDE Message-ID: <1187632249.748945.158910@i13g2000prf.googlegroups.com> Hi Everyone, I am using the Wing IDE. It works great when developing applications, but the workflow is like Visual Studio -- after you execute it or debug it, the python script ends. What I want is an interactive interpreting environment. I want the IDE to execute a boot script to initialize my environment and create some basic data objects. And then I want to be able to type in command on the command line using these objects. The IDLE that comes with Python does this, but compared with Wing, it does not have a lot of the convenient features. I am wondering if there is anything more powerful than IDLE that can do this. Thanks, Geoffrey From bj_666 at gmx.net Thu Aug 16 02:34:38 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Aug 2007 06:34:38 GMT Subject: replacement for string.printable References: <5ih0vlF3mc1akU2@mid.uni-berlin.de> Message-ID: <5ii9ftF3pp59iU1@mid.uni-berlin.de> On Wed, 15 Aug 2007 23:15:12 +0100, John K Masters wrote: > help('string') > > DESCRIPTION > Warning: most of the code you see here isn't normally used nowadays. > Beginning with Python 1.6, many of these functions are > implemented as methods on the standard string object. They used to be > implemented by a built-in module called strop, but strop is now > obsolete itself. > > Beginning with Python 1.6 > > We are now way past 1.6. Are you sure the string module is still being > added to? The `string.Template` class was added in Python?2.4: http://docs.python.org/lib/node40.html Ciao, Marc 'BlackJack' Rintsch From conra2004 at yahoo.com Tue Aug 14 03:27:46 2007 From: conra2004 at yahoo.com (yadin) Date: Tue, 14 Aug 2007 00:27:46 -0700 Subject: about negative polar plots Message-ID: <1187076466.955318.249250@57g2000hsv.googlegroups.com> hi am doing a polar plot of the radiation pattern of an antenna. the polar plots represents the value of the power in dB's and the dB go from -40dB to 0dB as the angle theta changes from 0 to 2*pi rads the polar plot in python goes with positive values how can i solve this problem rough example example: power = arange(-40,0,-10) theta = arange(0, 2pi,pi/12) polar(power,theta) title.....? how can i show the step on the polar plot plot(-40, -30,-20,-10,0) From bronger at physik.rwth-aachen.de Fri Aug 24 06:59:28 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 24 Aug 2007 12:59:28 +0200 Subject: Co-developers wanted: document markup language References: <87odgyyx9u.fsf@wilson.homeunix.com> <87tzqpew22.fsf@wilson.homeunix.com> <87tzqp77my.fsf@wilson.homeunix.com> <7xy7g1if24.fsf@ruckus.brouhaha.com> <87mywh717i.fsf@wilson.homeunix.com> Message-ID: <878x816vvz.fsf@wilson.homeunix.com> Hall?chen! Wildemar Wildenburger writes: > [...] > >> Well, because they are awful. ;-) I don't see that there is a >> bunch of already existing projects, in fact, I don't see anyone >> challenging LaTeX at all. However, competition is a good thing, >> and I think there are enough aspects about LaTeX that can be done >> better so that this project is worth being done. > > Well there is ConTeXt . I've > never actually used it, but from reading the docs I deem it a very > attractive alternative to LaTeX. That's right, I failed to mention ConTeXt, which really is a competitor to LaTeX. I even took one good idea from context, namely the availability of syntax elements in different human languages. However, ConTeXt documents are as much cluttered as LaTeX. ConTeXt is a huge system with the aim of fine control on the PDF layout. Therefore, it is even harder to convert it to HTML than it is for LaTeX. Besides, I never managed to comprehend its documentation. It has its good aspects, too, but these are the reasons why I don't think that it would be a good starting point for improving the situation with plain text document markup languages. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From pavlovevidence at gmail.com Fri Aug 24 20:04:12 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 24 Aug 2007 17:04:12 -0700 Subject: py2exe/distutils: how to include a tree of files? In-Reply-To: <13cukd39lgsfgb4@corp.supernews.com> References: <13cuhdr58m5one7@corp.supernews.com> <13cukd39lgsfgb4@corp.supernews.com> Message-ID: <1188000252.290854.289870@q4g2000prc.googlegroups.com> On Aug 24, 5:46 pm, Grant Edwards wrote: > On 2007-08-24, Grant Edwards wrote: > > > I'm packaging up a python program and need to include an entire > > directory tree in the distribution. > > I've cobbled together something using package_dir/package_data > and os.path.walk(), but it seems like a bit of a kludge... "data_files" is documented in the official distutils documentation. (Yes, in regular distutils you do have to pretty much walk the data directories to get your data.) I guess the idea was that you would use the same setup.py for building, installing, and packaging (source and py2exe). But it doesn't work all that well in practice, because using "data_files" is rather useless for non-py2exe packaging since you could never be sure where distutils actually installed the data files. (You could only guess, based on the location of the script files, and even that was shaky because of a bug if the user installed it with --prefix.) The packages I use all seem to avoid this difficulty by placing data in the package directories, alongside the py files. I suppose because "data_files" wasn't too helpful, there was never much incentive to improve it. Which (getting back to py2exe) is unfortunate since you CAN rely on the location when using py2exe, but it is stuck with the unwieldy usage. Oh well. Carl Banks From NO_Kroeger at gmx.de Wed Aug 22 14:06:28 2007 From: NO_Kroeger at gmx.de (=?ISO-8859-1?Q?Nils_Oliver_Kr=F6ger?=) Date: Wed, 22 Aug 2007 20:06:28 +0200 Subject: Threads and racing conditions In-Reply-To: <5fb10ac20708212126j70f8100bka66fe5e3661904cc@mail.gmail.com> References: <5fb10ac20708212126j70f8100bka66fe5e3661904cc@mail.gmail.com> Message-ID: <46CC7B24.5090103@gmx.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Flavio Preto schrieb: > Hi, > > I have a doubt. Supose that i have the minimun class below: > > class db: > def __init__(self): > self.db = {} > def read(self, key): > return self.db[key] > def write(self, key, value): > self.db[key] = value > > > and an object of this class is shared among some threads. Is it possible > that in a read, the method return a value that is not an old or a new value? > In other words, is it possible that a 'read' return (due to a 'write' at the > same time by another thread) an invalid value that was never supposed to be > there? > > Thanks, > Flavio Preto > > Make the class thread safe by using Lock or RLock ... that will save you a lot of trouble. Your limited example might or might not work, but once your class gets more complex you will most likely run into serious problems. Greetings Nils -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGzHsizvGJy8WEGTcRAgN1AJ42cM1P/NW7Ei3F5ViSsmTcKDvCIgCeIUGG GD7DAb3f+Lmcav663F+wkQg= =kJ0G -----END PGP SIGNATURE----- From mail at microcorp.co.za Fri Aug 3 02:38:18 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 3 Aug 2007 08:38:18 +0200 Subject: i am new to python-Please somebody help References: <1186047103.673871.150460@z24g2000prh.googlegroups.com><1186063842.827016.95030@q3g2000prf.googlegroups.com> <1186081737.357371.232040@i13g2000prf.googlegroups.com> Message-ID: <00fa01c7d59b$9672c6a0$03000080@hendrik> "gregarican" wrote: > Maybe it's just me but the word "grovelling" just doesn't ring of > newbie friendliness. To each their own I guess. Kind of like the > Smalltalk list where a few respondents are really dry. Someone will > post asking something like "Can I use Smalltalk to do X so that it > talks to Y?" One guy (without pointing to a link or offering a > snippet) just posts "Yes." I guess literally they have contributed. Or > someone calls your house and asks, "Is so-and-so there?" You just say > "Yes" and hang up on them :-) Or at table - "Can you pass the salt?" "Yes" < a brief hiatus, laden with unfulfilled expectations and no action > "Please pass me the salt" "Certainly - there you are." On the subject of "grovelling" - this refusal to tug, and to condone tugging at forelocks, may be a Southern Hemisphere affliction. Don't like it myself. - Hendrik From siona at chiark.greenend.org.uk Thu Aug 2 07:44:56 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 02 Aug 2007 12:44:56 +0100 (BST) Subject: Use variable in regular expression References: <1186051401.122847.114690@d55g2000hsg.googlegroups.com> Message-ID: <4Ym*UdhRr@news.chiark.greenend.org.uk> wrote: >I know I can use a variable in regular expressions. I want to use a >regex to find something based on the beginning of the string. You're coming from a Perl background, right? No-one else would think of using a regexp for such a simple thing. There are two things you need to learn: (a) Python doesn't do automatic variable interpolation in strings. (b) For simple find and replace operations, there are string methods which are easier and faster than regexps. >Yesterday's date is 20070731, and assigned to the variable >"yesterday_date". I want to loop thru a directory and find all of the >yesterday's data ONLY IF the feature class has the date at the >BEGINNING of the filename. > >Sample strings: >20070731_test1 >Copy20070731_test1 >20070731_test2 >Copy20070731_test2 >20070731_test3 >Copy20070731_test3 > >I don't want the one's that start with "Copy". >>> "20070731_test1".startswith(yesterday_date) True >>> "Copy20070731_test1".startswith(yesterday_date) False -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From ca.allen at gmail.com Mon Aug 20 17:47:56 2007 From: ca.allen at gmail.com (Chris Allen) Date: Mon, 20 Aug 2007 14:47:56 -0700 Subject: Newbie question about a web server In-Reply-To: <1187593367.402094.235410@g4g2000hsf.googlegroups.com> References: <1187593367.402094.235410@g4g2000hsf.googlegroups.com> Message-ID: <1187646476.945061.169110@r23g2000prd.googlegroups.com> On Aug 20, 12:02 am, Frank Millman wrote: > Hi all > > I have just started to dabble in writing my own web server. > > I googled for 'python web server', and this is the first hit - > > http://fragments.turtlemeat.com/pythonwebserver.php > > It has the source code for a simple web server, based on HTTPServer > and BaseHTTPRequestHandler. > > It demonstrates the concepts of > - returning a static page > - constructing and returning a dynamic page > - sending a form with a POST method, and responding to the result > > I typed it in and ran it, and it 'just worked', with one exception. > > When responding to the initial request, it sends a 200 response, > followed by a content-type header, followed by an html page. This > works fine. > > When responding to the POST data received, it sends a 301 response, no > headers, and then the html page. > > This works with a Firefox browser on Linux, but MSW IE6 displays 'the > page cannot be displayed'. > > According to the notes, "You don't have to know much about the HTTP > protocol at all. Except some basic that when the client request > something it is a "GET", and when the client sends something it is in > our case a POST. Some basic responce codes like 200 is OK for GET, and > 404 is file not found, 301 is OK for a Post." > > I googled for 'http response code 301', and found that it is actually > a redirection code. It seems that the notes are misleading. > > So I guess my questions are - > 1. what is the correct response for a POST? > I think the answer is 200. > However, I assume the author is trying to demonstrate a > particular technique. > Can anyone explain what that may be. > 2. why does the above work with Firefox? > > TIA for any enlightenment. > > Frank Millman Yes HTTP response code 200 does indicate a normal response. What you really need to look at to build an HTTP server is is the RFC for HTTP. It is HTTP 1.1 is RFC 2616 and you can view it here: http://www.faqs.org/rfcs/rfc2616.html That should get you on your way... From rrs at researchut.com Tue Aug 14 23:14:04 2007 From: rrs at researchut.com (Ritesh Raj Sarraf) Date: Wed, 15 Aug 2007 08:44:04 +0530 Subject: Module imports during object instantiation References: <4c3vo4-u7k.ln1@learner.hq.netapp.com> <46c16ec9$0$405$426a34cc@news.free.fr> Message-ID: Neil Cerutti wrote: >> >> Doesn't __init__ get called automatically ? > > It gets called automatically when you construct an instance of > the class in which it's defined. I am a little confused by your statements now. In my earlier posts in the same thread, I gave some code example which was something like this: class Log: def __init__(): if os.name == 'posix': try: import foobar except ImportError, e: print >> sys.stderr, e (Sorry for the bad indentation) Now, what do you mean here by "construct an instance of the class in which it is defined" ? __init__() _is_ defined in the Log class and I try to create an instance of the class Log as: log = Log() Assuming it is run on a box which is POSIX compliant, the try/import should fail and I should see an error message because there is no module named foobar. But I don't see that. And this is what exactly I wanted to get clarified in this whole thread. (But still haven't got a clear answer to a Yes/No). Or am I terribly missing something that you are trying to tell ? Ritesh -- If possible, Please CC me when replying. I'm not subscribed to the list. From mccredie at gmail.com Tue Aug 28 20:25:15 2007 From: mccredie at gmail.com (Matimus) Date: Wed, 29 Aug 2007 00:25:15 -0000 Subject: Pythonic way of reading a textfile line by line without throwing an exception In-Reply-To: References: <1ab7b8470708281647g59e685ect371f20aaea30b070@mail.gmail.com> Message-ID: <1188347115.998206.111790@z24g2000prh.googlegroups.com> > fp=open(filename, 'r') > for line in fp: > # do something with line > > fp.close() Or, if you are using Python 2.5+, you can use the file context via the `with' statement. [code] from __future__ import with_statement # this line won't be needed in Python 2.6+ with open(filename, 'r') as fp: for line in fp: # do something with line [/code] This basicly just closes the file automatically (even if there is an exception) when the context (part indented under `with') is exited. This is a new feature, but probably the most pythonic way of doing it. That will be especially true in the future. Matt From dstromberg at datallegro.com Thu Aug 23 12:48:53 2007 From: dstromberg at datallegro.com (Dan Stromberg - Datallegro) Date: Thu, 23 Aug 2007 09:48:53 -0700 Subject: Socket recv(1) seems to block instead of returning end of file. References: Message-ID: On Thu, 23 Aug 2007 11:54:01 +0200, Hendrik van Rooyen wrote: > > While doing a netstring implementation I noticed that if you > build a record up using socket's recv(1), then when you close > the remote end down, the recv(1) hangs, despite having a short > time out of 0.1 set. > > If however, you try to receive more than one char, (I tested with 3, > did not try 2), then when you shut the remote end down you do not > get a time out, but an empty string - the normal end of file, I suppose. > > Has anybody else seen this behaviour? > > The transmit side seems to give a broken pipe error, which is fine. > > I am using stock standard SuSe 10, Python 2.4, out of the box. > > - Hendrik Are you using sock.settimeout()? I've always done timed-out sockets in python using select; IINM, the settimeout method is a new addition. I agree with Grant though - posting a minimal snippet of code that replicates the problem would help us help you. In fact, it might help you help yourself :) From steve at holdenweb.com Tue Aug 7 02:39:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 07 Aug 2007 02:39:05 -0400 Subject: read(size=-1) In-Reply-To: <1186466817.747723.87910@19g2000hsx.googlegroups.com> References: <1186466817.747723.87910@19g2000hsx.googlegroups.com> Message-ID: 7stud wrote: > Suppose I write: > > f = open("myimg.jpg") > f.read(10) > > > According to the docs, > ----------- > read([size]) > > Read at most size bytes from the file....The bytes are returned as a > string object. > ---------- > > How does python convert a byte to a string? > Each byte of the file occupies one character in the string. As you could have found out (more quickly than posting!) by actually typing your example into an interpreter. >>> f = open('desktop01-real.jpg') >>> f.read(10) '\xff\xd8\xff\xe0\x00\x10JFIF' >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bdesth.quelquechose at free.quelquepart.fr Wed Aug 22 01:48:18 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 22 Aug 2007 07:48:18 +0200 Subject: How to replace a method in an instance. In-Reply-To: <1187971953.261328.219000@q3g2000prf.googlegroups.com> References: <1187971953.261328.219000@q3g2000prf.googlegroups.com> Message-ID: <46cf2ba2$0$30562$426a74cc@news.free.fr> kyosohma at gmail.com a ?crit : > On Aug 24, 11:02 am, "Steven W. Orr" wrote: > >>In the program below, I want this instance to end up calling repmeth >>whenever inst.m1 is called. As it is now, I get this error: >> >>Hello from init >>inst = <__main__.CC instance at 0x402105ec> >>Traceback (most recent call last): >> File "./foo9.py", line 17, in ? >> inst.m1() >>TypeError: repmeth() takes exactly 1 argument (0 given) >> >>#! /usr/bin/python >>def repmeth( self ): >> print "repmeth" >> >>class CC: >> def __init__( self ): >> self.m1 = repmeth >> print 'Hello from init' >> >> def m1 ( self ): >> print "m1" >> >>inst = CC() >>inst.m1() >> >>TIA >> > > Remove "self" from repmeth as it's not required in a function, only in > functions that are defined within a class. Obviously wrong. 'self' (or whatever-you-name-it) as first arg is mandatory for functions used as instance methods. The fact that a function is defined outside a class doesn't mean it cannot be used as a method... > Of course, a function in a > class is also know as a method. Less obvious but still wrong !-) A function object, whereever (and however) it's defined, is a function object, not a method objet. Now what happens is that functions defined inside a class are wrapped in method (by default, instancemethod) objects. To be more accurate - and talking only about how it works for new-style classes - function objects implements the descriptor protocol, so when a function is a class attribute (which is what happens when the function is defined in the class statement's body), and is looked up on an instance, it returns an instancemethod object that has the instance and the function as attributes. This instancemethod object is itself callable, and when called returns the result of calling the function with the instance as first argument. classmethods and staticmethods are variants fo this scheme, calling the function with either the class as first arg (for classmethods) or just as-is (for staticmethods). Now when you set a function as an *instance* (not class) attribute, the descriptor protocol isn't invoked (it only works on class attributes), so if you want to use the function as a method, you have to do the wrapping by yourself (cf my other answer to the OP). HTH From steve at holdenweb.com Sun Aug 12 21:59:32 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 12 Aug 2007 21:59:32 -0400 Subject: Hex editor - Python beginner's code open to review In-Reply-To: <1186967504.796928.264650@l22g2000prc.googlegroups.com> References: <1186967504.796928.264650@l22g2000prc.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Aug 10, 10:36 pm, CC wrote: >> Hi: >> >> http://web.newsguy.com/crcarl/python/hexl.py >> >> This is my first Python program other than tutorial code snippet >> experimentation. I chose a hex line editor. I may do a hex screen >> editor once this is done, if I feel like playing with the curses module. >> Or move straight to wxPython. >> >> This is unfinished, and is really just a hex viewer at this point. It >> seems like a good point to stop and see what others think. I would be >> interested to hear any comments. >> >> My command parsing if of course crude, brute-force, and not very >> scalable. I am doing some reading on this subject, and will be trying >> to do a more generalized approach in the next revision. This is going >> to be a subject where I need to learn a lot, because I have 2-3 >> embedded applications in C that need varying levels of command parsers, >> so I will be seeking to improve this skill considerably. >> >> Thanks for input. >> >> -- >> _____________________ >> Christopher R. Carlen >> cr... at bogus-remove-me.sbcglobal.net >> SuSE 9.1 Linux 2.6.5 > > Looks like mostly clean code to me. I don't understand why you declare > "Offset" globally twice. Wouldn't it make more sense to just stick it > at the top of the file like your "Hexdigits" variable? I'm also not > sure if your style follows the style guide...then again, mine probably > doesn't either. You can check it out here though: > > http://www.python.org/doc/essays/styleguide.html > Nowadays the standard for Python style is PEP 8, which represents an update on the above. http://www.python.org/dev/peps/pep-0008/ > Rather than using if/else statements for error checking, you may want > to consider using try/except: > > http://docs.python.org/tut/node10.html > > That my 2?! > "if" statements are best if the errors are predictable, "try/except"for the less predictable ones, or when it would be difficult to ensure correct program flow with "if". regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bj_666 at gmx.net Tue Aug 7 12:43:21 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Aug 2007 16:43:21 GMT Subject: Adding a list of descriptors to a class References: <1186503932.110835.293640@x40g2000prg.googlegroups.com> Message-ID: <5hrlp9F3ldifeU6@mid.uni-berlin.de> On Tue, 07 Aug 2007 09:25:32 -0700, Bob B. wrote: > Ok, that "exec" is an ugly hack. There's gotta be someway to plop > this straight into the class's __dict__ without doing that, but when I > try adding self.__class__.__dict__[attr] = MyDesc(attr) in MyClass's > __init__ method, I get the error: "TypeError: 'dictproxy' object does > not support item assignment" Does ``setattr(self.__class__, attr, MyDesc(attr))`` work? Ciao, Marc 'BlackJack' Rintsch From nytrokiss at gmail.com Mon Aug 13 12:49:49 2007 From: nytrokiss at gmail.com (James Matthews) Date: Mon, 13 Aug 2007 09:49:49 -0700 Subject: which IDE is highly recommended in Windows OS In-Reply-To: <1186993664.769976.109710@r34g2000hsd.googlegroups.com> References: <1186970945.403792.51790@d55g2000hsg.googlegroups.com> <1186993664.769976.109710@r34g2000hsd.googlegroups.com> Message-ID: <8a6b8e350708130949o4482471ax9f12fca866f00b70@mail.gmail.com> www.wingide.com On 8/13/07, Ge Chunyuan wrote: > > On Aug 13, 10:24 am, _spitFIRE wrote: > > -----BEGIN PGP SIGNED MESSAGE----- > > Hash: SHA1 > > > > Ge Chunyuan wrote: > > > hi Group: > > > > > I am a new comer for Python, I wonder which IDE is recommended in > > > Windows OS. > > > Can anyone give some suggestion. > > > > > Thanks indeed > > > Ge Chunyuan > > > > - - Stani's Python Editor > > ( > http://www.softpedia.com/get/Programming/Coding-languages-Compilers/S...) > > - - Black Adder (http://www.thekompany.com/products/blackadder/) > > - - Zeus (http://www.zeusedit.com/python.html) > > - - PyScripter (http://mmm-experts.com/Products.aspx?ProductId=4) > > - - ActivePython (http://www.activestate.com/) > > - - IDLE (http://www.python.org/idle/doc/idle2.html) > > > > and depending on how you define IDEs, you can also decide whether or not > to > > include, the following > > - - emacs > > - - vim > > - - scite > > ... > > > > - -- > > _ _ _]{5pitph!r3}[_ _ _ > > __________________________________________________ > > "I'm smart enough to know that I'm dumb." > > - Richard P Feynman > > -----BEGIN PGP SIGNATURE----- > > Version: GnuPG v1.4.6 (GNU/Linux) > > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org > > > > iD8DBQFGv8DSA0th8WKBUJMRAqGcAJ9hhMp3tyS7XmBZT2+fol/A69j4jwCfXNya > > xQTmmDlDF5BAfiWkrSW3TuQ= > > =902n > > -----END PGP SIGNATURE----- > > thanks buddy, I am now using ActivePython, actually it is beyond my > expectation:) > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From half.italian at gmail.com Fri Aug 31 17:02:01 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Fri, 31 Aug 2007 21:02:01 -0000 Subject: Is there a simple way to exit a while loop on keystroke? In-Reply-To: <1188583918.747640.300850@22g2000hsm.googlegroups.com> References: <1188578827.809840.90100@r29g2000hsg.googlegroups.com> <1188581623.588967.78050@z24g2000prh.googlegroups.com> <1188583918.747640.300850@22g2000hsm.googlegroups.com> Message-ID: <1188594121.992051.47790@e9g2000prf.googlegroups.com> On Aug 31, 11:11 am, gsxg wrote: > Thanks, > The curses library doesn't look to helpful to me. However using CTRL- > C is fine and is working nicely. > > BTW, it should be "time.sleep(1)" in the example above, instead of > just > "sleep(1)" (Just in case any other newbies like me read this) > > Thanks again Depends on how you import 'time' import time time.sleep(1) from time import sleep sleep(1) ~Sean From ycoci3000 at gmail.com Tue Aug 14 02:05:23 2007 From: ycoci3000 at gmail.com (Brisingman) Date: Tue, 14 Aug 2007 06:05:23 -0000 Subject: IDLE path browser not recognizing my PYTHONPATH Message-ID: <1187071523.150365.125590@x40g2000prg.googlegroups.com> Hi, I set PYTHONPATH to /home/me/bin in bash.bashrc, however the IDLE path browser is not recognizing this. Not sure why. Grateful for any insight. Best From aahz at pythoncraft.com Sat Aug 11 09:32:42 2007 From: aahz at pythoncraft.com (Aahz) Date: 11 Aug 2007 06:32:42 -0700 Subject: Augmented assignment (was Re: Something in the function tutorial confused me.) References: <1186383024.384152.87480@l70g2000hse.googlegroups.com> Message-ID: In article , Neil Cerutti wrote: >On 2007-08-11, Alex Martelli wrote: >> Neil Cerutti wrote: >> ... >>> The Python Language Reference seems a little confused about the >>> terminology. >>> >>> 3.4.7 Emulating numeric types >>> 6.3.1 Augmented assignment statements >>> >>> The former refers to "augmented arithmetic operations", which I >>> think is a nice terminology, since assignment is not necessarily >>> taking place. Then the latter muddies the waters. >> >> Assignment *IS* "necessarily taking place"; if you try the augmented >> assignment on something that DOESN'T support assignment, you'll get an >> exception. Consider: >> >>>>> tup=([],) >>>>> tup[0] += ['zap'] >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: 'tuple' object does not support item assignment >> >> Tuples don't support item ASSIGNMENT, and += is an ASSIGNMENT, >> so tuples don't allow a += on any of their items. >> >> If you thought that += wasn't an assignment, this behavior and >> error message would be very problematic; since the language >> reference ISN'T confused and has things quite right, this >> behavior and error message are perfectly consistent and clear. > >Thanks for the correction. I was under the illusion that sometimes >augmented assignment would instead mutate the object. Although Alex is essentially correct, the situation is a bit more complex and you are correct that augmented assignment allows the object to decide whether to mutate in place. However, the critical part of Alex's point is what you need to focus on: it's the *tuple* in Alex's example that intercepts the assignment call, not the list contained in the tuple. Obviously, you can easily work around it: >>> t = ([],) >>> l = t[0] >>> l += ['foo'] >>> t (['foo'],) And this proves that you are correct about the list getting mutated in place and reflected back in the tuple. Generally speaking, augmented assignment with nested container objects is a Bad Idea IMO -- split out the bits you want to work with. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "And if that makes me an elitist...I couldn't be happier." --JMS From mobilendd at gmail.com Sun Aug 19 13:34:58 2007 From: mobilendd at gmail.com (mobilendd at gmail.com) Date: Sun, 19 Aug 2007 17:34:58 -0000 Subject: Latest models of Gibson guitars Message-ID: <1187544898.289948.322160@22g2000hsm.googlegroups.com> Reviews of latest models of best guitars, fender, gibson, yamaha, and many more, with pictures and prices. http://pro-guitars.blogspot.com/ And if you want to win a free guitar go here http://freeguitars.blogspot.com/ From sdeibel at gmail.com Thu Aug 2 11:00:40 2007 From: sdeibel at gmail.com (sdeibel at gmail.com) Date: Thu, 02 Aug 2007 08:00:40 -0700 Subject: Wing IDE for Python v. 3.0 beta1 released In-Reply-To: References: <46AF8ED7.2070206@wingware.com> <20070801212840.GA25065@spookie1.spookiegate> <496954360708011453h2a68dee4x48dcb15bb25ea717@mail.gmail.com> Message-ID: <1186066840.011817.327080@x35g2000prf.googlegroups.com> On Aug 1, 6:42 pm, John K Masters wrote: > To suggest that, because the autocompletion worked on one method of a > module and not on another was because I had not configured the > PYTHONPATH properly is at least insulting. We certainly didn't intend to be insulting. This it the most common cause of auto-completion problems but you are right that it's a mis-diagnosis on our part if it was just one method. We respond to sometimes hundreds of emails a day ,so we do make mistakes. It may be solved by using Reanalyze File from the right-click context menu on the editor but there's no gaurantee. This is incredibly complex code with many layers of highly optimized tokenizing, analysis, inference, caching, and then display in the various tools in Wing so it often takes a bit more time to find where the bug is. By the way, Wing 3.0 beta1 fixes a number of bugs that would lead to bad analysis, including missing methods as a result of failure to track edits in a file properly. It also improves reading completion info out of extension modules and properly handles several forms of import where it fell on its face previously. Hope that's useful... please let me know if not. - Stephan From eduardo.padoan at gmail.com Fri Aug 24 12:26:09 2007 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Fri, 24 Aug 2007 13:26:09 -0300 Subject: List Comprehension Question: One to Many Mapping? In-Reply-To: <1187929443.636690.287450@i13g2000prf.googlegroups.com> References: <1187929443.636690.287450@i13g2000prf.googlegroups.com> Message-ID: > For example, if I have x=[ [1,2], [3,4] ] > > What I want is a new list of list that has four sub-lists: > > [[1,2], [f(1), f(2)], [3,4], [f(3), f(4)]] [[a, [f(b) for b in a]] for a in x] From robert.kern at gmail.com Thu Aug 30 20:57:06 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 30 Aug 2007 19:57:06 -0500 Subject: strings (dollar.cents) into floats In-Reply-To: <46d75cf3$0$7698$9b4e6d93@newsspool2.arcor-online.net> References: <877incd20i.fsf@benfinney.id.au> <46d75cf3$0$7698$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Wildemar Wildenburger wrote: > Ben Finney wrote: >> You most likely do *not* want floating-point numbers for currency, >> since they rely on the operating system's binary floating point >> support which cannot accurately represent decimal fractions. > > I've heard (ok, read) that several times now and I understand the > argument. But what use is there for floats, then? When is it OK to use them? There are many, many situations where one is *not* trying to represent numbers that have nice decimal fractions or the error induced is insignificant to the problem. For example, I might take temperature readings good to 0.1 degrees Celcius. I'll type those numbers in decimal even though when I do my calculations I'll use floating point math because the error (about 1e-15 or so) is so far below the error in my measurement (about 0.1) that I won't have problems. Binary floating point has the advantage of being widely implemented and quite fast compared to decimal floating point. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From alexandre.badez at gmail.com Wed Aug 29 11:50:18 2007 From: alexandre.badez at gmail.com (Alexandre Badez) Date: Wed, 29 Aug 2007 15:50:18 -0000 Subject: What's the difference ? In-Reply-To: <1i3ljrn.nrie0r1227d9jN%aleax@mac.com> References: <1188394767.333396.129020@r29g2000hsg.googlegroups.com> <1i3ljrn.nrie0r1227d9jN%aleax@mac.com> Message-ID: <1188402618.499201.273400@50g2000hsm.googlegroups.com> Thanks for all you information. I'll continue to use 'in' instead of 'has_key' for a "faster, more concise, & readable" code (^L^ ) From stefan.behnel-n05pAM at web.de Fri Aug 3 07:23:26 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 03 Aug 2007 13:23:26 +0200 Subject: How to read information from tables in HTML? In-Reply-To: References: Message-ID: <46B3102E.10001@web.de> ZelluX wrote: > I'm confronted with some trouble when dealing with html files. > > The html files contain javascript and some information stored in tables. > And it seems that they're not well-formed, when parsed with minidom, it > will say "mismatched tag". minidom deals with XML. You're trying to read something that's (similar to) HTML. HTML is much less strict. > Then how can i get information from those files? Is there any useful > library for me? BeautifulSoup or lxml.html (which supports the BeautifulSoup parser, btw). Both can deal with broken HTML, but lxml.html has better support for cleaning up HTML (e.g. removing Javascript or embedded content, etc.) or handling forms. http://codespeak.net/lxml/ The lxml.html package is not currently in an official lxml release, but you can install it from SVN sources: http://codespeak.net/svn/lxml/branch/html/ A release is expected soon. Stefan From carsten at uniqsys.com Sat Aug 4 12:14:35 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 04 Aug 2007 12:14:35 -0400 Subject: Problems with headers in email.message In-Reply-To: <1186241903.509471.26460@d55g2000hsg.googlegroups.com> References: <1186241903.509471.26460@d55g2000hsg.googlegroups.com> Message-ID: <1186244075.3385.12.camel@dot.uniqsys.com> On Sat, 2007-08-04 at 15:38 +0000, Slippy wrote: > [...] > import smtplib, email > from email.message import Message > m = Message( ) > m['From'] = 'Slippy ' > m['To'] = 'mygroup at googlegroups.com' > m['Subject'] = 'A Test Message' > m.set_payload('This is a test email. Please ignore') > s = smtplib.SMTP('smtp.myemail.com') > failed = > s.sendmail('user at myemail.com','mygroup at googlegroups.com',str(m)) > if failed: > print 'Message sending failed.' > else: > print 'Message sent.' > print 'Bye.' > -------------Snip Here-------------Snip Here-------------Snip > Here------------- > > Now, I get all the right responses, and the message sends ok. I go and > check my inbox, and the message is there, but the From, To and Subject > lines I created (as well as a preceding blank line and a "From nobody" > line) are in the message body, followed by the body text. > > How do I assign values to the header? The way you're doing it is fine as far as assigning headers goes. My semi-educated guess is that either your mail-transfer agent or Google Groups' MTA is being confused by the "Unix From" envelope (that's the "From nobody..." you're seeing) that is included by str(m). Try m.as_string() instead, which doesn't include the Unix From envelope. I'd also like to point out that email.message is overkill for your simple use case. An email message is simply a series of headers followed by a blank line followed by the message body, which you can easily build manually if the headers aren't too long and the body is plain text: email_message = """\ From: %s To: %s Subject: %s %s""" % (email_from, email_to, email_subject, email_body) HTH, -- Carsten Haese http://informixdb.sourceforge.net From martin at v.loewis.de Mon Aug 6 02:30:43 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 06 Aug 2007 08:30:43 +0200 Subject: Setting default output encoding In-Reply-To: <871wehky9z.fsf@wilson.homeunix.com> References: <871wehky9z.fsf@wilson.homeunix.com> Message-ID: <46B6C013.8080000@v.loewis.de> > python = subprocess.Popen(["python", "myscript.py"], > stdout=subprocess.PIPE, stderr=subprocess.PIPE) > > However, this child script has sys.stdout.encoding set to None, > which means that Unicode strings cannot be printed without trouble. The automatic setting of .encoding is only done when the output is a terminal. If you write to a file, or a pipe, Python's guess as to what the encoding of that stream is might be easily wrong. If you want to be able to write Unicode strings to stdout always, it's best to wrap stdout with the result of codecs.getwriter. If you want to use the user's locale as the encoding, use locale.getpreferredencoding(). Regards, Martin From bj_666 at gmx.net Thu Aug 30 03:08:19 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Aug 2007 07:08:19 GMT Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> Message-ID: <5jn8n3FdmbcU1@mid.uni-berlin.de> On Wed, 29 Aug 2007 23:44:33 -0700, zzbbaadd wrote: > What's with the index() function of lists throwing an exception on not > found? Let's hope this is rectified in Python 3. If nothing else, add > a function that doesn't throw an exception. There are a million > situations where you can have an item not be in a list and it is not > an exception situation. Write such a function yourself, it is quite easy after all. I very seldom use the `list.index()` method. What do your millions situations look like? Maybe there is a better data structure than lists for those situations!? Ciao, Marc 'BlackJack' Rintsch From aboudouvas at panafonet.gr Fri Aug 10 06:49:36 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Fri, 10 Aug 2007 03:49:36 -0700 Subject: Question about properties. In-Reply-To: <1186742730.729034.256800@i13g2000prf.googlegroups.com> References: <1186741289.074717.174370@e16g2000pri.googlegroups.com> <5i2t7dF3kqc46U3@mid.uni-berlin.de> <1186742730.729034.256800@i13g2000prf.googlegroups.com> Message-ID: <1186742976.758800.102090@q3g2000prf.googlegroups.com> Maybe is just a writers' "play" and nothing else. From Graham.Dumpleton at gmail.com Sun Aug 26 07:19:54 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 26 Aug 2007 11:19:54 -0000 Subject: Python error on Mac In-Reply-To: References: Message-ID: <1188127194.110057.321140@x40g2000prg.googlegroups.com> On Aug 26, 12:58 pm, Clover wrote: > When trying to do some things on my Mac (starting Lyx, compiling Latex > via TextMate) I get this error: > > python: execv: > /Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python: > No such file or directory > > I (and people on Lyx and TextMate lists) are at a complete loss as to > why this is happening. I didn't (at least intentionally) fiddle with > Python setup. The default operating system supplied version of Python on recent versions of MacOS X is 2.3.5. Unless you have specifically installed 2.5, it will not exist. So, if those applications have it hardwired to use Python 2.5 they will not work. Graham From james.pingenot at gmail.com Wed Aug 22 15:23:36 2007 From: james.pingenot at gmail.com (james.pingenot) Date: Wed, 22 Aug 2007 19:23:36 -0000 Subject: libgmail failure In-Reply-To: References: <1187730447.621592.93740@q4g2000prc.googlegroups.com> Message-ID: <1187810616.747944.290720@i38g2000prf.googlegroups.com> On Aug 22, 10:26 am, James Stroud wrote: > james.p.n... at gmail.com wrote: > > Hey all, > > > I've been using libgmail to send out automated notification emails for > > my company's nightly regression testing. Last night these emails > > started failing, though the python code has not changed. I updated to > > the latest libgmail, but that isn't helping. I've logged in to the > > email account directly, and the account is still working fine. > > > The error I get is "HTTP Error 400: Bad Request" when using > > gmailAccount.login(). This doesn't throw an exception, just prints > > the error. The code crashes outright when it tries to send mail. > > > This code has been up and running for several months and just started > > failing last night. Does anyone have an idea what's going on? > > > The code and error follow (fairly short :-) > > > Thanks much, > > James > > Have you thought about spoofing explorer? Always spoof explorer. > > James I have not heard of this. How do you spoof IE for libgmail? Thanks, James From llothar at web.de Fri Aug 31 21:16:57 2007 From: llothar at web.de (llothar) Date: Fri, 31 Aug 2007 18:16:57 -0700 Subject: How to find out if the interpreter is a debug build? Message-ID: <1188609417.273513.74450@i13g2000prf.googlegroups.com> How can i find out if a selected python interpreter (i only know the path name under which i should start it) is a debug build? I tried sys.api_version, sys.platform, sys.version, sys.version_info and there is no difference between "python.exe" and "python_d.exe". I'm pretty sure the information is stored somewhere but i can't find it. Please help. From kyosohma at gmail.com Thu Aug 9 13:51:50 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 09 Aug 2007 10:51:50 -0700 Subject: how to get command output using python In-Reply-To: References: Message-ID: <1186681910.789048.132140@z24g2000prh.googlegroups.com> On Aug 9, 12:01 pm, Arnau Sanchez wrote: > Steven Harms escribi?: > > > In python it is quite easy: > > > import commands > > status, output = commands.getstatusoutput("my command") > > Uhm, this module has a big issue: > > (http://docs.python.org/lib/module-commands.html) > ---- > 8.17 commands -- Utilities for running commands > > Availability: Unix. > ---- > > Any non cross-platform module should be avoided unless absolutely necessary. > > Subprocess is the right module to use. > > arnau You forgot to mention that subprocess replaces commands, so in effect, commands is deprecated anyway. Mike From dzjoost at gmail.com Tue Aug 14 19:39:18 2007 From: dzjoost at gmail.com (Joost Molenaar) Date: Wed, 15 Aug 2007 01:39:18 +0200 Subject: FM synthesis using Numpy Message-ID: <3657a8860708141639l7e90ebdoe844691627152e40@mail.gmail.com> Hello fellow Python coders, I'm trying to build a simple FM synthesizer in Python. As a beginner, I take 'FM synthesizer' to mean: "using a sine wave to control the frequency of another sine wave." I tried to generate a tone of 1000 Hz that deviates 15 Hz six times a second. The start of the resulting wave file sounds right, i.e., a vibrato effect can be heard. After a second or so, the vibrato becomes more and more extreme, as if the modulating oscillator's amplitude is rising over time. I suspect that I am misunderstanding the math. I tried a couple of things: - removing the factor 2 * num.pi from either of the oscillators does not fix it, besides, doing so is even more wrong because numpy.sin works with radians - using a higher sampling frequency makes no difference - making t run from 0 to 1 each second (t %= 1) causes a clipping of the sound, so this seems wrong too - the problem is not related to Numpy, because the effect also happens in pure-Python implementations of my bug As you can see, I'm at a loss and am even trying incorrect bugfixes. Any help would be very welcome. Thanks for your time, Joost Molenaar [I left out a writewavheader function to aid brevity] ------------------------------------------------------------------- import numpy as num def oscillator(x, freq=1, amp=1, base=0, phase=0): return base + amp * num.sin(2 * num.pi * freq * x + phase) def writewav(filename, data): wave = open(filename, 'wb') # .wav header: 30 s at 44100 Hz, 1 channel of 16 bit signed samples wave.write('RIFF\x14`(\x00WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00D' '\xac\x00\x00\x88X\x01\x00\x02\x00\x10\x00data\xf0_(\x00') # write float64 data as signed int16 (32767 * data).astype(num.int16).tofile(wave) wave.close() t = num.arange(0, 30, 1./44100) freq = oscillator(t, freq=6, amp=15, base=1000) tone = oscillator(t, freq=freq, amp=0.1) writewav('spam.wav', tone) ------------------------------------------------------------------- From jquinn+google at cs.oberlin.edu Mon Aug 20 17:01:59 2007 From: jquinn+google at cs.oberlin.edu (jquinn+google at cs.oberlin.edu) Date: Mon, 20 Aug 2007 14:01:59 -0700 Subject: Pattern for error checking easiest-first? Message-ID: <1187643719.772672.70780@w3g2000hsg.googlegroups.com> Heres the situation: class AbstractThing(): def changeMe(self,blah): if blah < 1: raise MyException self.blah = blah class NetworkedThing(AbstractThing): def changeMe(self,blah): if blah > self.getUpperLimitOverTheNetworkSlowly: raise MyOtherException AbstractThing.changeMe(self,blah) The problem is that code like this does error checking backwards. A call to NetworkedThing.changeMe will first do a slow error check and then a fast one. Obviously there are various ways to get around this - either have the subclass explicitly ask the superclass to error check first, or vice totally versa. Is there some accepted pattern/idiom for handling this issue? From pyth0nc0d3r at gmail.com Thu Aug 23 16:55:54 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Thu, 23 Aug 2007 15:55:54 -0500 Subject: How would I go about making a file open. Not the way you might think. In-Reply-To: References: Message-ID: I've completed this request and I got the answer already. On 8/23/07, Larry Bates wrote: > > Hendrik van Rooyen wrote: > > Lamonte Harris wrote: > > > >> Basically you can open a file by double clicking, and by default it > would open > > w/ what every program you have it set >to. Most text files would open > in > > notepad. How can I make a txt open so that notepad opens w/ the content > in it > > by >using just python. > > > > I asked this question just yesterday - and Tim Golden answered: > > > > os.startfile() > > > > - Hendrik > > > Actually os.startfile('filename.txt') will open the file with whatever > application is associated with .txt files on that machine. That could be > different from notepad if the user has chosen to override the defaults. > > os.system('notepad.exe c:\\junk.txt') > > will force notepad.exe to load and it will load the file specified. > > All depends on what you want to do. > > -Larry > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Wed Aug 29 09:22:16 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 29 Aug 2007 09:22:16 -0400 Subject: handling tabular data in python--newbie question In-Reply-To: <6cf42$46d56771$839b8704$5034@news1.tudelft.nl> References: <6cf42$46d56771$839b8704$5034@news1.tudelft.nl> Message-ID: hyena wrote: > Hi, > Just jump in python few days. I am wondering how to store and index a > table in python effectively and easily.I think the basic data types are not > very straight foward to handle a table (eg, from csv or data base.) > > I have a csv file, the first row of it is column names and the rest rows > are data. There are some tens of columns and hundreds rows in the file. I am > planning to use the column names as variables to access data, currently I am > thinking of using a dictionary to store this file but did not figure out a > elegant way to start. > > Any comments and suggestions are wellcomed. Please forgive me if this > question is too naive , and yes, I did search google a while but did not > find what I want. > > Thanks > > One way would be to store each row as a dictionary. Suppose your data file is called "myfile.txt" and, for simplicity, that columns are separated by whitespace. Please note the following code is untested. f = open("myfile.txt", "r") names = file.next().split() So now names contains a list of the field names you want to use. Let's store the rows in a dictionary of dictionaries, using the first column to index each row. rows = {} for line in file: cols = line.split() rdict = dict(zip(names, cols)) rows[cols[0]] = rdict dict(zip(names, cols)) should create a dictionary where each field is stored against its column name. I assume that cols[0] is unique for each row, otherwise you will suffer data loss unless you check for that circumstance. You can check this kind of thing in the interactive interpreter: >>> names = ["first", "second", "third"] >>> dict(zip(names, [1, 2, 3]) ... ) {'second': 2, 'third': 3, 'first': 1} >>> Another alternative, however, would be to create an object for each row where the columns are stored as attributes. This approach would be useful if the column names are predictable, but rather less so if each of your data files were to use different column names. Let us know and if appropriate someone can point you at the "bunch" class. Welcome to Python! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From paul.nospam at rudin.co.uk Fri Aug 10 00:41:27 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Fri, 10 Aug 2007 05:41:27 +0100 Subject: Puzzled by "is" References: <20070809194105.39BD11E400A@bag.python.org> Message-ID: <87bqdg80i0.fsf@rudin.co.uk> John K Masters writes: > > OK fiddling around with this and reading the docs I tried:- > a = 'qqqqqqqqqq' #10 q's > b = 'qqqqqqqqqq' #10 q's > a is b > true > c = 'q' * 10 > c > 'qqqqqqqqqq' #10 q's > d = 'q' * 10 > d > 'qqqqqqqqqq' #10 q's > c is d > false > > So from what I've read "==" tests for equivalence, "is" tests for identity but > that does not explain the behaviour above. > There's nothing especially to be explained, other than "that's the way the compiler does it". Two equal string literals might be the same object or they might not be. It's a language implementation detail. From nospam.themindstorm at gmail.com Wed Aug 1 04:40:16 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Wed, 1 Aug 2007 08:40:16 +0000 (UTC) Subject: Where do they tech Python officialy ? References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> <1185265091.276958.239910@r34g2000hsd.googlegroups.com> <1i23wyk.avc945i4dwsiN%aleax@mac.com> Message-ID: aleax at mac.com (Alex Martelli) wrote in news:1i23wyk.avc945i4dwsiN% aleax at mac.com: > NicolasG wrote: > ... >> The problem is that I would like to work as a Python programmer but >> all the job vacancies I can find requires a couple of years of >> professional experience ... that I don't have. How a wanna be >> programmer can start working as a programmer if there is no chance to >> start from somewhere ? That's the reason I created this topic. > > Open source projects do not require previous professional experience to > accept volunteers. So, one way out of your dilemma is to make a name > for yourself as an open source contributor -- help out with Python > itself and/or with any of the many open source projects that use Python, > and you will both learn a lot _and_ acquire "professional experience" > that any enlightened employer will recognize as such. It depends :-). In my experience I met employers being concerned by my implication in the oss world :-). > That will take a > while, but not as long as getting a college degree (and it will be far > cheaper than the degree). > I don't know much about the open community in Python world, but in Java world becoming a project member may be more difficult than getting a degree (or close to :-)) ). bests, ./alex -- .w( the_mindstorm )p. From tamim.shahriar at gmail.com Tue Aug 21 06:01:45 2007 From: tamim.shahriar at gmail.com (subeen) Date: Tue, 21 Aug 2007 10:01:45 -0000 Subject: C# and Python Message-ID: <1187690505.903506.79690@d55g2000hsg.googlegroups.com> Hi, I am a newcomer in Python. I am going to write a small Python application that will run in windows xp. This application needs to have GUI. Is it possible to make a C# application using visual studio 2005 that will call the python scripts? Let me explain more here: My program will generate a text file of 100 - 100000 random integers, and sort those using various sorting methods. Now I have written separate sorting scripts in Python (quick sort, insertion sort etc.). But I want to write the GUI and number generation program in C#.net. When the user clicks Quick Sort button, the quicksort.py will be called and it will sort the numbers. regards, Subeen From goldtech at worldpost.com Sat Aug 4 17:43:59 2007 From: goldtech at worldpost.com (goldtech) Date: Sat, 04 Aug 2007 14:43:59 -0700 Subject: Client-side HTML form processing with Python? Message-ID: <1186263839.778333.143200@d30g2000prg.googlegroups.com> I want to have an HTML form from a local local html file write a text field's data to a local text file. I have no client or server side tools like PHP, JAVA. I don't know JavaScript. I can not add anything to the workstation I am using. It's going to have to be a client-side solution - there's no CGI on the server, no PHP. It's XP with MS-Office, so I guess I have the usual active-x, and I have Python 2.1. Is there a way? Thanks, Lee G. From martin at v.loewis.de Mon Aug 13 13:51:58 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 13 Aug 2007 19:51:58 +0200 Subject: Python in Chinese In-Reply-To: <1187026857.622808.80470@19g2000hsx.googlegroups.com> References: <1187026857.622808.80470@19g2000hsx.googlegroups.com> Message-ID: <46C09A3E.4040309@v.loewis.de> Paul McGuire schrieb: > Back in May, there was quite an extensive discussion of whether or not > Python should support Unicode identifiers (with the final result being > that this would be supported in Python 3). In my periodic googling > for pyparsing users, I stumbled upon Zhpy, a preprocessor that renders > on the fly Chinese Python keywords and indentifiers written using > traditional Chinese characters into ASCII counterparts, and then > executes the resulting script. Interesting! Notice what they do to the identifiers - when translating to "English", the just number them. I wonder what this will do to backtraces, cross-module imports, and such... With Python 3, they can restrict themselves to just translating keywords, and leave all identifiers in place. Regards, Martin From steve at holdenweb.com Fri Aug 17 02:05:01 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 17 Aug 2007 02:05:01 -0400 Subject: using super() to call two parent classes __init__() method In-Reply-To: <1187328619.039289.244900@g4g2000hsf.googlegroups.com> References: <1187328619.039289.244900@g4g2000hsf.googlegroups.com> Message-ID: 7stud wrote: > When I run the following code and call super() in the Base class's > __init__ () method, only one Parent's __init__() method is called. > > > class Parent1(object): > def __init__(self): > print "Parent1 init called." > self.x = 10 > > class Parent2(object): > def __init__(self): > print "Parent2 init called." > self.y = 15 > > class Base(Parent1, Parent2): > def __init__(self): > super(Base, self).__init__() > self.z = 20 > > b = Base() > > --output:-- > Parent1 init called. > If you want super() to work for you then all your classes have to use it. There is only one call to an __init__() method in your definitions - Parent1 and Parent2 should also be calling their super().__init__(). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From kyosohma at gmail.com Fri Aug 3 15:15:35 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 03 Aug 2007 12:15:35 -0700 Subject: downloading files In-Reply-To: <1186166920.757662.269340@o61g2000hsh.googlegroups.com> References: <1186166920.757662.269340@o61g2000hsh.googlegroups.com> Message-ID: <1186168535.345161.325580@j4g2000prf.googlegroups.com> On Aug 3, 1:48 pm, Ehsan wrote: > I foundd this code in ASPN Python Cookbook for downloading files in > python but when it finished downloading files the files became > corrupted and didn't open, the files in internet havn't any problem: > > def download(url,fileName): > """Copy the contents of a file from a given URL > to a local file. > """ > import urllib > webFile = urllib.urlopen(url) > localFile = open(fileName, 'w') > localFile.write(webFile.read()) > webFile.close() > localFile.close() > download('http://www.2shared.com/download/1839752/cd520048/ > xpersia14.3gp?tsid=20070803-143313-49566ea2', 'xpersia4.3gp' ) Uhhh...you probably need to change the open() command to binary mode. Replace that line with this: localFile = open(fileName, mode='wb') I tried it on my PC to download a photo from one of my sites and it worked great. Mike From sjmachin at lexicon.net Fri Aug 31 20:29:48 2007 From: sjmachin at lexicon.net (John Machin) Date: Fri, 31 Aug 2007 17:29:48 -0700 Subject: Python Unicode to String conversion In-Reply-To: References: <1188600916.528901.189680@d55g2000hsg.googlegroups.com> Message-ID: <1188606588.808009.10150@r23g2000prd.googlegroups.com> On Sep 1, 9:56 am, "Chris Mellon" wrote: > On 8/31/07, thijs.br... at gmail.com wrote: > > > Hi everyone, > > > I'm having quite some troubles trying to convert Unicode to String > > (for use in psycopg, which apparently doesn't know how to cope with > > unicode strings). > > > The error I keep having is something like this: > > ERREUR: S?quence d'octets invalide pour le codage ?UTF8? : 0xe02063 > > > (sorry, locale is french, it means "byte sequence invalid for encoding > > <>", the value is probably an e with one of the french accents) > > > I've found lots of stuff about this googling the error, but I don't > > seem to be able to find a "works always"-function just to convert a > > unicode variable back to string... > > encode(). > > You didn't post the code that was failing, I can encode that value > into UTF-8 What is "that value"? (1) unichr(0xe02063)? You must have a wide unicode build of Python ... (2) u"\xe0\x20\x63"? Of course you can encode it; so what? > (and unless I'm very much mistaken, you should be able to > encode any unicode string to UTF-8). That is true, by definition. However you are barking this truism up the wrong tree. The unknown complainant's whinge is that it is expecting a sequence of octets (an 8-bit string) that is valid UTF8, but the actuality is something else. It is *NOT* trying to say that a unicode input can't be converted to UTF8. From bignose+hates-spam at benfinney.id.au Tue Aug 28 19:02:09 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 29 Aug 2007 09:02:09 +1000 Subject: Check for dict key existence, and modify it in one step. References: <1188311810.226363.295500@w3g2000hsg.googlegroups.com> Message-ID: <87bqcrfeku.fsf@benfinney.id.au> rodrigo writes: > Im using this construct a lot: > > if dict.has_key(whatever): > dict[whatever] += delta > else: > dict[whatever] = 1 I'd prefer: foo.setdefault(whatever, 0) foo[whatever] += delta > sometimes even nested: > > if dict.has_key(whatever): > if dict[whatever].has_key(someother): > dict[whatever][someother] += delta > else: > dict[whatever][someother] = 1 > else: > dict[whatever]={} > dict[whatever][someother] = 1 foo.setdefault(whatever, {}) foo[whatever].setdefault(someother, 0) foo[whatever] += delta > there must be a more compact, readable and less redundant way to do > this, no? Hope that helps. -- \ "I took a course in speed waiting. Now I can wait an hour in | `\ only ten minutes." -- Steven Wright | _o__) | Ben Finney From paddy3118 at googlemail.com Wed Aug 8 13:38:40 2007 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 08 Aug 2007 17:38:40 -0000 Subject: This bit of code hangs Python Indefinitely In-Reply-To: References: Message-ID: <1186594720.330941.221440@d55g2000hsg.googlegroups.com> > You could possibly make a case that before Queue.put blocks it should check > whether the program has more than just the one thread and if not it should > raise an RTFMException. Cute :-) From sawveq at gmail.com Fri Aug 31 03:51:38 2007 From: sawveq at gmail.com (SAWVEQ) Date: Fri, 31 Aug 2007 07:51:38 -0000 Subject: Requirement-HEAD OF TECHNOLOGY Message-ID: <1188546698.143237.147060@m37g2000prh.googlegroups.com> Senior Position Vacant for www.123greetings.com Head of Technology (Kolkata, India) Responsibilities: To Scale the website to handle large volumes of user traffic. To lead the development team for Alexa Top 100 Web Property. To Manage Relationships with DataCenters, CDN/Bandwidth providers, ESP's etc. To Implement next generation of web technologies. Deliverables Increase User Access Speed of the Website * Implement Distributed DNS * Implement Web Catching/Acceleration Increase Website Uptime * Implement Load Balancing to handle 600 web servers * Manage servers spread across 5 Datacenters in 3 geographies * Implement Blade Servers/Web Farm Website Management * Improve Content Management System to update 50,000 WebPages daily. Website Features * Implement Web 2.0 Features to increase stickiness of the website. * Implement latest flash & streaming technologies for content delivery. Data Mining & Warehousing * To Collect & Store huge volumes of user data. * To Structure & Mine user data for trend, data analysis. Requirements: Profile Exp:-10Years In related field Required to manage & lead the development team consist of PHP & Perl Programmers, Project Managers, Action Script Developers, JavaScript Developers, Server Administrators. Website Technologies Operating Systems: Linux /Apache/FreeBSD; No Microsoft Technologies Development Languages: Open Source Technologies (Perl/PHP/MySQL) Front End languages: JavaScript, AJAX, HTML, CSS, Flash ActionScript Developers. Interested Candidate plz contact - souvik.mukherjee at itlindia.com or visit http://www.123greetings.com/careers/form.html for more details From aleax at mac.com Mon Aug 27 00:07:26 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 26 Aug 2007 21:07:26 -0700 Subject: beginner, idiomatic python References: <13cqlqbbpn0dmea@corp.supernews.com> <1187898049.734696.9500@l22g2000prc.googlegroups.com> <13csi2tn49esmc3@corp.supernews.com> <13csqk47j0c56b0@corp.supernews.com> <13ct7v3qn2v5206@corp.supernews.com> <13d00hu2mflt01b@corp.supernews.com> <13d4bn9kchd9u94@corp.supernews.com> Message-ID: <1i3h19b.1yiv6tjnazk9iN%aleax@mac.com> bambam wrote: ... > Bags don't seem to be built in to my copy of Python, and A "bag" is a collections.defaultdict(int) [[you do have to import collections -- it's in the standard library, NOT built-in]]. Alex From hortitude at gmail.com Sun Aug 19 23:58:38 2007 From: hortitude at gmail.com (hortitude at gmail.com) Date: Mon, 20 Aug 2007 03:58:38 -0000 Subject: popen4 not returning output Message-ID: <1187582318.054450.76960@z24g2000prh.googlegroups.com> I am trying to run the following script: #!/usr/bin/python import popen2 commandToRun = """scp scp_trial.py user at host:/targetDirectory""" #commandToRun = "ls" print commandToRun p_out, p_in = popen2.popen4 (commandToRun) theOut = p_out.readlines () print theOut When I run this command with the "ls" command I see the output. When I run this with the scp command I do not see the output of my command -- however the file is successfully transfered. How can I see the output? Thanks From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Aug 11 17:40:45 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 11 Aug 2007 23:40:45 +0200 Subject: python 2.5 bug References: <1186825286.493878.80380@l70g2000hse.googlegroups.com> <5i5fktF3ml00gU1@mid.uni-berlin.de> <1186826980.346619.287670@r34g2000hsd.googlegroups.com> <46bdfb3f$0$5102$ba4acef3@news.orange.fr> Message-ID: <5i6omtF3mr9f4U3@mid.individual.net> Thorsten Kampe wrote: > Yeah. Did the Original Poster mention any details about his > problem. Like - for instance - that he's using Windows? Don't you know the empiric law of platforms? :) "Users who ask about OS specific problems and not state their platform are Windows users." Regards, Bj?rn -- BOFH excuse #284: Electrons on a bender From stefan.behnel-n05pAM at web.de Wed Aug 29 12:44:34 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 29 Aug 2007 18:44:34 +0200 Subject: replacing xml elements with other elements using lxml In-Reply-To: <1188399381.188639.289480@57g2000hsv.googlegroups.com> References: <1188399381.188639.289480@57g2000hsv.googlegroups.com> Message-ID: <46D5A272.2000509@web.de> Ultrus wrote: > I'm attempting to generate a random story using xml as the document, > and lxml as the parser. I want the document to be simplified before > processing it further, and am very close to accomplishing my goal. > Below is what I have so far. Any ideas on how to move forward? > > The goal: > read and edit xml file, replacing random elements with randomly picked > content from within > > Completed: > [x] read xml > [x] access first random tag > [x] pick random content within random item > [o] need to replace tag with picked contents > > xml sample: > Here is some content. > > Here is some random content. > Here is some more random content. > > Here is some content. Hmm, this is not well-formed XML, so I assume you stripped the example. The root element is missing. > Python code: > from lxml import etree > from StringIO import StringIO > import random > > theXml = "Here is some content. contents>Here is some random content. contents>Here is some more random content. contents>Here is some content." > > f = StringIO(theXml) > tree = etree.parse(f) ^^^^^ This would raise an exception if the above really *was* your input. > r = tree.xpath('//random') > > if len(r) > 0: > randInt = random.randInt(0,(len(r[0]) - 1)) > randContents = r[0][randInt][0] > #replace parent random tag with picked content here > > now that I have the contents tag randomly chosen, how do I delete the > parent tag, and replace it to look like this: > > final xml sample (goal): > Here is some content. > Here is some random content. > Here is some content. what about: r.getparent().replace(r, random.choice(r)) ? Stefan From james.p.news at gmail.com Tue Aug 21 17:07:27 2007 From: james.p.news at gmail.com (james.p.news at gmail.com) Date: Tue, 21 Aug 2007 21:07:27 -0000 Subject: libgmail failure Message-ID: <1187730447.621592.93740@q4g2000prc.googlegroups.com> Hey all, I've been using libgmail to send out automated notification emails for my company's nightly regression testing. Last night these emails started failing, though the python code has not changed. I updated to the latest libgmail, but that isn't helping. I've logged in to the email account directly, and the account is still working fine. The error I get is "HTTP Error 400: Bad Request" when using gmailAccount.login(). This doesn't throw an exception, just prints the error. The code crashes outright when it tries to send mail. This code has been up and running for several months and just started failing last night. Does anyone have an idea what's going on? The code and error follow (fairly short :-) Thanks much, James Code: ------------------------------------------------------------------------------------------------------- def send(TO_LIST,SUBJECT,MESSAGE): GA = libgmail.GmailAccount("xxxxxx at gmail.com","xxxxxxx") try: print "Logging in" GA.login() except libgmail.GmailLoginFailure: print "\nLogin failed. (Wrong username/password?)" else: print "Log in successful.\n" for RX in TO_LIST: MSG = libgmail.GmailComposedMessage(RX,SUBJECT,MESSAGE) if GA.sendMessage(MSG): print "Message successfully sent to `%s` ." % RX else: print "Could not send message." ------------------------------------------------------------------------------------------------------- Output: ------------------------------------------------------------------------------------------------------- Logging in HTTP Error 400: Bad Request Log in successful. No messages found Traceback (most recent call last): File "C:\projects\physware\testCases\PythonTestScripts \SendEmail.py", line 58, in main() File "C:\projects\physware\testCases\PythonTestScripts \SendEmail.py", line 55, in main send(TO_LIST,SUB,MSG) File "C:\projects\physware\testCases\PythonTestScripts \SendEmail.py", line 39, in send if GA.sendMessage(MSG): File "C:\projects\physware\testCases\PythonTestScripts\libgmail.py", line 588, in sendMessage U_ACTION_TOKEN: self._getActionToken(), File "C:\projects\physware\testCases\PythonTestScripts\libgmail.py", line 563, in _getActionToken at = self._cookieJar._cookies[ACTION_TOKEN_COOKIE] KeyError: 'GMAIL_AT' ------------------------------------------------------------------------------------------------------- From larry.bates at websafe.com Tue Aug 14 08:06:06 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 14 Aug 2007 07:06:06 -0500 Subject: Drawing a graph In-Reply-To: References: Message-ID: <46C19AAE.4010009@websafe.com> Ghirai wrote: > Hello list, > > I need to draw a graph, 2 axes, 2D, nothing fancy. > One of the axes is time, the other one is a series of integers. > > I don't care much about the output format. > > Are there any specialized libraries for this, or should i use PIL? > > Thanks. > ReportLab graphics works for me. www.reportlab.org -Larry From siona at chiark.greenend.org.uk Thu Aug 9 11:51:01 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 09 Aug 2007 16:51:01 +0100 (BST) Subject: Help with Dictionaries and Classes requested please. References: <46bacae3$0$89254$7b0f0fd3@mistral.news.newnet.co.uk> <46bacf1b$0$54289$7b0f0fd3@mistral.news.newnet.co.uk> <87ejic6dkw.fsf@benfinney.id.au> <46bb19e2$0$9835$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <59o*53SRr@news.chiark.greenend.org.uk> special_dragonfly wrote: > if key in FieldsDictionary: > FieldsDictionary[key].append(FieldClass(*line.split(","))) > else: > FieldsDictionary[key]=[FieldClass(*line.split(","))] These four lines can be replaced by: FieldsDictionary.setdefault(key, []).append(FieldClass(*line.split(","))) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From hniksic at xemacs.org Tue Aug 21 09:34:41 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 21 Aug 2007 15:34:41 +0200 Subject: File Read Cache - How to purge? References: <1187669203.698637.81990@i38g2000prf.googlegroups.com> Message-ID: <87veb9xb7y.fsf@mulj.homelinux.net> Signal writes: > 2. Is there anyway to somehow to take advantage of this "caching" by > initializing it without reading through the entire file first? > > 3. If the answer to #2 is No, then is there a way to purge this > "cache" in order to get a more accurate result in my routine? That > is without having to read another large file first? On a Unix system the standard way to purge the cache is to unmount the file system and remount it. If you can't do that on Windows, you can get the same effect by placing the test files on an external (USB) hard drive; unplugging the drive and plugging it back again will almost certainly force the OS to flush any associated caches. Having to do that is annoying, even as a last resort, but still better than nothing. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Aug 7 06:22:11 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 07 Aug 2007 12:22:11 +0200 Subject: Global package variable, is it possible? In-Reply-To: <1186438575.861738.173900@g12g2000prg.googlegroups.com> References: <1186160415.065108.139160@e9g2000prf.googlegroups.com> <46b6d0b4$0$29273$426a74cc@news.free.fr> <1186438575.861738.173900@g12g2000prg.googlegroups.com> Message-ID: <46b847bb$0$1940$426a74cc@news.free.fr> Chris Allen a ?crit : > On Aug 6, 12:41 am, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> Chris Allen a ?crit : >> (snip) >> Hi Chris... >> I've read all the thread, and it seems that your problem is mostly to >> share a single dynamic state (the config) between several modules. So I >> do wonder: have you considered the use of the Singleton pattern (or one >> of it's variants...) ? > > Thanks, I don't know anything about python singletons. It's a design pattern, so it's not realluy language specific. I thought about this because some of your wordings in various posts in this thread clearly called for such a pattern, but Ben is right, it won't probably buy you more than a plain python module (which are one of the possible implementations of the Singleton pattern). From pyth0nc0d3r at gmail.com Mon Aug 27 23:42:01 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Mon, 27 Aug 2007 22:42:01 -0500 Subject: Asking all python programmers. Message-ID: Okay, I know you've guys told me millions of times to read the manual I've read a lot of it. What do you recommend studying the most? Python is my goal for the next year in the half. :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Wed Aug 8 23:03:00 2007 From: http (Paul Rubin) Date: 08 Aug 2007 20:03:00 -0700 Subject: Issues of state (was: Tkinter or wxpython?) References: <7x8x8mpn37.fsf@ruckus.brouhaha.com> Message-ID: <7xfy2t8l5n.fsf@ruckus.brouhaha.com> claird at lairds.us (Cameron Laird) writes: > Others have answered this at other levels. In elementary terms, > there truly is a difference, Paul, and one that's widely reified: > a "desktop client-server" application typically listens through > one socket, which therefore constitutes an index of the connection > or client, while a Web application communicates through a sequence > of independent HTTP transactions. The latter can manage state only > to the extent it passes session information around. Is this significant? In the case of a single user http app running on the same computer as the browser, the server should only listen on 127.0.0.1. Every http hit then almost certainly comes from the same session. If there's doubt, the app can always set a random cookie at the initial screen and check that the cookie never changes. If there's only a small amount of session state (say up to a few hundred bytes) you can put it entirely into browser cookies and send it on every single http hit.